@promptctl/cc-candybar 1.180.6 → 1.180.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +59 -59
- package/package.json +5 -5
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
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 from"node:os";import{spawn as s,spawnSync as c}from"node:child_process";import l,{closeSync as u,constants as d,existsSync as f,fstatSync as p,linkSync as m,mkdtempSync as h,openSync as g,readFileSync as _,readSync as v,rmSync as y,statSync as b,writeFileSync as x}from"node:fs";import{StringDecoder as S}from"node:string_decoder";import{inspect as C,parseArgs as w,types as ee}from"node:util";import{clearImmediate as T,setImmediate as te}from"node:timers";import E,{basename as ne,dirname as D,isAbsolute as re,join as ie,sep as O}from"node:path";import ae,{createHash as oe,createHmac as se,randomBytes as ce,randomUUID as le,timingSafeEqual as ue}from"node:crypto";import de from"node:net";import fe from"node:v8";import{open as pe,readFile as me,readdir as he,stat as ge}from"node:fs/promises";import{get as _e}from"node:https";import{WriteStream as ve}from"node:tty";import{createInterface as ye}from"node:readline";var be=Object.create,xe=Object.defineProperty,Se=Object.getOwnPropertyDescriptor,Ce=Object.getOwnPropertyNames,we=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty,Ee=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),De=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ce(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Te.call(e,s)&&s!==n&&xe(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Se(t,s))||r.enumerable});return e},Oe=(e,t,n)=>(n=e==null?{}:be(we(e)),De(t||!e||!e.__esModule?xe(n,`default`,{value:e,enumerable:!0}):n,e));let ke=!1;const Ae=()=>ke;function je(e){ke=e}function Me(e){return Ae()?`[DEBUG] ${e()}\n`:``}function k(e,...t){Ae()&&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);function Fe(e,t){return ee.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!f(t)?`working directory does not exist: ${t}`:e.message:String(e)}const Ie={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function Le(e,t,n){let r=Ie[t];if(r===void 0)return{allowed:!0};let i=e.get(t);if(i===void 0)return{allowed:!0};let a=n-i;return a>=r?{allowed:!0}:{allowed:!1,minIntervalMs:r,sinceLastMs:a}}function Re(e,t){return{...e.inherited,...t.envOverlay}}const ze=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function Be(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 Ve(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function He(e,t,n){let r=Ue(e,t,n);return r===null?(e.lastStartAt.set(t,e.scope.clock.now()),null):(e.scope.stats?.onRefused(t),r)}function Ue(e,t,n){if(e.scope.signal.aborted)return ze(e.scope.signal);if(n?.aborted)return ze(n);let r=Le(e.lastStartAt,t,e.scope.clock.now());return r.allowed?null:Be(t,r.minIntervalMs,r.sinceLastMs)}const We=`\$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 Ge(e,t){t!==e.fault&&(e.fault=t,e.scope.observeLifeline(t))}function Ke(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),Ge(e,n))}function qe(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 Je(e){let{stats:t,clock:n}=e.scope;t?.onStart(`lifeline`);let r=n.now(),i;try{i=s(`awk`,[We],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(i){return t?.onEnd(`lifeline`,n.now()-r),Ge(e,`did not start: ${Fe(i,void 0)}`),null}t?.onEnd(`lifeline`,n.now()-r);let a=i.stdin;if(a==null)return i.once(`error`,t=>Ge(e,`did not start: ${t.message}`)),null;i.once(`spawn`,()=>{e.lifeline?.process===i&&Ge(e,null)}),i.once(`error`,t=>Ke(e,i,`failed: ${t.message}`)),i.once(`exit`,(t,n)=>Ke(e,i,`exited ${n??t}`)),a.on(`error`,t=>Ke(e,i,`pipe failed: ${t.message}`)),Ve(e,new Promise(e=>i.once(`close`,e))),i.unref(),a.unref();for(let t of e.liveGroups)a.write(`+ ${t}\n`);return{process:i,pipe:a}}function Ye(e,t){e.liveGroups.add(t),e.lifeline??=Je(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function Xe(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function Ze(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}function Qe(e,t){try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!$e(e)))throw t}}function $e(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}function et(e){let t=new S(`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 tt(e,t){let{stats:n,clock:r}=e.scope,i=He(e,t.category,t.signal);if(i!==null)return i;let a=r.now();return n?.onStart(t.category),new Promise(i=>{let o;try{o=s(t.bin,t.args??[],{cwd:t.cwd,env:Re(e.scope,t),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(e){n?.onEnd(t.category,r.now()-a),i({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Fe(e,t.cwd)});return}let c=o.pid;c!==void 0&&Ye(e,c);let l=new Promise(e=>o.once(`exit`,e)),u=et(o.stdout),d=et(o.stderr),f=()=>({stdout:u(),stderr:d()}),p=!1,m=null,h=null,g=null,_=null,v=()=>w(`aborted`),y=()=>{t.signal?.removeEventListener(`abort`,v),e.inFlight.delete(v)},b=i=>{if(!p){p=!0,m?.(),h?.(),g?.(),y(),c!==void 0&&Xe(e,c),n?.onEnd(t.category,r.now()-a);for(let e of[o.stdout,o.stderr])e?.unref();i()}},x=e=>b(()=>i(e)),S=(n,r)=>{try{Qe(n,r)}catch(n){e.unreaped.set(o,t.category),l.then(()=>e.unreaped.delete(o)),x({ok:!1,reason:`signal-refused`,...f(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},C=()=>ee(o.exitCode,o.signalCode);if(c!==void 0){let e=t=>{if(!p){if(ut(c)){r.defer(C);return}g=r.after(t,()=>e(Math.min(t*2,1e3)))}};l.then(()=>r.defer(()=>e(25)))}let w=e=>{if((o.exitCode!==null||o.signalCode!==null)&&c!==void 0&&ut(c)){_=e===`aborted`?e:null,r.defer(C);return}_=e,m?.(),y();let t=o.pid;t!==void 0&&(h=r.after(250,()=>{S(t,`SIGKILL`),l.then(()=>r.defer(C))}),S(t,`SIGTERM`))};o.on(`error`,e=>{x({ok:!1,reason:`spawn-error`,...f(),exitCode:null,signal:null,error:Fe(e,t.cwd)})});let ee=(e,t)=>{if(_!==null){x({ok:!1,reason:_,...f(),exitCode:e,signal:t});return}if(e===0){x({ok:!0,...f(),exitCode:e});return}x({ok:!1,reason:t?`signal`:`non-zero`,...f(),exitCode:e,signal:t})};o.on(`close`,ee),t.timeoutMs&&t.timeoutMs>0&&(m=r.after(t.timeoutMs,()=>w(`timeout`))),t.signal?.addEventListener(`abort`,v,{once:!0}),e.inFlight.add(v),o.stdin?.on(`error`,()=>{}),o.stdin?.end(t.stdinInput)})}function nt(e,t){let{stats:n,clock:r}=e.scope,i=He(e,t.category);if(i!==null)return i;let a=r.now();n?.onStart(t.category);let o=[`pipe`,`pipe`,`pipe`];try{let i=c(t.bin,t.args??[],{cwd:t.cwd,env:Re(e.scope,t),input:t.stdinInput,timeout:t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:void 0,stdio:o,encoding:`utf8`});n?.onEnd(t.category,r.now()-a);let s=typeof i.stdout==`string`?i.stdout:``,l=typeof i.stderr==`string`?i.stderr:``,u=i.error?.code;return i.error&&u!==`EPIPE`&&u!==`ECONNRESET`?{ok:!1,reason:u===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:s,stderr:l,exitCode:null,signal:i.signal??null,error:Fe(i.error,t.cwd)}:i.status===0?{ok:!0,stdout:s,stderr:l,exitCode:i.status}:{ok:!1,reason:i.signal?`signal`:`non-zero`,stdout:s,stderr:l,exitCode:i.status,signal:i.signal??null}}catch(e){return n?.onEnd(t.category,r.now()-a),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Fe(e,t.cwd)}}}function rt(e,t){let{stats:n,clock:r}=e.scope,i=He(e,t.category);if(i!==null)return i;let a=r.now();n?.onStart(t.category);let o=it(e.scope,t);return n?.onEnd(t.category,r.now()-a),o}function it(e,t){let n;try{n=s(t.bin,t.args??[],{cwd:t.cwd,env:Re(e,t),detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Fe(e,t.cwd)}}return n.once(`error`,()=>{}),n.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${t.bin}): no pid (binary not found or unexecutable)`}:(n.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}const at=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`;function ot(e,t,n){let{stats:r,clock:i}=e.scope,a=He(e,t.category);if(a!==null)return{ok:!1,reason:a.reason,error:a.error};let o=i.now();r?.onStart(t.category);let c;try{c=s(`/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:Re(e.scope,t),detached:!0,stdio:[`pipe`,`ignore`,`ignore`]})}catch(e){return r?.onEnd(t.category,i.now()-o),{ok:!1,reason:`spawn-error`,error:Fe(e,t.cwd)}}r?.onEnd(t.category,i.now()-o),c.once(`error`,()=>{});let l=c.pid,u=c.stdin;return u.on(`error`,()=>{}),l===void 0?(u.destroy(),{ok:!1,reason:`spawn-error`,error:`spawn(/bin/sh): no pid (shell not found or unexecutable)`}):(c.unref(),u.unref(),{ok:!0,pid:l,release:()=>u.end(`go
|
|
3
|
-
`),withdraw:()=>u.end()})}function st(e){let t;try{t=_(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 ct(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 lt(e){return ct(e,0)}function ut(e){try{return process.kill(-e,0),!1}catch(e){return e.code===`ESRCH`}}function dt(e,t,n,r){let i=`${t}.${process.pid}`;try{x(i,`${at(n)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let a=!0;try{m(i,t)}catch(e){if(e.code!==`EEXIST`)throw e;a=!1}finally{y(i,{force:!0})}let o=ct(e,`SIGTERM`);return o&&r.after(250,()=>ct(e,`SIGKILL`),{unref:!0}),{stands:a,signalled:o}}function ft(e,t){return mt(e,t).launcher}function pt(e,t){let{launcher:n,state:r}=mt(e,t);return{...n,launchSync:e=>nt(r,e)}}function mt(e,t){let n={clock:t,launch:e=>Ve(r,tt(r,e)),launchDetachedSync:e=>rt(r,e),launchJobSync:(e,t)=>ot(r,e,t),lifelineWarnings:()=>qe(r),settled:async()=>(await Promise.all(r.ending),{unreaped:[...r.unreaped.values()]}),__lifelineForTest:()=>{let e=r.lifeline;return{pid:e?.process.pid,cut:()=>{e?.pipe.end(),e&&Ke(r,e.process,`cut by a test`)}}}},r={scope:{stats:null,observeLifeline:()=>n.lifelineWarnings().forEach(e=>process.emitWarning(e.message)),signal:new AbortController().signal,...e,clock:t},lastStartAt:new Map,inFlight:new Set,liveGroups:new Set,lifeline:null,fault:null,ending:new Set,unreaped:new Map};return r.scope.signal.addEventListener(`abort`,()=>{r.inFlight.forEach(e=>e()),Ze(r)},{once:!0}),{launcher:n,state:r}}const ht={now:()=>Date.now(),monotonic:()=>performance.now(),after:(e,t,n)=>{let r=setTimeout(t,e);return n?.unref&&r.unref(),()=>clearTimeout(r)},every:(e,t,n)=>{let r=setInterval(t,e);return n?.unref&&r.unref(),()=>clearInterval(r)},defer:e=>{let t=te(e);return()=>T(t)}};function A(e,t,n){return new Promise((r,i)=>{let a=()=>Object.assign(Error(`The operation was aborted`),{name:`AbortError`,code:`ABORT_ERR`,cause:n?.reason});if(n?.aborted){i(a());return}let o=()=>{s(),i(a())},s=e.after(t,()=>{n?.removeEventListener(`abort`,o),r()});n?.addEventListener(`abort`,o,{once:!0})})}function gt(e,t){let n=new AbortController;return e.after(t,()=>n.abort(new DOMException(`The operation was aborted due to timeout`,`TimeoutError`)),{unref:!0}),n.signal}function _t(){let e={env:process.env,home:o.homedir(),tmp:o.tmpdir()},t=ht;return{host:e,launcher:pt({inherited:process.env},t),clock:t}}const vt=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function yt(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function bt(e){return vt.test(e)?e:yt(e)}function xt(e){return`${e.dir===void 0?``:`cd ${bt(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${bt(t)} `).join(``)}${[e.program,...e.args].map(bt).join(` `)}`}const St=`cc-extra`;function Ct(e){return E.join(E.dirname(e),St,`src`,`bun-attach.js`)}function wt(e){return E.join(E.dirname(e),`bun-graph.js`)}const Tt=`attach-preload.cjs`;function Et(e){return E.join(E.dirname(e),Tt)}function Dt(e,t){return xt({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Ot=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function kt(e,t){return t.isSymbolicLink()?Buffer.from(l.readlinkSync(e)):l.readFileSync(e)}function At(e,t,n=Ot){return l.readdirSync(t).filter(n).sort().flatMap(n=>{let r=E.join(t,n),i=l.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?At(e,r):[[E.relative(e,r).split(E.sep).join(`/`),kt(r,i)]]})}function jt(e){let t=ae.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Mt(e){return jt(At(e,e))}const Nt=[`Cargo.toml`,`Cargo.lock`,`src`];function Pt(e){return jt(At(e,e,e=>Nt.includes(e)))}const Ft=e=>e.slice(0,7),It=`1.180.
|
|
3
|
+
`),withdraw:()=>u.end()})}function st(e){let t;try{t=_(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 ct(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 lt(e){return ct(e,0)}function ut(e){try{return process.kill(-e,0),!1}catch(e){return e.code===`ESRCH`}}function dt(e,t,n,r){let i=`${t}.${process.pid}`;try{x(i,`${at(n)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let a=!0;try{m(i,t)}catch(e){if(e.code!==`EEXIST`)throw e;a=!1}finally{y(i,{force:!0})}let o=ct(e,`SIGTERM`);return o&&r.after(250,()=>ct(e,`SIGKILL`),{unref:!0}),{stands:a,signalled:o}}function ft(e,t){return mt(e,t).launcher}function pt(e,t){let{launcher:n,state:r}=mt(e,t);return{...n,launchSync:e=>nt(r,e)}}function mt(e,t){let n={clock:t,launch:e=>Ve(r,tt(r,e)),launchDetachedSync:e=>rt(r,e),launchJobSync:(e,t)=>ot(r,e,t),lifelineWarnings:()=>qe(r),settled:async()=>(await Promise.all(r.ending),{unreaped:[...r.unreaped.values()]}),__lifelineForTest:()=>{let e=r.lifeline;return{pid:e?.process.pid,cut:()=>{e?.pipe.end(),e&&Ke(r,e.process,`cut by a test`)}}}},r={scope:{stats:null,observeLifeline:()=>n.lifelineWarnings().forEach(e=>process.emitWarning(e.message)),signal:new AbortController().signal,...e,clock:t},lastStartAt:new Map,inFlight:new Set,liveGroups:new Set,lifeline:null,fault:null,ending:new Set,unreaped:new Map};return r.scope.signal.addEventListener(`abort`,()=>{r.inFlight.forEach(e=>e()),Ze(r)},{once:!0}),{launcher:n,state:r}}const ht={now:()=>Date.now(),monotonic:()=>performance.now(),after:(e,t,n)=>{let r=setTimeout(t,e);return n?.unref&&r.unref(),()=>clearTimeout(r)},every:(e,t,n)=>{let r=setInterval(t,e);return n?.unref&&r.unref(),()=>clearInterval(r)},defer:e=>{let t=te(e);return()=>T(t)}};function A(e,t,n){return new Promise((r,i)=>{let a=()=>Object.assign(Error(`The operation was aborted`),{name:`AbortError`,code:`ABORT_ERR`,cause:n?.reason});if(n?.aborted){i(a());return}let o=()=>{s(),i(a())},s=e.after(t,()=>{n?.removeEventListener(`abort`,o),r()});n?.addEventListener(`abort`,o,{once:!0})})}function gt(e,t){let n=new AbortController;return e.after(t,()=>n.abort(new DOMException(`The operation was aborted due to timeout`,`TimeoutError`)),{unref:!0}),n.signal}function _t(){let e={env:process.env,home:o.homedir(),tmp:o.tmpdir()},t=ht;return{host:e,launcher:pt({inherited:process.env},t),clock:t}}const vt=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function yt(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function bt(e){return vt.test(e)?e:yt(e)}function xt(e){return`${e.dir===void 0?``:`cd ${bt(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${bt(t)} `).join(``)}${[e.program,...e.args].map(bt).join(` `)}`}const St=`cc-extra`;function Ct(e){return E.join(E.dirname(e),St,`src`,`bun-attach.js`)}function wt(e){return E.join(E.dirname(e),`bun-graph.js`)}const Tt=`attach-preload.cjs`;function Et(e){return E.join(E.dirname(e),Tt)}function Dt(e,t){return xt({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Ot=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function kt(e,t){return t.isSymbolicLink()?Buffer.from(l.readlinkSync(e)):l.readFileSync(e)}function At(e,t,n=Ot){return l.readdirSync(t).filter(n).sort().flatMap(n=>{let r=E.join(t,n),i=l.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?At(e,r):[[E.relative(e,r).split(E.sep).join(`/`),kt(r,i)]]})}function jt(e){let t=ae.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Mt(e){return jt(At(e,e))}const Nt=[`Cargo.toml`,`Cargo.lock`,`src`];function Pt(e){return jt(At(e,e,e=>Nt.includes(e)))}const Ft=e=>e.slice(0,7),It=`1.180.7`;function Lt(e){let t=E.dirname(E.dirname(e));return l.existsSync(E.join(t,`src`))?t:null}function Rt(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:It,digest:e}}function zt(){return`dce01c2a646ca24a4503b62ed8e57295e4daed6dfb87494c79766429aaec03f1`}function Bt(e){let t=JSON.parse(l.readFileSync(E.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${E.join(e,`package.json`)} has no version string`);return n}function Vt(e,t){try{let n=Lt(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Mt(E.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:Bt(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function Ht(e,t){let n=e[t];return n&&n.length>0?n:void 0}function Ut(e){let t=Ht(e.env,`XDG_STATE_HOME`)??E.join(e.home,`.local`,`state`);return E.join(t,`cc-candybar`)}function j(e){let t=Ht(e.env,`XDG_CACHE_HOME`)??E.join(e.home,`.cache`);return E.join(t,`cc-candybar`)}function Wt(e){return Ut(e)}function Gt(e){return e.env.CC_CANDYBAR_SOCKET||Kt()}function Kt(){let e=o.userInfo().uid;return E.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function qt(e){l.mkdirSync(e,{recursive:!0,mode:448});let t=l.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=o.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 Jt(e){qt(E.dirname(e));for(let t of[e,Yt(e)])try{if(l.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 M(e){return Yt(Gt(e))}function Xt(e){return E.join(Ut(e),`session-state.json`)}function Zt(e){return E.join(Ut(e),`settings-history.json`)}function Qt(e){let t=e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(t)return t;let n=o.userInfo().uid;return E.join(`/tmp`,`cc-candybar-${n}`,`daemons`)}function $t(e){return E.join(Ut(e),`spawn.lock`)}function en(e){return E.join(Ut(e),`spawn.cooldown`)}function tn(e){return E.join(Ut(e),`spawn.backoff`)}function nn(e){return E.join(Ut(e),`watch-probe`)}function rn(e){return E.join(Ut(e),`daemon.log`)}function an(e){return{socket:Gt(e),lease:M(e),state:Ut(e),registry:Qt(e),log:rn(e),sessionState:Xt(e),settingsHistory:Zt(e),watchProbe:nn(e),spawnBackoff:tn(e)}}function on(e){let{env:t}=e,n=`/usr/local/share:/usr/share`,r=process.platform===`darwin`?`${E.join(Ht(t,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${n}`:n;return{home:e.home,configHome:Ht(t,`XDG_CONFIG_HOME`)??E.join(e.home,`.config`),dataHome:Ht(t,`XDG_DATA_HOME`)??E.join(e.home,`.local`,`share`),dataDirs:(Ht(t,`XDG_DATA_DIRS`)??r).split(`:`).filter(e=>e!==``)}}function sn(e,t,n){let r=cn(e);l.mkdirSync(E.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??l.statSync(r,{throwIfNoEntry:!1})?.mode;try{l.writeFileSync(i,t,a===void 0?{}:{mode:a}),l.renameSync(i,r)}catch(e){throw l.rmSync(i,{force:!0}),e}}function cn(e){return ln(e).at(-1)}function ln(e){let{hops:t,stopped:n}=un(e);if(n!==null)throw n;return t}function un(e){let t=[e];try{for(let e=0;e<fn;e++){let e=dn(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${fn} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function dn(e){try{return l.lstatSync(e).isSymbolicLink()?E.resolve(l.realpathSync(E.dirname(e)),l.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const fn=40,pn=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function mn(e){return Object.fromEntries(pn.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const hn=[`native`,`node`,`frames`];function gn(e,t){return{kind:e,bundle:t,source:null}}const _n=[`ansi`,`frame`],vn=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function yn(e){let t=Dn(e.termCols),n=Dn(e.termRows),r=On(e.ssh),i=N(e.tmux),a=Tn(e.configEnv),o=Tn(e.claudeConfigDir),s=wn(e.terminalEnv),c=In(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 bn(e,t){return vn.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function xn(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 Sn={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Cn(e){let t=Object.keys(Sn).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Sn[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
4
4
|
`)}function wn(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=pn.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 Tn(e){return typeof e==`string`&&E.isAbsolute(e)?e:void 0}function N(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 En=1e4;function Dn(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>En?En:t}function On(e){return typeof e==`boolean`?e:void 0}function kn(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var An=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}},jn=class extends Error{constructor(e){super(e===`connect`?`CONNECT_TIMEOUT`:`TIMEOUT`),this.phase=e,this.name=`ClientTimeoutError`}};function Mn(e){return Nn(JSON.stringify(e))}function Nn(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function Pn(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 An(`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 An(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function Fn(e,t,n,r){return new Promise((i,a)=>{let o=!1,s=t=>{if(!o){o=!0,c(),e.off(`data`,l),e.off(`error`,u),e.off(`close`,d);try{t()}catch{}}},c=r.after(n-r.now(),()=>{s(()=>{e.destroy(),a(new jn(`deadline`))})}),l=Pn(e=>s(()=>i(e)),e=>s(()=>a(e))),u=e=>s(()=>a(e)),d=()=>s(()=>a(Error(`socket closed before response`)));e.on(`data`,l),e.on(`error`,u),e.on(`close`,d),e.write(Mn(t))})}function In(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Tn(n);return hn.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function Ln(e,t,n,r){let i;try{i=await Un(Gt(e.host),n.connectMs,e.clock)}catch(e){return Hn(e)}return Rn(i,e.clock,t,n,r)}async function Rn(e,t,n,r,i){try{let a=t.now()+r.budgetMs,o=n(a),s=await Fn(e,{v:3,...o},a,t);return Vn(o.kind,s,i)}catch(e){return Hn(e)}finally{e.destroy()}}function zn(e,t){return typeof e==`string`?e:t}function Bn(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function Vn(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=zn(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:Bn(r.daemonV)};case`TIMEOUT`:return{kind:`busy`,phase:`deadline`,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 Hn(e){if(e instanceof An||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 e instanceof jn?{kind:`busy`,phase:e.phase,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 Un(e,t,n){return new Promise((r,i)=>{let a=de.createConnection({path:e}),o=n.after(t,()=>{a.destroy(),i(new jn(`connect`))});a.once(`connect`,()=>{o(),r(a)}),a.once(`error`,e=>{o(),i(e)})})}function Wn(e){if(e.kind===`busy`)return`daemon busy (${e.message})`;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}`}}function Gn(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 Kn(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)}const qn={connectMs:50,budgetMs:150},Jn={connectMs:50,budgetMs:350};function Yn(e){let t=e.output;return typeof t==`string`?t:void 0}function Xn(e){return Vn(`render`,e,Yn)}function Zn(e,t,n,r,i,a=qn){return Ln(e,e=>({kind:`render`,hookData:t,args:n,cwd:r,deadline:e,...i}),a,Yn)}function Qn(e,t,n){return Ln(e,()=>({kind:`pane-session`,socket:t,pane:n}),Jn,e=>`paneSession`in e?e.paneSession:void 0)}function $n(e,t,n){return Ln(e,()=>({kind:`click`,verb:t,value:n,clientVersion:It}),Jn,Yn)}const er=5e3;async function tr(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 nr=`/usr/bin/footprint`;function rr(e,t,n){return t===`darwin`?[sr(e,nr,[`-p`,String(n)]),sr(e,`/usr/bin/vmmap`,[`--summary`,String(n)])]:t===`linux`?[cr(`/proc/self/smaps_rollup`),cr(`/proc/self/status`)]:[]}function ir(e,t,n){return t===`darwin`?ar(n,t=>e.launch({bin:nr,args:t,timeoutMs:er,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function ar(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}`}${lr(r.stderr)}`};let i=or(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 or(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function sr(e,t,n){return{name:`${t} ${n.join(` `)}`,read:async()=>{let r=await e.launch({bin:t,args:[...n],timeoutMs:er,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}`}${lr(r.stderr)}`}}}}function cr(e){return{name:e,read:async()=>{try{let t=l.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 lr(e){let t=e.split(`
|
|
6
6
|
`).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const ur=`CC_CANDYBAR_RSS_LIMIT_MB`;function dr(e){let t=e[ur];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${ur} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function fr(e){return dr(e)*2}const pr=1024*1024,mr=e=>Math.round(e/pr);function hr(e){return dr(e)*pr}const gr={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function _r(e,t){return e>t}function vr(e,t){if(e.kind===`charged`)return e;let n=t.kind===`unmeasured`?0:t.charge.kind===`charged`?t.rss-t.charge.bytes:t.charge.gap;return{...e,bytes:e.bytes-n,gap:n}}const yr=.75;function br(e,t){return e>t*yr}function xr(e,t,n){let{prefix:r,suffix:i}=gr[t];return E.join(e,`${r}${n}${i}`)}function Sr(e){for(let t of Object.keys(gr)){let{prefix:n,suffix:r}=gr[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function Cr(e){let t=e.limitBytes??1024*pr,n=e.snapshotsKeep??3,r=!1,i={kind:`unmeasured`},a=null,o=!1,s;function c(){return a??=l().finally(()=>{a=null}),a}async function l(){if(r)return!0;let{rss:a,heapTotal:s}=e.memoryBytes(),c=vr(await e.memoryCharge(a),i),l={kind:`measured`,charge:c,rss:a,heapTotal:s};if(i=l,e.log(`info`,`memory ${Er(l,t)}`),o||c.bytes<=t)return!1;r=!0,e.log(`warn`,`${wr(c)} > limit ${mr(t)} MB (rss ${mr(a)} MB, v8 heap ${mr(s)} MB); recording memory then shutting down`);let u=`${new Date(e.clock.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return await Dr(e.log,`memory report`,async()=>{let t=xr(e.snapshotDir,`memoryReport`,u),n=await e.captureMemoryReport();o||(e.writeMemoryReport(t,n),e.log(`info`,`memory report written: ${t}`))}),o?(e.log(`info`,`daemon closed during the breach: no snapshot, no exit`),!1):(await Dr(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=xr(e.snapshotDir,`heapSnapshot`,u);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),await Dr(e.log,`artifact rotation`,async()=>{for(let{artifacts:t}of Or(e.listArtifacts()).slice(n))for(let n of Object.values(t))await Dr(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0)}function u(){return i.kind===`measured`&&br(i.charge.bytes,t)?`${wr(i.charge)} approaching limit ${mr(t)} MB (v8 heap ${mr(i.heapTotal)} MB)`:null}function d(){let n;try{n={kind:`ok`,value:Or(e.listArtifacts())}}catch(e){n={kind:`failed`,reason:e.message}}return{pid:e.pid,memory:i,limit:t,postMortems:n}}function f(t=6e4){let n=async()=>{try{if(await c())return}catch(t){e.log(`warn`,`memory check failed: ${t.message}`)}o||(s=e.clock.after(t,()=>void n(),{unref:!0}))};n()}function p(){o=!0,s?.()}return{check:c,describeNextRestart:u,serving:d,arm:f,disarm:p}}function wr(e){return e.kind===`charged`?`${e.measure} ${mr(e.bytes)} MB`:`rss ${mr(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${mr(e.gap)} MB gap`} (standing in: ${e.unread})`}function Tr(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function Er({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${mr(e.gap)}MB`:``;return`measure=${Tr(e)} charge=${mr(e.bytes)}MB rss=${mr(t)}MB heap=${mr(n)}MB limit=${mr(r)}MB${i}`}async function Dr(e,t,n){try{await n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function Or(e){let t=new Map;for(let n of e){let e=E.basename(n),r=Sr(e);if(r===null)continue;let{prefix:i,suffix:a}=gr[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(gr);return[...t].sort(([e],[t])=>_r(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function kr(e,t,n,r={}){let i=n.snapshotDir;return{clock:n.clock,pid:process.pid,snapshotDir:i,log:n.log,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},memoryCharge:ir(n.launcher,process.platform,process.pid),captureMemoryReport:()=>tr(rr(n.launcher,process.platform,process.pid)),writeMemoryReport:(e,t)=>l.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>fe.writeHeapSnapshot(e),writeLogNow:n.writeLogNow,listArtifacts:()=>{let e;try{e=l.readdirSync(i)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>Sr(e)!==null).map(e=>E.join(i,e))},removeFile:e=>l.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}function Ar(e,n={}){let{host:r,clock:i}=e;if(Kr(r)!==null)return;let a=n.spawn??(()=>Jr(e)),o=Ur(r,i);if(o.kind===`contended`){let e=Mr(r,i);e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),jr(r,i,a));return}if(o.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${o.reason}) — spawning unlocked\n`),jr(r,i,a);return}try{jr(r,i,a)}finally{Gr()}}function jr(e,t,n){zr(e,t)&&Nr(n)}function Mr(e,t){try{let n=l.statSync($t(e));return t.now()-n.mtimeMs}catch{return null}}function Nr(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
|
|
@@ -175,21 +175,21 @@ Config tooling:
|
|
|
175
175
|
|
|
176
176
|
`,jN=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`;function MN(e,t){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?t+e.slice(1):e}function NN(e,t,n){return E.resolve(e,MN(t,n))}function PN(e,t,n){return typeof t==`string`&&t!==``?NN(e,t,n):void 0}const FN=`CC_CANDYBAR_CONFIG`;function IN({env:e,home:t},n){return PN(n,e[FN],t)}function LN(e,t){return e===void 0?t===void 0?{source:`search`}:{source:`environment`,path:t}:{source:`argument`,path:e}}function RN(e,t,n){return LN(PN(n,e,t.home),IN(t,n))}function zN(e,t=`bundled default (no config file loaded)`){return e.join(` < `)||t}const BN=new Cf({"strip.separator":`default`,"strip.rail":`default`});function VN(e){return BN.resolve(e)}const HN={kind:`still`},UN=e=>Sp.at(e.timeline,e.wall),WN=Symbol(`bar`);function GN(e){return e.name!==ay}function KN(e){return t=>G.map(G.all(e.map(({timeline:e,effect:n})=>Sp.run(e,n(t)))),e=>(t,n)=>e.reduce((e,t)=>t(e,n),t))}const qN=wd;function JN(e,t){let n=new Wl(t,qN.foregroundColor,qN.ansiColors,qN.palette);return t=>e({...t,theme:n})}function YN(e,t){return n=>yh(()=>e(n),...t)(n)}function XN(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t/4294967296}const ZN=4096;function QN(e,t,n){let r=(n,{terminal:r})=>({...n,bg:r.bg?n.bg:e,fg:r.fg?n.fg:r.bg?e:t}),i=e=>e,a=Zb.reduceRight((e,{lit:t,seconds:n})=>G.sequence(G.constant(t?r:i),n,e),G.constant(i)),o=G.sequence(G.constant(i),n,a);return()=>o}var $N=class{inForce=null;anchor=Sp.play(0);placements=new Map;made=new Map;passages=null;frame={effect:ay,t:0,speed:1,made:0,reused:0,own:[],basis:`off`,revision:0,fades:[],leaves:[]};constructor(e){this.key=e}lastFrame(){return this.frame}get heldCount(){let e=this.passages?.size??0;return[...this.made.values()].reduce((e,t)=>e+t.size,e)}clockAt(e,t){return{wall:e,timeline:Sp.withRate(this.anchor,e,t)}}motion(e,t,n,r=null){let i=UN(t),a=e=>Sp.seek(t.timeline,t.wall,e),o=this.inForce?.name===e?this.inForce:{name:e,since:i},s={scope:WN,name:e,t:i-o.since},c=this.placements,l=new Map,u=this.made,d=new Map,f=[],{last:p}=n,m=this.passages,h=n.transitions?m!==null&&p!==null?`compared`:`fresh`:`off`,g=h===`compared`?e=>{let t=p.placements.get(e);return t?.kind===`drew`?{drawing:t.drawing,passage:m.get(e)??null}:void 0}:null,_=new Set,v=new Map,y=[],b=[],x={effect:e,t:s.t,speed:t.timeline.rate,made:0,reused:0,own:f,basis:h,revision:n.source.revision,fades:y,leaves:b},S=(e,t,{ground:n})=>{let r=Rg.transitions[e]({z:XN(`${this.key}@${t}`)*ZN});return{name:e,since:i,done:e=>r.done(e),effect:JN(r.effect,n)}},C=({since:e,done:t})=>t(i-e),w=(e,t,n)=>({drawing:t,passage:g===null?null:n===void 0||n.passage?.name===`dissolve`?S(`fade`,e,t):n.passage!==null&&!C(n.passage)?n.passage:null}),ee=(e,t)=>{if(t===void 0||t.drawing.opened||t.drawing.own.length===0)return;if(t.passage?.name===`dissolve`)return C(t.passage)?void 0:t;let r={...t.drawing,own:t.drawing.own.map(n.hold)};return{drawing:r,passage:S(`dissolve`,e,r)}},T=(e,t)=>{if(_.has(e))throw Error(`placement "${e}" was reached twice in one frame`);_.add(e);let r=g?.(e),{drawing:a,deeper:o}=n.returned(e,t),s=a===null?ee(e,r):w(e,a,r);return s===void 0?t:(s.passage!==null&&(v.set(e,s.passage),(s.passage.name===`fade`?y:b).push({placement:e,t:i-s.passage.since})),a===null?[...s.drawing.own,...o]:t)},te=(e,t)=>{let n=l.get(e)??c.get(e),r=n?.name===t?n:{name:t,since:i},a=i-r.since;return l.has(e)||(l.set(e,r),f.push({placement:e,effect:t,t:a})),{scope:e,name:t,t:a}},E=(e,t)=>{let n=d.get(e)??new Map;d.set(e,n);let r=n.get(t.scope);if(r!==void 0)return r.effect;let i=u.get(e)?.get(t.scope),a=i?.name===t.name,o=XN(t.scope===WN?e:`${e}@${t.scope}`),s=a?i.effect:Rg.loops[t.name]({z:o*ZN});return x[a?`reused`:`made`]++,n.set(t.scope,{name:t.name,effect:s}),s},ne=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?s:te(r.id,r.effect),i=t.get(e.scope);i===void 0?t.set(e.scope,{...e,owners:[n]}):i.owners.push(n)}return[...t.values()]},D=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=t.get(r.id);e===void 0?t.set(r.id,[n]):e.push(n)}return[...t].flatMap(([e,t])=>{let n=v.get(e)??null;return n===null?[]:[{timeline:a(i-n.since),effect:yh(n.effect,...t)}]})},re=r===null?[]:[{timeline:Sp.play(r.idleSince),effect:QN(r.fill,r.text,tx(r.timeoutS))}],ie=e=>e===`menu`?re:[];return{placed:h===`off`?(e,t)=>t:T,row:(e,n,r)=>{let i=(r.some(e=>e.placement.effect!==`bar`)?ne(r):[{...s,owners:void 0}]).filter(GN),o=D(r),c=ie(n);if(i.length===0&&o.length===0&&c.length===0)return HN;let l=`${this.key}#${e}`;return{kind:`moving`,time:t.wall,wrap:e=>new lh(e,KN([...i.map(e=>{let t=E(l,e);return{timeline:a(e.t),effect:e.owners===void 0?t:YN(t,e.owners)}}),...o,...c]),{key:l,theme:qN})}},drawn:()=>{this.anchor=t.timeline,this.inForce=o,this.placements=l,this.made=d,this.passages=h===`off`?null:v,this.frame=x}}}},eP=class{sessions=new Map;constructor(e=256){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new $N(e);this.sessions.delete(e),this.sessions.set(e,t);for(let e of this.sessions.keys()){if(this.sessions.size<=this.maxSessions)break;this.sessions.delete(e)}return t}getStats(){let e=0;for(let t of this.sessions.values())e+=t.heldCount;return{sessions:this.sessions.size,effects:e}}};const tP={fg:`#ffffff`,bg:`#c82828`},nP={fg:`#000000`,bg:`#dca028`};function rP(e,t){return`\x1b[${e};2;${[1,3,5].map(e=>Number.parseInt(t.slice(e,e+2),16)).join(`;`)}m`}const iP=rP(38,tP.fg),aP=rP(48,tP.bg),oP=[[0,31],[127,159],[8234,8238],[8294,8303]];function sP(e){return oP.some(([t,n])=>e>=t&&e<=n)}function cP(e){let t=``;for(let n of e)t+=sP(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function lP(e,t){let n=cP(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const uP=`${aP}${iP}`;function dP(e){return`⚠ cc-candybar: ${pP(e)}`}function fP(e){return`${uP}${dP(e)}[0m\n`}function pP(e){switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:return`daemon rejected request: ${lP(e.message,60)}`;case`render_failed`:return`render failed: ${lP(e.message,60)}`;case`switched_off`:return`switched off: ${lP(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${lP(e.message,60)}`}}function mP(e,t){return{depth:e.depth,rows:t,nextChange:1/0,motion:e.motion===`still`?`still`:`can-move`,pending:[]}}function hP(e,t){return{depth:`truecolor`,rows:[{kind:`diagnostic`,runs:[{text:cP(e),...t}]}],nextChange:1/0,motion:`still`,pending:[]}}function gP(e){return hP(dP({kind:`permanent`,cause:`render_failed`,message:e}),tP)}function _P(e,t){try{return e(t)}catch(t){return e(hP(`⚠ cc-candybar ${t instanceof Error?t.message:String(t)}`,tP))}}function vP(e){return e.type===V.TRUECOLOR?e.value.hex:e.number===void 0?e.name:`color(${e.number})`}const yP=Object.keys(new U().attributes);function bP(e,t){let{color:n,bgcolor:r}=e.drawnColors(t),i=yP.filter(t=>e[t]===!0);return{...n!==void 0&&{fg:vP(n)},...r!==void 0&&{bg:vP(r)},...i.length>0&&{attrs:i}}}function xP({text:e,style:t},n){return{text:e,...t!==void 0&&n!==null&&bP(t,n),...t?.link!==void 0&&{link:t.link}}}function SP(e,t){let n=e.filter(e=>!e.isControl&&e.text.length>0);return W.splitLines(n).map(e=>e.map(e=>xP(e,t)))}function CP({text:e,fg:t,bg:n,attrs:r=[],link:i}){return new W(e,new U({color:t,bgcolor:n,link:i,...Object.fromEntries(r.map(e=>[e,!0]))}))}function wP(e,t){let n=xl(t);return e.map(e=>ah(e.map(CP),n)).join(`
|
|
177
177
|
`)}function TP(e){return wP(e.rows.map(e=>e.runs),e.depth)}function EP(e){return TP(e)+`
|
|
178
|
-
`}const DP=(e,t)=>e.fg===t.fg&&e.bg===t.bg&&e.link===t.link&&e.attrs?.join()===t.attrs?.join();function OP({runs:e}){let t=[];for(let n of e){let e=t.at(-1);e!==void 0&&DP(e,n)?t[t.length-1]={...e,text:e.text+n.text}:t.push(n)}return t}function kP(e){return e.map(e=>e.text).join(``)}const AP={};function jP(e,t){let n=xl(t.colorSystem),{time:r}=t,i=1/0,a=[...Jf(e,{maxWidth:t.width??80,isTerminal:!1,asciiOnly:!1,theme:BN,colorSystem:n.colorSystem,...r===void 0?{}:{frame:{time:r,host:AP}},onStyleError:e=>{throw e},onHold:({nextChange:e})=>{i=Math.min(i,e)}})];return{lines:SP(a,n.colorSystem),nextChange:Math.min(W.nextChange(a),i)}}const MP=new Map;function NP(e){let t=MP.get(e);if(t!==void 0)return t;let n=t=>({seam:t.seam.map(t=>`cap`in t?t:{...t,glyph:e})}),{seam:r,caps:i}=nh.plain,a=new Em({glyph:n(r.glyph),ascii:r.ascii},i);return MP.set(e,a),a}function PP(e,t){return e===`plain`&&t!==void 0?NP(t):nh[e]}const FP=new Map;function IP(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=FP.get(t);if(n!==void 0)return n;let r=PP(e.endcaps,e.separator),i=e=>new K(`x`,{end:``,overflow:`ignore`,style:new U({bgcolor:e})}),a=e=>{let{lines:t}=jP(new $p(e,r),{colorSystem:null});return new K(kP(t.flat())).cellLength},o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return FP.set(t,s),s}function LP(e){return IP(e).chrome}function RP(e){return IP(e).seam}const zP=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function BP(e){return[...new Set(e.match(zP)??[])].join(``)}function VP(e){let t=PP(e.endcaps,e.separator),n=e=>new K(`x`,{end:``,style:new U({bgcolor:e})}),{lines:r}=jP(new $p([n(`#101010`),n(`#202020`)],t),{colorSystem:null});return BP(kP(r.flat()))}function HP(e){return e.wrap?e.width:1/0}function UP(e,t){return jP(new K(e,{overflow:`fold`,end:``}),{colorSystem:null,width:t}).lines.map(kP)}function WP(e,t,n=HN){if(e.length===0)return{lines:[[]],nextChange:1/0};let r=PP(t.endcaps,t.separator),i=Number.isFinite(HP(t)),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new __([...e],{joiner:r}):new $p([...e],r),s=n.kind===`still`?jP(o,a):jP(n.wrap(o),{...a,time:n.time});if(s.lines.length===0)throw Error(`drawStripCells: rich-js strip drew no line`);return s}function GP(e,t){return wP(WP(e,t).lines,t.colorCompatibility)}const KP=[`moves`,`can-move`,`still`];function qP(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const JP=[`statusline`,`frames`],YP=e=>e?.kind===`frames`?`frames`:`statusline`,Xee=[`carried`,`missing`,`unanswered`];function Zee(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:qP(e)===`no`?`unanswered`:`missing`}function Qee(e){return{path:e.transcript_path,answered:qP(e)===`yes`}}const XP=[...KP,`failed`,`drawing`];var $ee=class{seen=new Map;see(e,t,n,r){let i=YP(t.client),a=JSON.stringify([e,i]),o=this.seen.get(a);o!==void 0&&o.order>r||(this.seen.delete(a),this.seen.set(a,{sessionId:e,said:{...t,role:i},at:n,order:r}),this.seen.size>64&&this.seen.delete(this.seen.keys().next().value))}list(e){return[...this.seen.values()].map(({sessionId:t,said:n,at:r})=>({...n,sessionId:t,ago:e-r}))}ofSession(e,t){return this.list(t).filter(t=>t.sessionId===e)}};const ZP={kitty:{label:`kitty`,xtversion:`kitty`,program:null,programVersion:!0,term:`xterm-kitty`,links:{since:`0.19.0`},glyphs:{kind:`bundled`,since:`0.36.0`}},wezterm:{label:`WezTerm`,xtversion:`WezTerm`,program:`WezTerm`,programVersion:!0,term:`wezterm`,links:{since:null},glyphs:{kind:`bundled`,since:`20230712`}},ghostty:{label:`Ghostty`,xtversion:`ghostty`,program:`ghostty`,programVersion:!0,term:`xterm-ghostty`,links:{since:null},glyphs:{kind:`bundled`,since:null}},iterm2:{label:`iTerm2`,xtversion:`iTerm2`,program:`iTerm.app`,programVersion:!0,term:null,links:{since:`3.1`},glyphs:{kind:`configured`}},alacritty:{label:`Alacritty`,xtversion:`alacritty`,program:null,programVersion:!0,term:`alacritty`,links:{since:`0.11.0`},glyphs:{kind:`configured`}},"apple-terminal":{label:`Terminal`,xtversion:null,program:`Apple_Terminal`,programVersion:!0,term:null,links:null,glyphs:{kind:`unread`}},vscode:{label:`VS Code`,xtversion:null,program:`vscode`,programVersion:!1,term:null,links:{since:`1.72`},glyphs:{kind:`unread`}}},QP=e=>ZP[e];function ete(e){return QP(e).glyphs.kind===`bundled`}function tte(e){return QP(e).glyphs.kind===`configured`}const $P=e=>QP(e).label,nte=[{since:`3.5.0`,from:57504,to:57507},{since:`3.5.0`,from:57520,to:57554},{since:`3.5.0`,from:57556,to:57556},{since:`3.5.6`,from:57558,to:57559}];function rte(e,t){let n=t.codePointAt(0);return nte.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&nF(e,t)===!0)}const eF=Object.keys(ZP);function tF(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function nF(e,t){let n=tF(e),r=tF(t);if(n===null)return null;for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t>i}return!0}function ite(e){for(let t of eF){let n=QP(t).xtversion;if(n!==null&&e.toLowerCase().startsWith(n.toLowerCase())){let r=e.slice(n.length).replace(/^[\s(]+/,``);return{name:t,version:/^[^\s)]+/.exec(r)?.[0]??null}}}return null}function rF(e){let t=eF.find(t=>QP(t).term===e);return t===void 0?null:{name:t,version:null}}function ate(e){let t=ite(e.termtype)??rF(e.termname);if(t!==null)return{kind:`known`,terminal:t};let n=/^[^\s(]*/.exec(e.termtype)[0];return n===``?{kind:`unnamed`,term:e.termname}:{kind:`unknown`,called:n}}function ote(e){let t=e.TERM_PROGRAM,n=eF.find(e=>QP(e).program===t),r=n===void 0?rF(e.TERM):{name:n,version:QP(n).programVersion?e.TERM_PROGRAM_VERSION??null:null};return r===null?t===void 0||t===`tmux`?{kind:`unnamed`,term:e.TERM??``}:{kind:`unknown`,called:t}:{kind:`known`,terminal:r}}function iF(e){switch(e.kind){case`known`:return $P(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function aF(e){switch(e.kind){case`known`:return $P(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function ste({name:e,version:t}){let n=QP(e).links;if(n===null)return{kind:`none`};if(n.since===null)return{kind:`draws`};if(t===null)return{kind:`unsaid`,since:n.since};let r=nF(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const cte=eF.filter(e=>QP(e).links!==null).map($P).join(`, `);function oF(e){if(e.kind===`failed`)return{kind:`unread`,reason:e.reason};let t=e.value.flatMap(({scope:e,path:t,settings:n})=>`statusLine`in n?[{from:{scope:e,path:t},line:n.statusLine}]:[]),n=t[0];if(n===void 0)return{kind:`absent`,read:e.value.map(e=>e.path)};if(!Mo(n.line))return{kind:`not-an-object`,value:n.line,from:n.from};for(let{from:e,line:r}of t){if(e.scope!==n.from.scope||!Mo(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function sF(e,t){if(e.kind===`failed`)return e;let n=e.value.find(e=>Object.hasOwn(e.env,t));return{kind:`ok`,value:n===void 0?{kind:`unset`}:{kind:`set`,value:n.env[t],from:{scope:n.scope,path:n.path}}}}const lte=[`managed`,`project`],ute=e=>!lte.includes(e.scope),dte={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:jo(t.projectDir)}),user:e=>({scope:`user`,path:e})},cF=[`drawn`,`boxes`],lF=1024*1024,uF=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function fte(e){switch(e.kind){case`claude-settings`:return`${e.kind} ${e.path.join(`.`)}=${JSON.stringify(e.value)} file=${JSON.stringify(e.file.path)} scope=${e.file.scope}`;case`post-mortems-read`:return`${e.kind} through=${e.through}`}}function dF(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const fF=fc.truecolor;function pF(e,t){switch(e.kind){case`unreported`:return{ok:!1,reason:"the client reported no tmux facts — re-run `cc-candybar install` to stage a current client"};case`outside`:return{ok:!0};case`inside`:return e.client.kind===`failed`?{ok:!1,reason:`tmux could not be asked: ${e.client.reason}`}:e.client.value===null?{ok:!0}:t(e.client.value,e.hint)}}const pte={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>pF(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=sF(t.sources,fF);if(r.kind===`failed`)return{ok:!1,reason:r.reason};let i=r.value;if(i.kind===`set`&&typeof i.value==`string`&&i.value!==``)return{ok:!1,reason:`${fF} is set in ${i.from.path} — restart Claude Code to apply`};let a=`Claude Code renders the bar in 256 colours inside tmux`,o=e=>({ok:!1,reason:a,fix:{kind:`claude-settings`,file:e,path:[`env`,fF],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=dte[i.from.scope](i.from.path,t.at);return s===null?{ok:!1,reason:`${a} — the value that counts is in managed settings, ${i.from.path}: set ${fF} to "1" there`}:o(s)})},mte={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>pF(e,e=>e.utf8?{ok:!0}:{ok:!1,reason:"tmux draws this terminal without UTF-8, so every glyph on the bar arrives as `_` — attach with `tmux -u`, or set a UTF-8 LC_ALL/LC_CTYPE/LANG in the shell that runs tmux"})},hte={name:`termWidth`,label:`terminal width`,takesMark:!1,probe:({width:e})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.columns===null?{ok:!1,reason:`${uF(e.value.of)} measured no width (no COLUMNS, and no terminal to ask — or the daemon refused the width sent, which the bar's diagnostics name), so the bar is laid out as if the terminal were 120 columns wide`}:{ok:!0,note:`${e.value.columns} columns, as ${uF(e.value.of)} measured`}},gte={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},_te={argument:`command argument`,environment:`$${FN}`,pick:`load-config pick`,unknown:`source unknown`};function vte({target:e,layers:t}){return e.source===`search`?t.length===0?zN(t):`${zN(t)} (searched)`:`${e.path} (${_te[e.source]})`}function yte(e){switch(e.kind){case`failed`:{let t=[...e.error.split(`
|
|
179
|
-
`).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return t.length===0?[`the config failed to load`]:t}case`loaded`:return[...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${gte[e]}`)]}}const bte={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{let t=vte(e),n=dF(yte(e));return n.ok?{ok:!0,note:t}:{...n,reason:`${t}: ${n.reason}`}}},mF="re-run `cc-candybar install`";function xte(e){if(e.kind===`failed`)return[`Launch Services could not be asked which app opens cc-candybar:// — ${e.reason}`];if(e.value===null)return[`no app is registered for cc-candybar:// — ${mF}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${mF}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${mF}`)}const Ste={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${mF}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${mF}`};case`lost`:return dF([...xte(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}};function hF({bundle:e,checkout:t},n){return{bundle:n.bundle.kind===`failed`?{kind:`unresolved`,reason:n.bundle.reason}:n.bundle.value===e?{kind:`same`}:{kind:`other`,path:n.bundle.value},source:n.client!==`native`||t===null?{kind:`uncompared`}:t.rustSource.kind===`failed`?{kind:`unreadable`,root:t.root,reason:t.rustSource.reason}:n.source===null?{kind:`unstamped`}:n.source===t.rustSource.value?{kind:`same`}:{kind:`other`,root:t.root}}}function gF(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${Vb.join(`|`)}>\``:e.checkout===null?mF:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function Cte(e,t,n){let{checkout:r}=e;if(n.kind===`unreported`)return[`the bar is drawn by a statusline client too old to say what it is — ${gF(e,`native`)}`];let{bundle:i,source:a}=hF(e,n);switch(i.kind){case`unresolved`:return[`the statusline client's bundle cannot be resolved: ${i.reason}`];case`other`:return[`the statusline client runs ${i.path}, not the daemon's ${e.bundle} — ${gF(e,n.client)}`];case`same`:break}if(n.client===`node`&&(t||r!==null))return[`the bar is drawn by the Node fallback, which starts node on every render — ${gF(e,`native`)}`];switch(a.kind){case`uncompared`:case`same`:return[];case`unreadable`:return[`${a.root}/rust-client could not be read: ${a.reason}`];case`unstamped`:return["the native client carries no source stamp, so which source it was built from is unknown — run `just install-rust`"];case`other`:return[`the native client was built from other source than ${a.root}/rust-client holds — run \`just install-rust\``]}}const _F=e=>{let t=`restarted since the bar was drawn, or has served 64 newer sessions`;return e.kind===`clicked`?`this daemon holds no render of this bar (it ${t})`:`this daemon holds no render of session ${e.sessionId}'s bar (its statusLine does not run cc-candybar — a \`claude -p\` session draws none — or the daemon ${t}; unset CLAUDE_CODE_SESSION_ID to judge every bar drawn recently)`},wte={name:`install`,label:`install`,takesMark:!1,probe:({install:e,sighted:t})=>{if(e.kind===`failed`)return{ok:!1,reason:`the daemon could not be asked which clients draw the bar: ${e.reason}`};let{daemon:n,nativeShipped:r,clients:i}=e.value;return i.length===0?{ok:!1,reason:t.kind===`recent`?`no statusline client has drawn a bar for this daemon in the last ${300/60} minutes — run the doctor again once the bar has redrawn; if it never does, the statusLine command does not run cc-candybar`:`${_F(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:dF([...new Set(i.flatMap(e=>Cte(n,r,e)))])}};function vF({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||_r(e.identity,t.value.through)):[]}function yF(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const Tte={name:`daemon`,label:`daemon`,takesMark:!1,probe:({daemon:{serving:e,processes:t,read:n}})=>{let r=t.kind===`failed`?[`the process table could not be read: ${t.reason}`]:[],i=t.kind===`ok`?yF(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return dF([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=vF(e.value,n),u=dF([...l.map(e=>`the daemon ran out of memory and restarted (${e.identity}) — post-mortem: ${Object.values(e.artifacts).join(`, `)}`),...c.kind===`failed`?[`the daemon's post-mortems could not be listed: ${c.reason}`]:[],...n.kind===`failed`&&!(c.kind===`ok`&&c.value.length===0)?[`which post-mortems were read could not be read: ${n.reason}`]:[],...r,...i.map(e=>`daemon ${e.pid} (started ${e.started}, rss ${mr(e.rss)} MB${e.ppid===1?``:`, child of ${e.ppid}`}) runs beside the one serving the bar (${a}) — \`kill ${e.pid}\``),...o.kind===`measured`&&o.charge.kind===`stand-in`?[`the daemon could not read what macOS charges it (${o.charge.unread}), so its memory limit judges ${o.charge.gap===0?`RSS, which counts pages macOS has reclaimed`:`RSS less the ${mr(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&br(o.charge.bytes,s)?[`the daemon holds ${wr(o.charge)} of its ${mr(s)} MB limit — at the limit it records a post-mortem and restarts`]:[]]);if(u.ok&&o.kind===`unmeasured`)return{ok:!0,note:`the daemon has not measured its memory yet`};let d=l[0];return u.ok||d===void 0?u:{...u,fix:{kind:`post-mortems-read`,through:d.identity}}}},bF=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function Ete(e,t){let n=iF(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?ste(e.terminal):{kind:`unknown`}}function Dte({identified:e,tmuxClient:t},n){let r=aF(e),i=Ete(e,n),a=iF(e)===null?bF:`${bF}, and the doctor remembers it for this terminal`,o=(()=>{switch(i.kind){case`draws`:return[];case`none`:return[`${r} draws no links (OSC 8), so nothing on the bar can be clicked — run Claude Code in a terminal that draws them: ${cte}`];case`older`:return[`${r} ${i.version} draws no links (OSC 8 came in ${i.since}) — update ${r}`];case`unsaid`:return[`${r} draws links (OSC 8) since ${i.since}, and did not say which release this is — ${a}`];case`unknown`:return[`the doctor does not know whether ${r} draws links (OSC 8) — ${a}`]}})(),s=n.kind===`failed`&&i.kind!==`draws`?[`the terminals a doctor click came back from could not be read: ${n.reason}`]:[],c=i.kind===`none`||t===null||t.features.includes(`hyperlinks`)?[]:[`tmux does not pass links through to ${r} — add \`set -as terminal-features ",${t.termname}:hyperlinks"\` to tmux.conf, then detach and reattach (tmux 3.4 or later)`];return[...o,...s,...c]}const Ote={name:`links`,label:`links`,takesMark:!1,probe:({sighted:e,terminal:t,clicked:n})=>{if(e.kind===`clicked`&&e.via===`link`)return{ok:!0};switch(t.kind){case`unreported`:return{ok:!1,reason:"the client reported no terminal — re-run `cc-candybar install` to stage a current client"};case`unasked`:return{ok:!1,reason:`tmux could not be asked which terminal is attached: ${t.reason}`};case`seen`:return dF(Dte(t,n))}}},xF=e=>e.filter(e=>e.role===`statusline`),SF={name:`effectRefresh`,label:`effect refresh`,takesMark:!1,probe:({frames:e,claudeSettings:{origin:t,elsewhere:n},sighted:r})=>{let i=[t,...n].flatMap(({sources:e,bars:t})=>TF(e,CF(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:wF(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:_F(r));let[o,...s]=i.flatMap(e=>e.ok?[]:[e]);if(o===void 0)return a;let c=[...new Set(s.map(e=>e.reason))].filter(e=>e!==o.reason);return c.length===0?o:{...o,more:c}}},CF=e=>{let t=xF(e).map(e=>e.frame);return t.includes(`moves`)?{kind:`moving`,wearing:`the bar moves (an effect, a fade, an animated segment, or an open menu counting down to its close)`}:t.includes(`can-move`)?{kind:`moving`,wearing:`the bar can start moving (an open menu, which flashes and closes on its own, a globals.effect rule, placements that fade in and out, or a placement with an effect of its own that is not drawn now)`}:t.includes(`still`)?{kind:`still`}:t.includes(`drawing`)?{kind:`unknown`,unseen:`the bar's latest render has not finished`}:t.length>0?{kind:`unknown`,unseen:`the bar's recent renders failed`}:e.length>0?{kind:`unknown`,unseen:"only a `cc-candybar frames` display has drawn this bar, not Claude Code's statusline"}:{kind:`none`}},wF=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function TF(e,t){let n=oF(e);if(n.kind===`present`&&n.refreshInterval===1)return{ok:!0,note:`statusLine.refreshInterval is 1 in ${n.from.path}`};switch(t.kind){case`none`:return null;case`still`:return{ok:!0};case`unknown`:return wF(t.unseen);case`moving`:break}let{wearing:r}=t;switch(n.kind){case`unread`:return{ok:!1,reason:`${r}, and Claude Code's settings could not be read: ${n.reason}`};case`absent`:return{ok:!1,reason:`${r}, and no settings file Claude Code reads here sets a statusLine (read: ${n.read.join(`, `)||`none`}) — the one that runs the bar comes from --settings, MDM or server-managed settings, which the doctor cannot read; set "refreshInterval": 1 beside its command there`};case`not-an-object`:return{ok:!1,reason:`${r}, and ${n.from.path} sets statusLine to ${JSON.stringify(n.value)}, not a statusLine object — ${n.from.scope===`user`?"re-run `cc-candybar install` to write one":`replace it there with the statusLine object that runs cc-candybar`}`};case`present`:{let{from:e,refreshInterval:t}=n,i=t===void 0?`its statusLine sets no refreshInterval, so Claude Code redraws it only on events`:typeof t==`number`&&t>1?`its statusLine redraws it only every ${t} s`:`its statusLine.refreshInterval is ${JSON.stringify(t)}, not a number of seconds Claude Code accepts (its minimum is 1)`;return ute(e)?{ok:!1,reason:`${r}, but ${i} (statusLine from ${e.path})`,fix:{kind:`claude-settings`,file:e,path:[`statusLine`,`refreshInterval`],value:1}}:{ok:!1,reason:`${r}, but ${i} — its statusLine is in ${e.scope===`managed`?`managed settings`:`the project's shared settings`}, ${e.path}: set "refreshInterval": 1 there`}}}}const EF=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function DF(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return aF(e);case`bundling`:case`unread`:case`configured`:return[$P(e.name),e.version].filter(e=>e!==null).join(` `)}}function OF(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return iF(e);case`bundling`:case`unread`:return $P(e.name);case`configured`:{let t=$P(e.name);return e.font.kind===`ok`?`${t} with ${e.font.value.font} (${e.font.value.from})`:`${t}, its font unread: ${e.font.reason}`}}}function kF(e){let t=OF(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${EF(e.glyphs)}`}}const AF={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=kF(e),r=e=>t.kind===`failed`&&n!==void 0?{ok:!1,reason:e,more:[`the mark book could not be read: ${t.reason}`]}:{ok:!1,reason:e,...n!==void 0&&{sighting:n}},i=e.terminal,a=DF(i);switch(n===void 0||t.kind===`failed`?null:t.value.nerdFont?.[n.id]??null){case`drawn`:return{ok:!0};case`boxes`:return r(`${a} draws ${EF(e.glyphs)} as boxes — set a Nerd Font as its font`);case null:break}switch(i.kind){case`unreported`:return r("the client reported no terminal — re-run `cc-candybar install` to stage a current client");case`unasked`:return r(`tmux could not be asked which terminal is attached: ${i.reason}`);case`unknown`:case`unnamed`:case`unread`:return r(`the doctor cannot read ${a}'s font`);case`bundling`:{let e=ZP[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:nF(i.version,e);if(t===!0)return{ok:!0};let n=$P(i.name);return r(t===null?`${n} ships Nerd Font symbols since ${e}, and did not say which release this is`:`${a} ships no Nerd Font symbols (they came in ${e}) — update ${n}, or set a Nerd Font as its font`)}case`configured`:{if(i.font.kind===`failed`)return r(`the doctor cannot read ${a}'s font: ${i.font.reason}`);let{font:e,from:t,lacks:n}=i.font.value;return n===null?r(`${a} is set to ${e} (${t}), which is not installed — install it or set a Nerd Font`):n.length===0?{ok:!0}:r(`${a} draws with ${e} (${t}), which has no ${EF(n)} — set a Nerd Font as its font`)}}}};function jF(e){return e.join(`, `)}function MF(e){return`or set missingData: "ignore" on ${jF(e)}`}function NF(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${jF(t)}: whether the forge CLI is ready could not be asked: ${n.reason}`];if(n.value===null)return[];let{cli:r,host:i,status:a}=n.value;return a===`ready`?[]:a===`missing`?[`${jF(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${MF(t)}`]:[`${jF(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${MF(t)}`]}function PF(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${jF(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${jF(n)}: no session of this Claude Code has drawn a bar for this daemon in the last ${300/60} minutes, so whether it sends rate_limits is unseen — run the doctor again once the bar has redrawn`:`${jF(n)}: ${_F(t)}, so whether Claude Code sends rate_limits is unseen — run the doctor again once the bar has redrawn`]:r.value.includes(`missing`)&&!r.value.includes(`carried`)?[`${jF(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${jF(n)}`]:[]}const FF={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>dF([...NF(e.pullRequests),...PF(e.rateLimits,t)])};function IF({path:e,answered:t,read:n}){switch(n.kind){case`absent`:return t?[`the transcript ${e} does not exist, though Claude Code has answered in its session — the bar's session cost, metrics and activity read nothing`]:[];case`failed`:return[`the transcript ${e} cannot be read: ${n.reason}`];case`ok`:{let{lines:t,unparsed:r,whole:i}=n.value;return r===0?[]:[`${r} of the ${t} lines ${i?`in`:`in the last ${lF/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const LF=[bte,wte,Tte,Ste,Ote,pte,mte,hte,SF,AF,FF,{name:`sessionData`,label:`session data`,takesMark:!1,probe:({transcripts:e,sighted:t})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.length===0?{ok:!1,reason:t.kind===`recent`?`no session has drawn a bar for this daemon in the last ${300/60} minutes, so no transcript was named — run the doctor again once the bar has redrawn`:`${_F(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:dF(e.value.flatMap(IF))}],RF=LF.filter(e=>e.takesMark);function zF(e){return LF.map(t=>({check:t,verdict:t.probe(e)}))}function BF(e){return LF.find(t=>t.name===e)}const VF=`${pi}doctor.`;function HF(e){let t=`${VF}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function UF({target:e}){return`configTarget=${e.source}`}function WF(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?iF(e.identified):null,i=t.kind===`failed`?`unread`:r===null?`-`:t.value.includes(r)?`yes`:`no`;return`tmuxLinks=${n===null?`-`:n.features.includes(`hyperlinks`)?`yes`:`no`} clicked=${i}`}function GF(e,t){let n=e.kind===`seen`?e.tmuxClient:null;return`cols=${t.kind===`failed`?`failed widthOf=-`:`${t.value.columns??`-`} widthOf=${t.value.of.kind}`} clientUtf8=${n===null?`-`:n.utf8?`yes`:`no`}`}function KF(e){if(e.kind===`failed`)return`clients=unasked`;let{daemon:t,clients:n}=e.value;return`clients=${n.map(e=>{if(e.kind===`unreported`)return`unreported/-/-`;let{bundle:n,source:r}=hF(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const qF=e=>`${e>=0?`+`:``}${mr(e)}`;function JF({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${yF(e,t.value).map(e=>e.pid).join(`,`)||`-`}`;if(e.kind===`failed`)return`${r} memory=unasked postMortems=unasked`;let{memory:i,limit:a,postMortems:o}=e.value,s=o.kind===`failed`||n.kind===`failed`?`unread`:`${vF(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Tr(i.charge)}${i.charge.kind===`stand-in`?`(${qF(-i.charge.gap)})`:``}:${mr(i.charge.bytes)}`}/${mr(a)} postMortems=${s}`}function YF(e){return`data=pr:${(()=>{if(e.pullRequests.kind===`unneeded`)return`-`;let t=e.pullRequests.fact;if(t.kind===`failed`)return`failed`;if(t.value===null)return`no-forge`;let{status:n}=t.value;return typeof n==`string`?n:`logged-out`})()},rateLimits:${(()=>{if(e.rateLimits.kind===`unneeded`)return`-`;let t=e.rateLimits.fact;if(t.kind===`failed`)return`failed`;let n=e=>t.value.filter(t=>t===e).length;return`${n(`carried`)}/${n(`missing`)}/${n(`unanswered`)}`})()}`}function XF(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>ZF(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${R(i)}`;let a=xF(r.flatMap(e=>e.bars));return`frames=${XP.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${R(i)}`}function ZF(e){let t=oF(e);switch(t.kind){case`unread`:return`failed`;case`absent`:case`not-an-object`:return t.kind;case`present`:return`${t.from.scope}:${t.refreshInterval===void 0?`-`:JSON.stringify(t.refreshInterval)}`}}function QF(e){let t=sF(e,fF);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${R(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function $F(e){if(e.kind===`failed`)return`transcripts=failed`;let t=t=>e.value.filter(e=>e.read.kind===t).length,n=e.value.reduce((e,t)=>e+(t.read.kind===`ok`?t.read.value.unparsed:0),0);return`transcripts=${t(`ok`)}/${t(`absent`)}/${t(`failed`)} unparsed=${n}`}function eI(e,t){if(e.kind===`none`)return`glyphs=- terminal=- font=- mark=-`;let{glyphs:n,terminal:r}=e,i=[...n].map(e=>e.codePointAt(0).toString(16)),a=(()=>{switch(r.kind){case`unreported`:case`unasked`:return r.kind;case`unknown`:return`unknown:${JSON.stringify(r.called)}`;case`unnamed`:return`unnamed:${JSON.stringify(r.term)}`;case`bundling`:case`unread`:case`configured`:return`${r.name}@${r.version??`-`}`}})(),o=(()=>{if(r.kind!==`configured`)return`-`;if(r.font.kind===`failed`)return`failed`;let{font:e,lacks:t}=r.font.value;return`${JSON.stringify(e)}:${t===null?`not-installed`:`lacks${t.length}`}`})(),s=kF(e),c=t.kind===`failed`?`unread`:s===void 0?`-`:t.value.nerdFont?.[s.id]??`-`;return`glyphs=${i.join(`,`)} terminal=${a} font=${o} mark=${c}`}function tI(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function nI(e){return e.flatMap(({check:e,verdict:t})=>{let n=HF(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:wy},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:tI(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?wy:Cy},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const rI={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function iI(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries(rI).map(([t,n])=>[`${e}${t}`,n]))}}const aI=`armed`,oI=`disarmed`,sI=`.armed`,cI=e=>e.endsWith(sI);function lI(e,t,n){let r=[...new Set(n.map(e=>e.when))].filter(e=>e!==`true`),i=t=>r.length===0?e:`${e}.${t}`,a={};for(let e=0;e<2**r.length;e++)a[i(e)]={do:[t,...n.filter(t=>t.when===`true`||e&1<<r.indexOf(t.when)).map(e=>e.action)]};let o=(e,t)=>e===r.length?`"${i(t)}"`:`(ternary ${o(e+1,t|1<<e)} ${o(e+1,t)} (${r[e]}))`;return{link:o(0,0),actions:a}}function uI(e,t,n){let r=`${e}${sI}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${aI}")`,s=lI(e,a,n);return{template:`{{ if ${o} }}{{ action ${s.link} "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:aI},[a]:{set:r,to:oI},...s.actions},armed:o,variables:{[e]:{kind:`state`,key:r,default:oI}},disarm:a}}const dI=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function fI(e){return typeof e==`string`&&dI.test(e)?{kind:`line`,line:e}:{kind:`refused`,reason:`a slash command is "/" then its name, e.g. "/compact" or "/model opus", on one line with no control characters, got ${JSON.stringify(e)}`}}function pI(e){let t=fI(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const mI=[`/compact`,`/model`],hI=`/clear`;function gI(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=uI(`${e}clear`,{arm:hI,confirm:`${hI} ✓ confirm`},[{action:n,when:`true`}]);return{template:mI.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${zb} }}`,actions:{...Object.fromEntries(mI.map(e=>[t(e),{slash:pI(e)}])),...r.actions,[n]:{slash:pI(hI)}},variables:r.variables,disarm:r.disarm}}const _I=Array.from({length:10},(e,t)=>(t+1)*1e5),vI=_I[0],yI=_I[_I.length-1];function bI(e){let t;try{t=ko(e)}catch(e){return L(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?F(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=vI&&n<=yI?F(n):L(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${vI}–${yI} tokens)`)}function xI(e,t){let n=Math.min(t??yI,yI),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:_I.filter(e=>e<r).at(-1)??0,higher:_I.find(e=>e>r&&e<=n)??0}}function SI(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${zb} }}{{ if gt .autocompact.lower 0 }} {{ action (printf "${e}%d" .autocompact.lower) "−" }}{{ end }}{{ if gt .autocompact.higher 0 }} {{ action (printf "${e}%d" .autocompact.higher) "+" }}{{ end }}{{ if gt .autocompact.window 0 }} {{ action "${e}auto" "↺" }}{{ end }}{{ end }}{{ end }}`,bg:`{{ if ne .autocompact.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .autocompact.window 0) (ne .autocompact.error "") }}`,actions:{[`${e}auto`]:{slash:pI(`/autocompact auto`)},...Object.fromEntries(_I.map(t=>[`${e}${t}`,{slash:pI(`/autocompact ${t}`)}]))}}}const CI=e=>`{{ if ge ${e} 1000000 }}{{ printf "%.1f" (divf ${e} 1000000) }}M{{ else if ge ${e} 1000 }}{{ printf "%.1f" (divf ${e} 1000) }}K{{ else }}{{ ${e} }}{{ end }}`,wI=`${pi}edit`,TI=`${pi}toolbar`,EI=iI(pi),DI=`${pi}commands`,OI=gI(`${DI}.`),kI=`${pi}autocompact`,AI=SI(`${kI}.`,CI),jI=e=>({kind:`segment`,name:e}),MI=`${pi}tab`,NI=e=>`${MI}.${e}`,PI=e=>`${NI(e)}.toggle`,FI=e=>({variable:MI,key:MI,member:e}),II=`${pi}save`,LI=`${pi}preset.save`,RI=`${pi}preset.delete`,zI=e=>`${pi}${e}`,BI=e=>`${pi}apply.${e}`,VI=e=>`${pi}reset.${e}`,HI=`${pi}themeDefault.save`,UI=`${pi}themeDefault.differs`,WI=`${pi}themeDefault.theme`,GI={when:`{{ .${UI} }}`,template:`{{ action "${HI}" (printf "⤓ default for %s" .${WI}) }} {{ swatch "${BI(`theme`)}" .${WI} }}`},KI=`${pi}resetAll`,qI=`${gi}.toggle`,JI=`${pi}undo`,YI=`${pi}back`,XI=`${YI}.step`,ZI=`${pi}navigation.back`,QI=YI,$I={template:`{{ if gt .${ZI} 0 }}{{ action "${YI}" "◁" }}{{ else }}{{ fg (${jN}) "◁" }}{{ end }}`},eL=`${pi}redo`,tL=`${pi}doctor`,nL=`${tL}.run`,rL=e=>`${tL}.fix.${e}`,iL=(e,t)=>`${tL}.mark.${e}.${t}`,aL=e=>`${tL}.${e}`,oL={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},sL=Gj(`${pi}pickers`),cL=e=>`${pi}${e}`,lL=e=>`${cL(e)}.toggle`,uL=e=>lM(e)?Gj(`${pi}${e}Pickers`):sL,dL=e=>{let t=uL(cM[oM[e].beside]);return{variable:t,key:t,member:e}},fL={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${RI}" (printf "🚮 delete %s" .${Mx.preset.effectiveVar}) }}`}},pL=(e,t)=>`${pi}list.${e}.${t}`,mL=e=>`${pi}resettable.${e}`,hL=e=>e.length===0?`false`:`(or ${e.map(e=>`(and (${e.shown}) .${mL(e.name)})`).join(` `)})`,gL=Vb.map(e=>[Bb[e].switch.setting,e]),_L={variables:{},actions:{},segments:{}},vL=Object.fromEntries(gL.map(([e,t])=>[e,gN(`${pi}help.${e}`,kN[t],[],_L)])),yL=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],bL=e=>{let t=t=>`.${Kb(e,t)}`,n=yL.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if eq .${Mx[Bb[e].switch.setting].effectiveVar} ${JSON.stringify(Bb[e].switch.on)} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},xL=`{{ if .diagnostics.label }} {{ bg .diagnostics.bg (fg .diagnostics.fg (action "${yi}" .diagnostics.label .diagnostics.open)) }}{{ end }}`,SL=`${pi}fps`,CL=`{{ if eq .${Wb(`by`)} "feed" }}{{ printf "%3s" (printf "≤%d" (int .${Wb(`fps`)})) }} fps{{ else }}${`polled`.padStart(7)}{{ end }}`,wL=Object.fromEntries(gL.map(([e,t])=>[e,bL(t)])),TL=e=>sM.filter(t=>oM[t].beside===e),EL=Object.keys(Mx).map(e=>{let t=Mx[e],n=cM[e];return{...t,name:e,place:n,control:nM({label:t.label,domain:gM(t.configKey)},t.sessionKey,t.effectiveVar,BI(e),uL(n)),beneath:t.previews.map(e=>fL[e]),help:[vL[e]].filter(e=>e!==void 0),submenus:TL(e)}}),DL=e=>EL.filter(t=>t.place===e),OL=e=>EL.filter(t=>uM(t.place,e)),kL=e=>t=>`(print ${oi(t)} (ternary ${oi(` •`)} "" ${hL(OL(e))}))`,AL=e=>DL(e).flatMap(e=>[HL(e),...e.help,...e.submenus.map(e=>ti(cL(e),dL(e),YL(e),`drop`))].map(t=>({...t,when:`{{ ${e.shown} }}`})));new Set(EL.flatMap(e=>[e.sessionKey,e.configKey]));const jL=uI(KI,{arm:`⟲`,confirm:`⟲ reset all?`},EL.map(e=>({action:VI(e.name),when:e.shown}))),ML=[`unsaved`,`history.undo`,`history.redo`],NL=e=>`${pi}${e}`,PL=NL(`unsaved`),FL=(e,t)=>({body:t,shown:`(gt .${NL(e)} 0)`}),IL=[FL(`unsaved`,`{{ action "${II}" (printf "💾 save %d" .${PL}) }}`),FL(`history.undo`,`{{ action "${JI}" "↶" }}`),FL(`history.redo`,`{{ action "${eL}" "↷" }}`),{body:jL.template,shown:`(or ${hL(EL)} ${jL.armed})`}],LL={when:`{{ or ${IL.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+IL.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},RL=[{step:jL,place:`door`},{step:OI,place:`session`}],zL=e=>e.map(e=>e.step.disarm),BL=zL(RL),VL=zL(RL.filter(e=>e.place!==`door`));function HL(e){let t=zI(e.name);return e.control.kind===`inline`?jI(t):ti(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>jI(pL(e.name,n)))},`drop`)}function UL(e){return e===gi}function WL(e){let t=jI(gi);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[WL(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[t,e]};if(e.when===void 0)return{...e,children:[t,...e.children]};let{when:n,children:r,...i}=e;return{...i,children:[t,{kind:`container`,direction:i.direction,when:n,children:r}]}}function GL(e){return KL(e)>0?e:WL(e)}function KL(e){let t=0;for(let n of Fy(e))n.kind===`segment`&&UL(n.name)&&(t+=1);return t}function qL(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&UL(e.name)||e.opens!==void 0&&qL(e.opens.body,!0):e.children.some(e=>qL(e,n))}const JL={door:{direction:`horizontal`,content:[jI(QI)],after:[jI(wI),jI(II)]},session:{direction:`vertical`,content:[jI(TI),{kind:`container`,direction:`horizontal`,children:[jI(DI),jI(kI)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[jI(LI)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[jI(tL),...LF.map(e=>jI(aL(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[jI(HI)]},toggles:{direction:`horizontal`,content:[],after:[]}};function YL(e){let{direction:t,content:n,after:r}=JL[e];return{kind:`container`,direction:t,children:[...n,...AL(e),...r]}}function XL(e){return e.kind===`segment`?UL(e.name)?{kind:`container`,direction:`horizontal`,children:[ti(e.name,vi,QL,`above`),jI(SL)]}:e:$L(e)}function ZL(){return{kind:`container`,direction:`vertical`,children:[YL(`door`),{kind:`container`,direction:`horizontal`,children:iM.map(({member:e})=>ti(NI(e),FI(e),YL(e),`drop`))}]}}const QL=ZL();function $L(e){return{...e,children:e.children.map(e=>XL(e))}}function eR(e){let t={variables:{[gi]:si(gi,Yr),[yi]:{kind:`state`,key:yi,default:`0`}},actions:{[qI]:P(gi,_i),[yi]:{set:yi,int:!0},[gi]:{do:[qI,...BL]},[nL]:{doctor:`run`},...EI.actions,...OI.actions,...AI.actions,[II]:{save:!0},[JI]:{undo:!0},[XI]:{back:!0},[YI]:{do:[XI,...BL]},[eL]:{redo:!0},[LI]:{preset:`save`},[HI]:{themeDefault:`save`},[RI]:{preset:`delete`,name:`{{ .${Mx.preset.effectiveVar} }}`}},segments:{[gi]:{template:`{{ $door := ${ai(gi,oi(e),oi(`✖`))} }}{{ if ${ri(vi)} }}{{ fg (keptOn (roleTextOn "error" (bgOf)) (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+xL},[SL]:{template:CL},[TI]:{template:EI.template},[DI]:{template:OI.template,when:OI.when},[kI]:{template:AI.template,bg:AI.bg,when:AI.when},[QI]:$I,[II]:LL,[HI]:GI,[LI]:{template:`{{ action "${LI}" "+ preset" }}`},[tL]:{template:`{{ action "${nL}" "🩺 doctor" }}`},[wI]:{template:`{{ action "${oN}" "✎ arrange" "✎ done" }}`}}};t.variables[UI]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[WI]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[ZI]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of ML)t.variables[NL(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[MI]=si(MI,Yr);for(let{member:e,label:n}of iM){t.actions[PI(e)]=P(MI,e),t.actions[NI(e)]={do:[PI(e),...VL]};let r=kL(e);t.segments[NI(e)]={template:`{{ ${ai(NI(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,OI.variables,jL.variables),nR(t),tR(t),t}function tR(e){for(let t of LF){let n=HF(t.name),r=rL(t.name);for(let t of Object.values(n))e.variables[t]={kind:`state`,key:t,default:``};e.actions[r]={doctor:`fix`,check:t.name};let i=t.takesMark?cF:[];for(let n of i)e.actions[iL(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${iL(t.name,e)}" "${oL[e]}" }}`).join(``);e.segments[aL(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ if ne .${n.reason} "" }} — {{ .${n.reason} }}{{ end }}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${Cy}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function nR(e){for(let t of EL){Object.assign(e.actions,t.control.actions);let n=VI(t.name);e.actions[n]={reset:t.configKey},e.variables[mL(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${mL(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[zI(t.name)]={template:`${t.control.template}${wL[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[pL(t.name,r)]=n})}Object.assign(e.actions,jL.actions),Object.assign(e.variables,_L.variables),Object.assign(e.actions,_L.actions),Object.assign(e.segments,_L.segments);for(let t of sM){let n=dL(t);e.actions[lL(t)]=P(n.key,n.member),e.segments[cL(t)]={template:`{{ action "${lL(t)}" ${kL(t)(oM[t].trigger)} }}`}}}function rR(e){let{variables:t,actions:n}=hN();Object.assign(e.variables,t),Object.assign(e.actions,n)}function iR(e){let t=eR(e.globals.menuGlyph??`🍫`);rR(t);let n={...e.presets},r=[];for(let t of mS(e.presets)){let{node:i}=_S(e,t),a=XL(GL(i));r.push(a),n[t]={...gS(e.presets,t),root:a}}let i=Vj(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const aR=`${fi}live`,oR=[`☐ live`,`☑ live`],sR=`${fi}done`,cR=`${fi}cancel`,lR=`${fi}rewind`,uR=`${fi}changes`,dR=`(gt .${uR} 0)`,fR=`(or ${dR} (gt .${PL} 0))`,pR={variable:aR,key:aR,member:Xr};function mR(e){return`${fi}configuring.p${e}`}function hR(e){return`and ${ri(uN)} (not ${ri(pR)}) (ne .${mR(e)} "true")`}function gR(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${aN} "${ei(e)}")`).join(` `)} false }}`}}function _R(e,t,n){return`{{ if ${hR(e)} }}${t}{{ else }}${n}{{ end }}`}const vR=`{{ and ${ri(uN)} .preset.customized }}`,yR=hi;function bR(e){return new Map([...wS(e),...SR(e)])}const xR=`${fi}addable`;function SR(e){return new Map([[xR,{members:Object.keys(e.segments).filter(e=>!yR(e)),library:{groups:QM.map(e=>({id:e,label:$M[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function CR(e,t,n){return n.segments[e]={template:t,when:dN,bg:vN},{kind:`segment`,name:e}}function wR(e,t,n){let r=`${fi}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${yv}`}) (action "${r}" "✖") }}`}function TR(e){return`{{ if ${ri(uN)} }}${e}{{ end }}`}function ER(e,t){return e.reduce((e,t)=>`{{ if and ${ri(uN)} ${ri(t)} }}true{{ else }}${e}{{ end }}`,t)}function DR(e){return e.flatMap(e=>[...Fy(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function OR(e,t,n){return`${cN}${e}.${t}.${n}`}function kR(e,t,n,r){let i=jy(n),a=`${fi}${e.presetIdent}`,o=lN(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=Gj(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:Yr},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:aN,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=OR(e.presetIdent,i,r),l=`${cN}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:tb(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=nM(eM(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};e.artifacts.segments[d]={template:f.template};let p=f.list.rows.map((t,n)=>{let r=`${d}.list.${n}`;return e.artifacts.segments[r]={template:t},{kind:`segment`,name:r}});return ti(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${wN}" }}`,ref:{variable:aN,key:aN,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const AR=`${fi}label:`;function jR(e){if(e.startsWith(AR)){let t=e.slice(AR.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function MR(e,t,n,r){let i=jy(e),a=NR(n,i,e,t,i),o=Object.fromEntries(Xy.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...ti(a,r.ref,r.body,`drop`,ER([r.ref],`{{ ${hR(n.presetIdent)} }}`)),...Object.keys(o).length>0&&{settings:o},drafts:Object.fromEntries(Xy.map(e=>[e,r.drafts[e]]))}}function NR(e,t,n,r,i){let a=`${AR}${t}:${n.name}`;return e.artifacts.segments[a]={template:`{{ "${ei(i)}" }}`,...r.palette!==void 0&&{palette:r.palette}},a}function PR(e,t,n,r){let i=jy(e),a=n?[LR(r,String(r.posCounter.n++),i,`before`)]:[],o=String(r.posCounter.n++),s=LR(r,o,i,`after`),c=wR(r,o,i),l=r.segments[e.name],u=kR(r,o,e,Zy(l)),d=TR(c),f=TR(u.term);return[...a.map(e=>CR(e.host,e.template,r.artifacts)),{...MR(e,l,r,u),lead:d,trail:f},{...t,when:_R(r.presetIdent,`false`,e.when??`true`),lead:d,trail:f,drafts:u.drafts},CR(s.host,s.template,r.artifacts)]}function FR(e){return E.join(E.basename(E.dirname(e)),E.basename(e))}function IR(e,t,n,r){let i=r.segments[e.name],a=jy(e);return[{kind:`segment`,name:NR(r,`${a}/${r.presetIdent}`,e,i,`${a} · ${FR(t.file)} ${t.entry}`),when:`{{ ${hR(r.presetIdent)} }}`},{...n,when:_R(r.presetIdent,`false`,e.when??`true`)}]}function LR(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${fi}${i}.insert.${t}`,s=`${fi}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:xR,anchor:n,relation:r};let c=Uj(o),l=Wj(s,o,void 0),u=qj(l),d=Kj(l,c);return a.variables[l]={...si(l,Yr),within:[uN]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=P(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${ri({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${yv}`}) $m }}{{ end }}`}}function RR(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!yR(e.name)&&e.insertedBy===void 0),i=e=>RR(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Py(o,i);if(yR(o.name)){n.push(s);continue}let c={kind:`container`,direction:`horizontal`,children:o.insertedBy===void 0?PR(o,s,a===r,t):IR(o,o.insertedBy,s,t),unit:!0};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[c]}:c)}return{...e,children:n,...e.when!==void 0&&{when:ER(DR(n),_R(t.presetIdent,`true`,e.when))}}}function zR(e,t,n,r,i,a,o){let s=`${fi}${t}.resetLayout`,c=`${fi}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:vR},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},BR(e,o)]}}function BR(e,t){if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t]};let n=e.children.at(-1);return e.direction===`vertical`&&n!==void 0&&(n.kind===`segment`||n.when===void 0)?{...e,children:[...e.children.slice(0,-1),BR(n,t)]}:{...e,children:[...e.children,t]}}function VR(e,t,n,r,i,a){let{node:o}=_S(e,t),s={presetIdent:Hj(t),rootKey:GM(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=RR(o,s);return n.variables[mR(s.presetIdent)]=gR(s.configured),zR(c,s.presetIdent,s.rootKey,n,r,i,a)}function HR(e){let t={variables:{},actions:{},segments:{}},n=gN(`${fi}help`,ON,[uN],t);t.variables[aR]=si(aR,Yr),t.actions[aR]=P(aR,pR.member),t.segments[aR]={template:ii(aR,...oR),when:dN};let r={kind:`segment`,name:aR},i=n;t.variables[uR]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[sR]={do:[II,oN]},t.segments[sR]={template:`{{ if ${fR} }}{{ action "${sR}" "✓ save" }}{{ else }}{{ action "${sR}" "✓ done" }}{{ end }}`,when:dN},t.actions[lR]={rewind:!0},t.actions[cR]={do:[lR,oN]},t.segments[cR]={template:`{{ action "${cR}" "↩ cancel" }}`,when:`{{ and ${ri(uN)} ${dR} }}`};let a=[{kind:`segment`,name:sR},{kind:`segment`,name:cR}],o={...e.presets},s=[];for(let n of mS(e.presets)){let c=VR(e,n,t,a,r,i);s.push(c),o[n]={...gS(e.presets,n),root:c}}let c=Vj(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function UR(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function WR(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function GR(e,t,n){let r=Ny(e,new Set(n.map(My).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const KR=/^-?\d+$/;function qR(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function JR(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!KR.test(t))return{ok:!1,reason:`${e} must be an integer, got "${t}"`};let n=t[0]===`-`,r=(n?t.slice(1):t).replace(/^0+/,``);return r===``?{ok:!0,value:`0`}:{ok:!0,value:n?`-${r}`:r}}}function YR(e,t,n){return r=>r?KR.test(r)?{ok:!0,value:String(Math.max(e,Math.min(t,parseInt(r,10))))}:{ok:!1,reason:`${n} must be an integer, got "${r}"`}:{ok:!1,reason:`${n} value is required`}}function XR(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!KR.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i}}return{kind:`int`}}function ZR(e){return e===`config`?`set-config`:`set-state`}function QR(e,t,n){return t.kind===`int`?JR(`menu page "${e}"`):t.kind===`range`?YR(t.min,t.max,`${n} stepper "${e}"`):qR(t.allowed,`${n} "${e}"`,ZR(n))}function $R(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:XR(e,n,t)}))}function ez(e,t,n,r){let i=new Map(Object.entries(e)),a=new Map,o=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of n)if(o.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let s=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...n];for(let{key:t,spec:n}of $R(s,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,QR(t,n,r)),n.kind===`range`&&a.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>a.get(e)??null}}function tz(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};ez(e,[o],[],t),r.push(o),i++;let s=!0;return()=>{s&&(s=!1,r.splice(r.indexOf(o),1),i++)}},gateFor(o){let s=a.get(o);if(s?.epoch===i)return s.gate;let c=ez(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}function nz(){return tz({},`config`,oz)}function rz(e,t){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:ES(e.from,t).members}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[UR({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[UR({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:ES(e.insertSegmentFrom,t).members.map(t=>UR({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function iz(e){let t=new Set;for(let n of Object.values(e.actions)){`reset`in n&&t.add(n.reset);let e=`persist`in n?YM(n.persist):null;e?.scope===`preset-root`&&t.add(GM(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function az(e){let t=bR(e);return[...iz(e),...Object.values(e.actions).flatMap(e=>rz(e,t))]}function oz(e){return $R(az(e),`config`)}const sz=qv(),cz=new Set(sz),lz=new Set(hy),uz=e=>e?cz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${sz.join(`, `)})`}:{ok:!1,reason:`theme name is required`},dz=e=>e?lz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${hy.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},fz=new Set([`1`,`true`]),pz=new Set([`0`,`false`]),mz={endcaps:dz,theme:uz,"toolbar-expanded":e=>fz.has(e)?{ok:!0,value:`1`}:pz.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}};function hz(){return tz(mz,`state`,yz)}function gz(e,t){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:ES(e.from,t).members}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function _z(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(mz,e.key))}function vz(e){let t=bR(e);return _z(Object.values(e.actions).flatMap(e=>gz(e,t)))}function yz(e){return $R(vz(e))}function bz(e){let t=hz(),n=nz();for(let{key:n,allowed:r}of e.state)t.register(n,r);for(let{key:t,allowed:r}of e.config)n.register(t,r);return{state:t,config:n}}const xz=`update.dismissed`,Sz=`updateNotice`,Cz=Mx.updateNotice.sessionKey;function wz(){return bz({config:[{key:Sz,allowed:[`false`]}],state:[{key:Cz,allowed:[`false`]},{key:xz,allowed:[]}]})}function Tz(e){try{return l.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function Ez(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:kz(t.segments,Dz(t.segments,e.segments??{})),root:oS(e.root??$x,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:kz(t.presets,Oz(t.presets,e.presets??{})),themeDefaults:kz(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function Dz(e,t){let n=(t,n,r)=>r[n]===void 0?r:{...r,[n]:{...e[t]?.[n],...r[n]}};return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,n(e,`partials`,n(e,`settings`,t))]))}function Oz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.globals===void 0?n:{...n,globals:{...e[t]?.globals,...n.globals}}]))}function kz(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const Az=new Map([[`gitTaculous`,{kind:`built-in`,to:`gitaculous`}],[`git`,{kind:`built-in`,to:`gitaculous`}],[`settings.menu`,{kind:`built-in`,to:`candybar.menu`}],[`ticket`,{kind:`plugin`,to:`plugins.lit.ticket`,source:`promptctl/links-issue-tracker`}],[`ceiling`,{kind:`removed`,why:`the program it showed draws it through a cc-candybar plugin of its own now — delete this reference, or place that plugin's segment`}],[`themeSwitcher`,{kind:`removed`,why:'the settings menu\'s 🎨 theme control steps themes — delete this reference, or write your own `{{ carousel "apply" "open" "label" }}`'}]]);function jz(e){let t=Az.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`;case`removed`:return` (the built-in segment "${e}" was removed: ${t.why})`}}function Mz(e,t,n,r){return n.cache===void 0?(e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${Vy.join(`, `)})`,line:q(e.source,t.split(`.`))}),null):Fz(e,`${t}.cache`,n.cache)}function Nz(e){return{required:!0,json:Iz(),parse:(t,n,r,i)=>Mz(t,n,i,e)??void 0}}const Pz={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Rz(n)?{ttl:n}:vb(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${J(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return vb(e,t,`cache.watch_file must be a path string, got ${J(n)}`);let r=Ab(`cache.watch_file`,n);return r===null?{watch_file:n}:vb(e,t,r)}},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:vb(e,t,`cache.depends_on must be an array of variable-name strings, got ${J(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:vb(e,t,`cache.key must be a non-empty template string, got ${J(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:vb(e,t,`cache.never must be the literal boolean true, got ${J(n)}`)}}};function Fz(e,t,n){return yb(e,Pz,t,n)}function Iz(){return Lb(Pz)}const Lz=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Rz(e){return Lz.test(e)}const zz=new Map([[`session.budget.amount`,{segment:`session`,setting:`budget`}],[`session.budget.warningThreshold`,{segment:`session`,setting:`warnAt`}],[`today.budget.amount`,{segment:`today`,setting:`budget`}],[`today.budget.warningThreshold`,{segment:`today`,setting:`warnAt`}],[`block.budget.heatThreshold`,{segment:`block`,setting:`warnAt`}],[`block.budget.warningThreshold`,{segment:`block`,setting:`errorAt`}],[`weekly.budget.heatThreshold`,{segment:`weekly`,setting:`warnAt`}],[`weekly.budget.warningThreshold`,{segment:`weekly`,setting:`errorAt`}],[`burn.eta.errorMinutes`,{segment:`burnrate`,setting:`errorWithin`}],[`burn.eta.warnMinutes`,{segment:`burnrate`,setting:`warnWithin`}]]);function Bz(e){return`it became the "${e.setting}" setting of each "${e.segment}" placement — set it on the placement where a row places "${e.segment}" ({ seg: "${e.segment}", settings: { ${e.setting}: <value> } }), or redeclare segments.${e.segment}.settings.${e.setting} with the default every placement should start from`}function Vz(e){let t=zz.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${Bz(t)}`}function Hz(e){let t=zz.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${Bz(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const Uz=new Map([[`git.timeSinceCommit`,`the payload stores the commit's date as "git.committedAt" (epoch seconds), and the bundled template variable "git.timeSinceCommit" computes its age at the draw: drop this declaration`],[`block.etaMinutes`,`the bundled template variable "block.etaMinutes" computes it at the draw: drop this declaration`],[`weekly.etaMinutes`,`the bundled template variable "weekly.etaMinutes" computes it at the draw: drop this declaration`]]),Wz=new Map([[`branch`,{read:`.git.branch`,declare:{kind:`input`,path:`git.branch`,default:``},note:`when HEAD is on no branch it reads "detached", where this kind read ""`}],[`sha`,{read:`.git.sha`,declare:{kind:`input`,path:`git.sha`,default:``}}],[`dirty`,{read:`(ne .git.status "clean")`,declare:{kind:`template`,template:`{{ ne .git.status "clean" }}`,type:`boolean`}}],...[`ahead`,`behind`,`stash`].map(e=>[e,{read:`.git.${e}`,declare:{kind:`input`,path:`git.${e}`,type:`number`,default:0}}])]);function Gz(e){let t=e=>typeof e==`string`&&e.includes(`"`)&&!e.includes(`'`)?`'${e}'`:JSON.stringify(e);return`{ ${Object.entries(e).map(([e,n])=>`${e}: ${t(n)}`).join(`, `)} }`}function Kz(e){let t=`kind "git" is retired: every git fact is an input over the payload's git lane, which the bundled default already declares — drop this declaration and`,n=typeof e.field==`string`?Wz.get(e.field):void 0;if(n===void 0){let e=[...Wz.values()].map(({read:e})=>e);return`${t} read whichever of ${e.slice(0,-1).join(`, `)} or ${e.at(-1)} it stood for, where it was read`}let r=n.note===void 0?``:` (${n.note})`;return`${t} read ${n.read} where it was read${r}, or declare ${Gz(n.declare)} under a name of your own`}function qz(e,t,n){if(n===void 0)return{};if(!db(n))return e.issues.push({path:t,message:`${t} must be an object, got ${fb(n)}`,line:q(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=bb(e,_B,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function Jz(){return{required:!0,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.value;if(typeof i!=`string`&&typeof i!=`number`&&typeof i!=`boolean`){e.issues.push({path:`${t}.value`,message:`literal value must be string|number|boolean, got ${fb(i)}`,line:q(e.source,t.split(`.`))});return}return i}}}function Yz(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Iee(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const Xz={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:vb(e,t,`parse.text must be the literal boolean true, got ${J(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?Zz(e,t,n):vb(e,t,`parse.regex must be a pattern string, got ${J(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:vb(e,t,`parse.json must be the literal boolean true, got ${J(n)}`)}}};function Zz(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return vb(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:vb(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function Qz(){return{required:!1,json:Lb(Xz),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:q(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:yb(e,Xz,`${t}.parse`,r.parse)??void 0)}}function $z(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>db(r.parse)&&`json`in r.parse?eB(e,t,r.default):cb(e,t,r,`default`)}}function eB(e,t,n){if(n!==void 0)return tB(n)?n:vb(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${J(n)}`)??void 0}function tB(e){return e!==null&&nB(e)}function nB(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(nB);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(nB)}default:return!1}}const rB={value:Jz(),default:wb()};function iB(){let e=kb();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:Uz.get(a);return o===void 0?a:vb(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const aB={path:iB(),type:Mb([`string`,`number`,`boolean`]),default:Yz()},oB={name:kb(),default:wb()},sB={path:jb(),readMode:Mb([`whole`,`first-line`]),parse:Qz(),cache:Nz(`file`),default:$z()},cB={command:kb(),parse:Qz(),cache:Nz(`shell`),default:$z()};function lB(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const uB={template:kb(),type:Mb([`string`,`number`,`boolean`]),default:Yz()},dB=lB(`a template variable recomputes whenever a variable it reads changes`),fB={layout:kb(),default:wb()},pB=lB(`a time variable reads the instant its render is drawn at`),mB={key:kb(),default:wb()},hB=`kind`;function gB(e,t,n={}){return{...xb(hB,e,t),parse:(r,i,a)=>{mb(r,n,i,a);let o=hb(r,t,i,a);return o===null?null:{kind:e,...o}}}}const _B={tag:hB,noun:`source kind`,memberNoun:`variable`,arms:{literal:gB(`literal`,rB),input:gB(`input`,aB),env:gB(`env`,oB),file:gB(`file`,sB),shell:gB(`shell`,cB),template:gB(`template`,uB,dB),time:gB(`time`,fB,pB),state:gB(`state`,mB)},retired:{git:Kz}};function vB(){return Ib(_B)}function yB(){return{type:`object`,additionalProperties:vB()}}const bB=/^[A-Za-z_][A-Za-z0-9_]*$/,xB={pattern:bB.source},SB={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},CB={type:`object`,additionalProperties:!1,required:[`label`,`domain`,`default`],properties:{label:{type:`string`,pattern:`^[^\\n\\r]+$`},domain:{anyOf:[{const:`bool`},{type:`array`,items:{type:`string`,pattern:`^[^/\\n\\r]+$`},minItems:1,uniqueItems:!0},{type:`object`,additionalProperties:!1,required:[`min`,`max`],properties:{min:{type:`integer`},max:{type:`integer`},step:{type:`integer`,minimum:1},atLeast:{type:`string`,...xB}}}]},default:SB}},wB=[`label`,`domain`,`default`],TB=[`min`,`max`,`step`,`atLeast`];function EB(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,t.split(`.`))})}function DB(e,t,n){if(n===`bool`)return`bool`;if(Array.isArray(n)){let r=n.filter(e=>typeof e==`string`);if(n.length===0||r.length!==n.length)return EB(e,t,`a list domain must be a non-empty list of words, got ${JSON.stringify(n)}`);if(new Set(r).size!==r.length)return EB(e,t,`a list domain names each word once, got ${JSON.stringify(n)}`);let i=r.filter(e=>e===``||e.includes(`/`)||/[\n\r]/.test(e));return i.length>0?EB(e,t,`a list domain's words must be non-empty, slash-free, and newline-free — configure mode writes each on the set-state wire — got ${JSON.stringify(i)}`):r}if(db(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!TB.includes(e)).length===0&&Number.isInteger(r)&&Number.isInteger(i)&&r<=i&&Number.isInteger(a)&&a>=1&&(o===void 0||typeof o==`string`)?{min:r,max:i,step:a,...o!==void 0&&{atLeast:o}}:EB(e,t,`a range domain is { min, max, step?, atLeast? } with integers min ≤ max, a whole step ≥ 1, and atLeast naming another range setting, got ${JSON.stringify(n)}`)}return EB(e,t,`domain must be "bool", a list of words, or { min, max }, got ${J(n)}`)}function OB(e,t,n){if(!db(n))return EB(e,t,`${t} must be { label, domain, default }, got ${fb(n)}`);for(let r of Object.keys(n))wB.includes(r)||EB(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${wB.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||EB(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${J(r)}`);let a=DB(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!kB(n.default)||!eb(o,n.default)?EB(e,`${t}.default`,`default must be ${rb(o)}, got ${J(n.default)}`):o}function kB(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const AB={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${Jy}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function jB(e){return Xy.includes(e)}function MB(){return{required:!1,json:{type:`object`,propertyNames:{...xB,not:{enum:[...Xy]}},additionalProperties:CB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!db(i))return EB(e,a,`${a} must be an object of name → { label, domain, default }, got ${fb(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!bB.test(t)){EB(e,`${a}.${t}`,`setting name "${t}" is read as .settings.${t} in a template, so it must be an identifier (letters, digits, _; not starting with a digit)`);continue}if(jB(t)){EB(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${AB[t]}`);continue}let r=OB(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const NB=mi.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function PB(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${NB})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!hi(i)?i:EB(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${mi.map(e=>`"${e}"`).join(`, `)} namespaces, got ${J(i)}`)}}}function FB(){return{required:!1,json:{type:`object`,propertyNames:xB,additionalProperties:SB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!db(i))return EB(e,a,`a placement's "settings" must be an object of setting name → value, got ${fb(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))kB(n)?o[t]=n:EB(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${fb(n)}`);return o}}}function IB(e){return new Set(Object.keys(e.segments).filter(e=>!hi(e)))}function LB(e,t,n){if(t===void 0)return{};if(!db(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${fb(t)}`,line:q(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=pb(e,n.has(i)?qB:KB,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function RB(e,t,n,r){let i=r[n];if(typeof i==`string`)return i;if(Array.isArray(i)){let r=!0,a=[];for(let[o,s]of i.entries()){if(typeof s==`string`){a.push(s);continue}r=!1,e.issues.push({path:`${t}.${n}[${o}]`,message:`${t}.${n}[${o}] must be a string, got ${fb(s)}`,line:q(e.source,[...t.split(`.`),n])})}return r?a.join(``):void 0}e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be a string or an array of strings, got ${fb(i)}`,line:q(e.source,[...t.split(`.`),n])})}const zB={anyOf:[{type:`string`},{type:`array`,items:{type:`string`}}]};function BB(){return{required:!0,json:zB,parse:(e,t,n,r)=>r[n]===void 0?vb(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own${jz(t.slice(9))}`)??void 0:RB(e,t,n,r)}}function VB(){return{required:!1,json:zB,parse:(e,t,n,r)=>r[n]===void 0?void 0:RB(e,t,n,r)}}function HB(){return{required:!1,json:{type:`object`,additionalProperties:zB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;if(!db(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be an object, got ${fb(i)}`,line:q(e.source,[...t.split(`.`),n])});return}let a=Object.create(null);for(let r of Object.keys(i)){let o=RB(e,`${t}.${n}`,r,i);o!==void 0&&(a[r]=o)}return a}}}function UB(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${J(i)}`,line:q(e.source,[...t.split(`.`),n])})}}}}function WB(){return{required:!1,json:yB(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return qz(e,`${t}.${n}`,i)}}}const GB={template:BB(),description:wb(),group:Mb(ZM),width:UB(),justify:Mb(Eee),truncate:Mb(Dee),bg:wb(),fg:wb(),when:wb(),palette:Ob(),vars:WB(),settings:MB(),missingData:Mb(Gy),partials:HB()},KB={noun:`segment key`,fields:GB},qB={noun:`segment key`,fields:{...GB,template:VB()}};function JB(e,t){if(t===void 0)return{};if(!db(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${fb(t)}`,line:q(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${J(i)}`,line:q(e.source,[`helpers`,r])});continue}n[r]=i}return n}function YB(e,t,n){if(t===void 0)return{};if(!db(t))return X(e,`actions`,`actions must be an object, got ${fb(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=XB(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function X(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,t.split(`.`))})}function XB(e,t,n,r){if(!db(n))return X(e,t,`${t} must be an action object, got ${fb(n)}`),null;if(`persistWhen`in n)return X(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let i=kS.filter(e=>e in n);return i.length===1?QB(r)[i[0]](e,t,n):(X(e,t,`action must declare exactly one of: ${kS.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function ZB(e){return e===`<default>`?{dir:null}:E.isAbsolute(e)?{dir:E.dirname(e)}:{text:e}}const QB=e=>({set:(e,t,n)=>PV(e,t,n,`set`,AV),persist:(e,t,n)=>PV(e,t,n,`persist`,jV),copy:$B(`copy`),open:$B(`open`),reset:eV,undo:nV(`undo`),redo:nV(`redo`),back:nV(`back`),rewind:nV(`rewind`),save:nV(`save`),preset:rV,themeDefault:iV,doctor:oV,slash:sV,run:uV(e),do:dV});function $B(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&X(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=sb(t,n,r,e);return i===null?null:{[e]:i}}}function eV(e,t,n){for(let r of Object.keys(n))r!==`reset`&&X(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=fV(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}const tV={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,back:`it steps the session's navigation history`,rewind:`it steps the session's settings history back to where edit mode opened`,save:`it saves the session's unsaved settings`};function nV(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&X(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(X(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${tV[e]}), got ${J(r[e])}`),null)}}function rV(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||X(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return X(e,`${t}.preset`,`preset must be "save" or "delete", got ${J(r)}`),null;if(r===`save`)return{preset:`save`};let a=sb(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function iV(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&X(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(X(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${J(n.themeDefault)}`),null)}const aV={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function oV(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(aV,r),a=i?aV[r]:[...new Set(Object.values(aV).flat())];for(let r of Object.keys(n))a.includes(r)||X(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return X(e,`${t}.doctor`,`doctor must be ${Object.keys(aV).map(e=>`"${e}"`).join(`, `)}, got ${J(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?RF:LF;if(typeof o!=`string`||!s.some(e=>e.name===o))return X(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${J(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return cF.includes(c)?{doctor:`mark`,check:o,mark:c}:(X(e,`${t}.mark`,`doctor mark must be ${cF.map(e=>`"${e}"`).join(` or `)}, got ${J(c)}`),null)}function sV(e,t,n){for(let r of Object.keys(n))r!==`slash`&&X(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=fI(n.slash);return r.kind===`refused`?(X(e,`${t}.slash`,r.reason),null):{slash:r.line}}const cV=[`run`,`env`,`refreshes`],lV=/^[A-Za-z_][A-Za-z0-9_]*$/;function uV(e){return(t,n,r)=>{for(let e of Object.keys(r))cV.includes(e)||X(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${cV.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&X(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${J(a)}`);let o=r.env??{};(!db(o)||Object.entries(o).some(([e,t])=>!lV.test(e)||typeof t!=`string`))&&X(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${J(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&X(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${J(s)}`),`dir`in e||X(t,`${n}.run`,`a run action runs in the directory of the file that declares it, and ${e.text} is no file`),t.issues.length>i||!(`dir`in e)?null:{run:a,env:o,refreshes:s,cwd:e.dir}}}lV.source;function dV(e,t,n){for(let r of Object.keys(n))r!==`do`&&X(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(X(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${J(r)}`),null):{do:r}}function fV(e,t,n,r,i,a){let o=sb(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(X(e,s,i),null):o.includes(`/`)?(X(e,s,a(o)),null):o}const pV={set:`the SessionState key to write`,persist:`the config globals field to write`};function mV(e,t,n,r){let i=pV[r],a=fV(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);return a===null?null:{[r]:a}}function hV(e){return e===`set`?`set-state`:`set-config`}const gV={to:FV(`set`)},_V={to:FV(`persist`)},vV={from:IV(`set`)},yV={from:IV(`persist`)},bV={min:VV(),max:VV(),by:VV()},xV={int:RV()},SV={cycle:LV(`set`)},CV={cycle:LV(`persist`)},wV={removeSegment:zV(`removeSegment`)},TV={insertSegment:zV(`insertSegment`),anchor:zV(`anchor`),relation:BV()},EV={insertSegmentFrom:IV(`persist`),anchor:zV(`anchor`),relation:BV()},DV={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},OV={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function kV(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>hb(e,t,n,r),c=Nb(t);return{detect:a,allowed:[...o,...i],label:i.join(`/`),json:{type:`object`,properties:{...Object.fromEntries(o.map(e=>[e,{type:`string`}])),...c.properties},required:[...o,...c.required??[]],additionalProperties:!1},parse:n.length?Cb(s,...n):s}}const AV=[kV(`set`,gV),kV(`set`,vV),kV(`set`,bV,[DV,OV]),kV(`set`,xV),kV(`set`,SV)],jV=[kV(`persist`,_V),kV(`persist`,yV),kV(`persist`,bV,[DV,OV]),kV(`persist`,CV),kV(`persist`,wV),kV(`persist`,TV,[],[`insertSegment`]),kV(`persist`,EV,[],[`insertSegmentFrom`])];function MV(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"endcaps"/"styles", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function NV(e){let t=MV(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function PV(e,t,n,r,i){let a=mV(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return X(e,t,`${NV(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||X(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function FV(e){let t=hV(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>fV(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function IV(e){let t=hV(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){X(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){X(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){X(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){X(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){X(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}X(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${J(o)}`)}}}function LV(e){let t=hV(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){X(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${fb(o)}`);return}let c=o;if(c.length<2){X(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){X(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){X(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){X(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function RV(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){X(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${J(r[n])}`);return}return!0}}}function zV(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=sb(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){X(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){X(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function BV(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){X(e,`${t}.${n}`,`relation must be "before" or "after", got ${J(i)}`);return}return i}}}function VV(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){X(e,`${t}.${n}`,`${n} must be an integer, got ${J(i)}`);return}return i}}}function HV(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const UV=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),WV=`plugin.json5`,GV=/^[a-z][a-z0-9_]*$/;function KV(e,t){let n=E.basename(E.dirname(e));return GV.test(n)?{path:e,scope:t,name:n}:{path:e,scope:t,name:void 0}}function qV(e){return`${e}.data`}function JV(e){return`${e}.json`}function YV(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:XV(e)}}}function XV(e){return e instanceof ib?e.issues.map(e=>e.path===``||e.message.includes(e.path)?e.message:`${e.path}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}function ZV(e,t,n,r){return e.map(e=>KV(NN(E.dirname(t),e,r),n))}function QV(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=n.path,o=n.name===void 0?void 0:FS(n),s=(t,r)=>{let i=new Map(e.rendering);return o!==void 0&&r!==e.config&&i.delete(o),{...e,config:r,rendering:i,dropped:[...e.dropped,{...n,reason:t}]}};if(E.basename(a)!==`plugin.json5`){let t=`a plugin is a folder holding its ${WV}, and the folder's name is the plugin's: move this file to <dir>/<name>/${WV} and list that`;return s(t,o===void 0?e.config:eH($V(e.config,o),o,{...n,reason:t}))}if(n.name===void 0||o===void 0)return s(`its folder "${E.basename(E.dirname(a))}" is not a plugin name (one matching ${GV}: it prefixes every name the plugin declares)`,e.config);let c=i.get(o);if(c!==void 0)return s(`plugin "${n.name}" is already listed, from ${c}`,e.config);i.set(o,a);let u=$V(e.config,o),d=YV(()=>{let i=l.readFileSync(a,`utf-8`),s=Ez(oH(a,n,{source:i,json:ua.default.parse(i)},t),u);return xH(a,o,s),r(s,o,u!==e.config),s});if(d.ok)return{...e,config:d.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[o,n]])};let f={...n,reason:d.reason};return s(d.reason,eH(u,o,f))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function $V(e,t){let n=IS(t),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n(e)));return[e.variables,e.segments,e.helpers,e.actions].some(e=>Object.keys(e).some(n))?{...e,variables:r(e.variables),segments:r(e.segments),helpers:r(e.helpers),actions:r(e.actions)}:e}function eH(e,t,n){return{...e,variables:{...e.variables,[t]:{kind:`dropped`,reason:HV(n),definition:n.path}}}}function tH(e){let t=Object.entries(e.variables).flatMap(([e,t])=>t.kind===`dropped`?[{ns:e,definition:t.definition,notice:t.reason}]:[]);return e=>t.find(({ns:t})=>IS(t)(e))}function nH(e,t){let n=tH(e.config),r=[...e.rendering.keys()].map(IS),i=[...t,...e.dropped].filter(e=>e.name===void 0);return e=>{let t=RS(e);if(t===void 0)return[];let a=n(e);return a===void 0?r.some(t=>t(e))?[]:i.filter(e=>e.scope===t).map(e=>({definition:e.path,notice:HV(e)})):[{definition:a.definition,notice:a.notice}]}}function rH(e,t,n){let r=mS(e.presets).flatMap(t=>[...Fy(_S(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),i=[...new Set([...r.map(e=>e.name),...n,...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),a=Object.fromEntries(i.map(({name:e,cause:t})=>[e,iH(e,t.map(e=>e.notice),r.filter(t=>t.name===e))])),o=tH(e),s=Object.values(e.variables).some(e=>e.kind===`dropped`),c=s?Object.values(e.segments).flatMap(e=>[...uH.flatMap(t=>e[t]===void 0?[]:[e[t]]),...Object.values(e.partials??{})]):[],l=s?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],u=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:o(e);return n===void 0?[]:[[e,n]]}),d=u([...c.flatMap(t=>aC(t,e.helpers).map(e=>e.name)),...l],e.actions),f=u(c.flatMap(t=>[...fC(t,e.helpers)]),e.helpers),p=Object.entries(e.actions).flatMap(([t,n])=>{if(!(`run`in n))return[];let r=new Map(u(n.refreshes,e.variables));return r.size===0?[]:[{name:t,action:{...n,refreshes:n.refreshes.filter(e=>!r.has(e))},causes:[...r.values()]}]}),m=new Set([...i.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...d,...f].map(([,e])=>e.definition),...p.flatMap(({causes:e})=>e.map(e=>e.definition))]);return{config:{...e,segments:{...e.segments,...a},actions:{...e.actions,...Object.fromEntries(p.map(({name:e,action:t})=>[e,t])),...Object.fromEntries(d.map(([e,{ns:t}])=>[e,{copy:`{{ .${t} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(f.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:m}}function iH(e,t,n){let r=`⚠ ${e}: ${t.join(`; `)}`,i=new Map;for(let e of n)for(let[t,n]of Object.entries(e.settings??{})){let e=i.get(t);i.set(t,e===void 0?[n]:[...e,n])}let a=Object.fromEntries([...i].map(([e,t])=>[e,aH(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function aH(e,t){let[n]=t,r=t.filter(e=>typeof e==`number`);return typeof n==`boolean`?{label:e,domain:`bool`,default:n}:typeof n==`number`?{label:e,domain:{min:Math.min(...r),max:Math.max(...r),step:1},default:n}:{label:e,domain:[...new Set(t.map(String))],default:n}}function oH(e,t,{source:n,json:r},{checkout:i,home:a}){let o=FS(t),s=[],c=()=>{throw new ib(e,s)};if(!db(r))return s.push({path:``,message:`a plugin definition must be an object, got ${fb(r)}`}),c();for(let t of Object.keys(r))UV.has(t)||s.push({path:t,message:t===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${E.basename(E.dirname(e))}") — remove "plugin"`:`a plugin definition may not declare "${t}". Expected only: ${[...UV].join(`, `)}`});let u=r.data===void 0?void 0:wH(r.data,e,i,a,s),d=r.sources===void 0?{}:bH(r.sources,e,s);if(s.length>0)return c();let f={source:n,issues:s,allowedPalettes:new Set(qv()),groups:[],unplaced:[],inherited:[]},p=u===void 0?{}:qz(f,`data`,{[qV(o)]:{kind:`file`,path:u,parse:{json:!0},cache:{watch_file:u},default:{}}}),m=qz(f,`variables`,r.variables);for(let[e,t]of[[`variables`,Object.keys(m)],[`sources`,Object.keys(d)]])t.includes(`data`)&&s.push({path:`${e}.data`,message:`"data" names the plugin's data file (.${qV(o)}), declared by the definition's own "data" key: give this ${e===`sources`?`source`:`variable`} another name`});for(let e of Object.keys(d))Object.hasOwn(m,e)&&s.push({path:`sources.${e}`,message:`source "${e}" and variable "${e}" are one name (.${o}.${e}): give one of them another name`});let h={variables:{...p,...pH(o,d),...pH(o,Object.fromEntries(Object.entries(m).map(([e,t])=>[e,hH(o,t)])))},segments:pH(o,gH(o,LB(f,r.segments,new Set))),helpers:pH(o,JB(f,r.helpers)),actions:pH(o,_H(o,YB(f,r.actions,{dir:l.realpathSync(E.dirname(e))})))};s.push(...dH(h,t));let g=sH(o,h);for(let[e,t]of fH(g))try{eN.parse(t)}catch(t){s.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return s.length>0&&c(),g}function sH(e,t){let n=t=>mC(t,LS,e),r=t=>IS(`self`)(t)?`${e}${t.slice(4)}`:t,i=(e,t)=>Object.fromEntries(Object.entries(e??{}).map(([e,n])=>[e,t(n)]));return{...t,variables:i(t.variables,e=>cH(Uy(e,n),r)),segments:i(t.segments,e=>({...e,...Object.fromEntries(uH.flatMap(t=>e[t]===void 0?[]:[[t,n(e[t])]])),...e.partials!==void 0&&{partials:i(e.partials,n)},...e.vars!==void 0&&{vars:i(e.vars,e=>cH(Uy(e,n),r))}})),helpers:i(t.helpers,n),actions:i(t.actions,e=>lH(MS(e,n),r))}}function cH(e,t){return Hy(e)&&`depends_on`in e.cache?{...e,cache:{depends_on:e.cache.depends_on.map(t)}}:e}function lH(e,t){let n=`segments.`,r={...e};`do`in e&&(r.do=e.do.map(e=>t(e,`do`)));for(let n of[`removeSegment`,`insertSegment`,`anchor`])n in e&&(r[n]=t(e[n],n));return`persist`in e&&e.persist.startsWith(n)&&(r.persist=n+t(e.persist.slice(9),`persist`)),r}const uH=[`template`,`bg`,`fg`,`when`];function dH(e,t){let n=e.helpers??{},r=PS.filter(e=>e!==t.scope).map(e=>({scope:e,ns:FS({scope:e,name:t.name})})),i=new Map,a=(e,n,a)=>{let o=r.find(({ns:e})=>IS(e)(n));if(o===void 0)return;let s=a?`.`:``;i.set(`${e}\0${n}`,{path:e,message:`${e} names ${s}${n}, this plugin under "${o.scope}", but it loads as ${FS(t)}: a plugin names itself without its scope — write ${s}${LS}${n.slice(o.ns.length)}`})},o=[...[...fH(e)].filter(([e])=>!e.startsWith(`helpers.`)),...Object.entries(n).map(([e,t])=>[`helpers.${e}`,t])];for(let[e,t]of o){for(let[r,i]of tC(t,n))i===null&&a(e,r,!0);for(let{name:r,via:i}of aC(t,n))i===null&&a(e,r,!1);for(let n of fC(t,{}))a(e,n,!1)}for(let[t,n]of Object.entries(e.actions??{}))lH(n,(e,n)=>(a(`actions.${t}.${n}`,e,!1),e));let s=[...Object.entries(e.variables??{}).map(([e,t])=>[`variables.${e}`,t]),...Object.entries(e.segments??{}).flatMap(([e,t])=>Object.entries(t.vars??{}).map(([t,n])=>[`segments.${e}.vars.${t}`,n]))];for(let[e,t]of s)if(Hy(t)&&`depends_on`in t.cache)for(let n of t.cache.depends_on)a(`${e}.cache.depends_on`,n,!1);return[...i.values()]}function*fH(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of Wy(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of uH){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[e,r]of Object.entries(n.partials??{}))yield[`segments.${t}.partials.${e}`,r];for(let[e,r]of Object.entries(n.vars??{}))for(let[n,i]of Wy(r))yield[`segments.${t}.vars.${e}.${n}`,i]}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))for(let[e,r]of jS(n))yield[`actions.${t}.${e}`,r]}function pH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,n]))}function mH(e,t){return`${e}.${t}`}function hH(e,t){return t.kind===`state`?{...t,key:mH(e,t.key)}:t}function gH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.vars===void 0?n:{...n,vars:Object.fromEntries(Object.entries(n.vars).map(([t,n])=>[t,hH(e,n)]))}]))}function _H(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:mH(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>mH(e,t))}:n]))}const vH=GV,yH={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function bH(e,t,n){if(!db(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${fb(e)}`}),{};let r=E.join(l.realpathSync(E.dirname(t)),`session`),i=JSON.stringify(yH),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!vH.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${vH}: it is the last segment of .<scope>.<plugin>.${t})`});continue}let s=CH(o,yH,e);for(let{field:e,is:t}of s)n.push({path:e,message:`${e} ${t}: what is built is a source ${i} — a session's JSON file in the plugin's managed storage, re-read when it changes`});s.length===0&&(a[t]={kind:`source`,storage:r})}return a}function xH(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=SH(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=IS(t),a=[...r].filter(([,e])=>e.length>1&&e.some(i)).map(([e,n])=>({path:`sources.${n.find(i).slice(`${t}.`.length)}`,message:`sources ${n.map(e=>`.${e}`).join(` and `)} read the same file, ${e}: a session's file is one document, read by one source`}));if(a.length>0)throw new ib(e,a)}function SH(e){return E.join(e.storage,JV(`<session id>`))}function CH(e,t,n){return!db(t)||!db(e)?JSON.stringify(e)===JSON.stringify(t)?[]:[{field:n,is:`is ${JSON.stringify(e)}`}]:[...new Set([...Object.keys(t),...Object.keys(e)])].flatMap(r=>{let i=`${n}.${r}`;return Object.hasOwn(t,r)?Object.hasOwn(e,r)?CH(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function wH(e,t,n,r,i){if(typeof e==`string`&&e!==``)return NN(E.dirname(t),e,r);if(db(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(E.isAbsolute(t)||t.startsWith(`~`)||E.normalize(t).split(E.sep)[0]===`..`){i.push({path:`data.checkout`,message:`data.checkout "${t}" must be a path inside the checkout, relative to its root (like ".lit/statusline.json"): no absolute path, "~" or ".."`});return}if(n===null){i.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return E.resolve(n.root,t)}if(db(e)&&`project`in e){i.push({path:`data.project`,message:`data: { project } is now data: { checkout }: the same path, relative to the root of the git checkout the session works in (a linked worktree is its own checkout)`});return}i.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { checkout: "<path>" } relative to the root of the session's checkout`})}function TH(e,t){let n=[...[...e.dataDirs].reverse().map(e=>E.join(e,`cc-candybar`,`plugins`)),EH(e)];return[...n.filter((e,t)=>n.lastIndexOf(e)===t).map(e=>({dir:e,scope:`plugins`})),...t===null?[]:[{dir:E.join(t,DH),scope:`repo`}]]}function EH(e){return E.join(e.dataHome,`cc-candybar`,`plugins`)}const DH=E.join(`.cc-candybar`,`plugins`);function OH(e,t){let n=TH(e,t),r=new Map,i=[],a=[];for(let{dir:e,scope:t}of n){let n=kH(e);if(`error`in n){i.push(n);continue}for(let i of n.folders){let n=KV(E.join(e,i,WV),t),a=`${t}\0${i}`;r.delete(a),r.set(a,n)}for(let r of n.files)a.push({path:E.join(e,r),scope:t,name:void 0,reason:`a plugin is a folder holding its ${WV}: move this file to ${E.join(e,`<name>`,WV)}`})}return{roots:n.map(e=>e.dir),definitions:[...r.values()],unchecked:i,strays:a}}function kH(e){try{let t=l.readdirSync(e,{withFileTypes:!0}).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),n=t=>t.isDirectory()||AH(e,t);return{folders:t.filter(n).map(e=>e.name),files:t.filter(e=>!n(e)).map(e=>e.name)}}catch(t){return t.code===`ENOENT`?{folders:[],files:[]}:{path:e,error:t.message}}}function AH(e,t){if(!t.isSymbolicLink())return!1;try{return l.statSync(E.join(e,t.name)).isDirectory()}catch{return!0}}const jH=[`approved`,`declined`];function MH(e){return e.link.kind===`linked`?e.link.main:e.dir}const NH=(e,t)=>Object.hasOwn(e,t)?e[t]:null;function PH(e,t){let n=MH(t);if(e.kind===`failed`)return{standing:`unread`,under:n};let r=NH(e.value,n),i=NH(e.value,t.dir);return r===null?i===null?{standing:`awaiting`,under:n}:{standing:i,under:t.dir}:{standing:i===null||i===r?r:`awaiting`,under:n}}function FH(e,t,n){let r=[...new Map([...t,...n?.ships?[n]:[]].map(e=>[e.dir,e])).values()],i=r.map(t=>({dir:t.dir,...PH(e,t)})),a=e=>i.filter(t=>t.standing===e),o=e=>[...new Set(a(e).map(e=>e.under))];return{plugins:n!==null&&PH(e,n).standing===`approved`?n.path:null,approved:a(`approved`).map(e=>e.dir),awaiting:o(`awaiting`),declined:o(`declined`),unproven:r.flatMap(e=>e.link.kind===`unproven`?[{dir:e.dir,reason:e.link.reason}]:[]),unread:e.kind===`failed`?e.reason:null}}function IH(e,t,n,r){if(e[t]===n&&r.length===0)return e;let i=Object.entries(e).filter(([e])=>!r.includes(e));return{...Object.fromEntries(i),[t]:n}}function LH(e){if(typeof e!=`object`||!e||Array.isArray(e))return{kind:`failed`,reason:`is not an object`};for(let[t,n]of Object.entries(e))if(!jH.includes(n))return{kind:`failed`,reason:`answers ${JSON.stringify(t)} ${JSON.stringify(n)}, not ${jH.join(` or `)}`};return{kind:`ok`,value:e}}function RH(e){return e.unread===null?null:`Repository config answers could not be read: ${e.unread} — no repository's config runs until they can be`}function zH(e){let t=RH(e);return[...t===null?[]:[t],...e.awaiting.map(e=>`awaiting approval: ${e} — its cc-candybar config runs once it is approved in the bar`),...e.declined.map(e=>`declined: ${e} — its cc-candybar config does not run`),...e.unproven.map(e=>`not proven a worktree: ${e.dir} — it answers for itself, because ${e.reason}`)]}const BH=[`json5`,`json`];function VH(e,t,n,r){if(r!==void 0)return[r];let i=n??process.cwd();return[...new Set([...t?BH.map(e=>E.join(t,`${HH}.${e}`)):[],...BH.map(e=>E.join(i,`${HH}.${e}`)),...BH.map(t=>`${UH(e)}.${t}`)])]}const HH=`.cc-candybar`;function UH(e){return E.join(e.configHome,`cc-candybar`,`config`)}function WH(e){return{path:e,scope:`plugins`}}function GH(e,t,n,r,i){let a=[],o=new Map;for(let t of VH(e,n,r,i)){let n=Tz(t);if(n===`absent`)continue;if(n!==`present`){a.push(n);continue}let r=l.realpathSync.native(E.dirname(t)),s=E.join(r,E.basename(t).replace(/\.(json5|json)$/,``));o.has(s)||o.set(s,{file:t,repo:i!==void 0||KH(e,t)?null:{dir:r,link:uc(r)}})}let s=[...o.values()],c=FH(t,s.flatMap(e=>e.repo===null?[]:[e.repo]),qH(n)),u=s.filter(e=>e.repo===null||c.approved.includes(e.repo.dir)).reverse().map(e=>({path:e.file,scope:e.repo===null?`plugins`:`repo`}));if(i===void 0)return{kind:`chain`,layers:u,home:JH(e,u),unchecked:a,repos:c};let[d]=a,f=i;return u.length>0?{kind:`chain`,layers:u,home:f,unchecked:a,repos:c}:d===void 0?{kind:`missing`,path:i,home:f,repos:c}:{kind:`unreadable`,...d,home:f,repos:c}}function KH(e,t){return BH.some(n=>t===`${UH(e)}.${n}`)}function qH(e){if(e===void 0||Tz(e)!==`present`)return null;let t=kH(E.join(e,DH)),n=l.realpathSync.native(e);return{dir:n,link:uc(n),path:e,ships:!(`error`in t)&&t.folders.length>0}}function JH(e,t){return t.find(t=>KH(e,t.path))?.path??`${UH(e)}.${BH[0]}`}function YH(e,t,n,r,i){let a=GH(e,t,n,r,i),o=a.kind===`chain`?a.layers:[];return{path:a.home,above:o.filter(e=>e.path!==a.home),repo:a.repos.plugins,cwd:r??null,locs:e}}function XH(e){return ZH(e).join(`
|
|
180
|
-
`)||null}function
|
|
178
|
+
`}const DP=(e,t)=>e.fg===t.fg&&e.bg===t.bg&&e.link===t.link&&e.attrs?.join()===t.attrs?.join();function OP({runs:e}){let t=[];for(let n of e){let e=t.at(-1);e!==void 0&&DP(e,n)?t[t.length-1]={...e,text:e.text+n.text}:t.push(n)}return t}function kP(e){return e.map(e=>e.text).join(``)}const AP={};function jP(e,t){let n=xl(t.colorSystem),{time:r}=t,i=1/0,a=[...Jf(e,{maxWidth:t.width??80,isTerminal:!1,asciiOnly:!1,theme:BN,colorSystem:n.colorSystem,...r===void 0?{}:{frame:{time:r,host:AP}},onStyleError:e=>{throw e},onHold:({nextChange:e})=>{i=Math.min(i,e)}})];return{lines:SP(a,n.colorSystem),nextChange:Math.min(W.nextChange(a),i)}}const MP=new Map;function NP(e){let t=MP.get(e);if(t!==void 0)return t;let n=t=>({seam:t.seam.map(t=>`cap`in t?t:{...t,glyph:e})}),{seam:r,caps:i}=nh.plain,a=new Em({glyph:n(r.glyph),ascii:r.ascii},i);return MP.set(e,a),a}function PP(e,t){return e===`plain`&&t!==void 0?NP(t):nh[e]}const FP=new Map;function IP(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=FP.get(t);if(n!==void 0)return n;let r=PP(e.endcaps,e.separator),i=e=>new K(`x`,{end:``,overflow:`ignore`,style:new U({bgcolor:e})}),a=e=>{let{lines:t}=jP(new $p(e,r),{colorSystem:null});return new K(kP(t.flat())).cellLength},o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return FP.set(t,s),s}function LP(e){return IP(e).chrome}function RP(e){return IP(e).seam}const zP=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function BP(e){return[...new Set(e.match(zP)??[])].join(``)}function VP(e){let t=PP(e.endcaps,e.separator),n=e=>new K(`x`,{end:``,style:new U({bgcolor:e})}),{lines:r}=jP(new $p([n(`#101010`),n(`#202020`)],t),{colorSystem:null});return BP(kP(r.flat()))}function HP(e){return e.wrap?e.width:1/0}function UP(e,t){return jP(new K(e,{overflow:`fold`,end:``}),{colorSystem:null,width:t}).lines.map(kP)}function WP(e,t,n=HN){if(e.length===0)return{lines:[[]],nextChange:1/0};let r=PP(t.endcaps,t.separator),i=Number.isFinite(HP(t)),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new __([...e],{joiner:r}):new $p([...e],r),s=n.kind===`still`?jP(o,a):jP(n.wrap(o),{...a,time:n.time});if(s.lines.length===0)throw Error(`drawStripCells: rich-js strip drew no line`);return s}function GP(e,t){return wP(WP(e,t).lines,t.colorCompatibility)}const KP=[`moves`,`can-move`,`still`];function qP(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const Xee=[`statusline`,`frames`],JP=e=>e?.kind===`frames`?`frames`:`statusline`,Zee=[`carried`,`missing`,`unanswered`];function Qee(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:qP(e)===`no`?`unanswered`:`missing`}function $ee(e){return{path:e.transcript_path,answered:qP(e)===`yes`}}const YP=[...KP,`failed`,`drawing`];var ete=class{seen=new Map;see(e,t,n,r){let i=JP(t.client),a=JSON.stringify([e,i]),o=this.seen.get(a);o!==void 0&&o.order>r||(this.seen.delete(a),this.seen.set(a,{sessionId:e,said:{...t,role:i},at:n,order:r}),this.seen.size>64&&this.seen.delete(this.seen.keys().next().value))}list(e){return[...this.seen.values()].map(({sessionId:t,said:n,at:r})=>({...n,sessionId:t,ago:e-r}))}ofSession(e,t){return this.list(t).filter(t=>t.sessionId===e)}};const XP={kitty:{label:`kitty`,xtversion:`kitty`,program:null,programVersion:!0,term:`xterm-kitty`,links:{since:`0.19.0`},glyphs:{kind:`bundled`,since:`0.36.0`}},wezterm:{label:`WezTerm`,xtversion:`WezTerm`,program:`WezTerm`,programVersion:!0,term:`wezterm`,links:{since:null},glyphs:{kind:`bundled`,since:`20230712`}},ghostty:{label:`Ghostty`,xtversion:`ghostty`,program:`ghostty`,programVersion:!0,term:`xterm-ghostty`,links:{since:null},glyphs:{kind:`bundled`,since:null}},iterm2:{label:`iTerm2`,xtversion:`iTerm2`,program:`iTerm.app`,programVersion:!0,term:null,links:{since:`3.1`},glyphs:{kind:`configured`}},alacritty:{label:`Alacritty`,xtversion:`alacritty`,program:null,programVersion:!0,term:`alacritty`,links:{since:`0.11.0`},glyphs:{kind:`configured`}},"apple-terminal":{label:`Terminal`,xtversion:null,program:`Apple_Terminal`,programVersion:!0,term:null,links:null,glyphs:{kind:`unread`}},vscode:{label:`VS Code`,xtversion:null,program:`vscode`,programVersion:!1,term:null,links:{since:`1.72`},glyphs:{kind:`unread`}}},ZP=e=>XP[e];function tte(e){return ZP(e).glyphs.kind===`bundled`}function nte(e){return ZP(e).glyphs.kind===`configured`}const QP=e=>ZP(e).label,rte=[{since:`3.5.0`,from:57504,to:57507},{since:`3.5.0`,from:57520,to:57554},{since:`3.5.0`,from:57556,to:57556},{since:`3.5.6`,from:57558,to:57559}];function ite(e,t){let n=t.codePointAt(0);return rte.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&tF(e,t)===!0)}const $P=Object.keys(XP);function eF(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function tF(e,t){let n=eF(e),r=eF(t);if(n===null)return null;for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t>i}return!0}function ate(e){for(let t of $P){let n=ZP(t).xtversion;if(n!==null&&e.toLowerCase().startsWith(n.toLowerCase())){let r=e.slice(n.length).replace(/^[\s(]+/,``);return{name:t,version:/^[^\s)]+/.exec(r)?.[0]??null}}}return null}function nF(e){let t=$P.find(t=>ZP(t).term===e);return t===void 0?null:{name:t,version:null}}function ote(e){let t=ate(e.termtype)??nF(e.termname);if(t!==null)return{kind:`known`,terminal:t};let n=/^[^\s(]*/.exec(e.termtype)[0];return n===``?{kind:`unnamed`,term:e.termname}:{kind:`unknown`,called:n}}function ste(e){let t=e.TERM_PROGRAM,n=$P.find(e=>ZP(e).program===t),r=n===void 0?nF(e.TERM):{name:n,version:ZP(n).programVersion?e.TERM_PROGRAM_VERSION??null:null};return r===null?t===void 0||t===`tmux`?{kind:`unnamed`,term:e.TERM??``}:{kind:`unknown`,called:t}:{kind:`known`,terminal:r}}function rF(e){switch(e.kind){case`known`:return QP(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function iF(e){switch(e.kind){case`known`:return QP(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function cte({name:e,version:t}){let n=ZP(e).links;if(n===null)return{kind:`none`};if(n.since===null)return{kind:`draws`};if(t===null)return{kind:`unsaid`,since:n.since};let r=tF(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const lte=$P.filter(e=>ZP(e).links!==null).map(QP).join(`, `);function aF(e){if(e.kind===`failed`)return{kind:`unread`,reason:e.reason};let t=e.value.flatMap(({scope:e,path:t,settings:n})=>`statusLine`in n?[{from:{scope:e,path:t},line:n.statusLine}]:[]),n=t[0];if(n===void 0)return{kind:`absent`,read:e.value.map(e=>e.path)};if(!Mo(n.line))return{kind:`not-an-object`,value:n.line,from:n.from};for(let{from:e,line:r}of t){if(e.scope!==n.from.scope||!Mo(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function oF(e,t){if(e.kind===`failed`)return e;let n=e.value.find(e=>Object.hasOwn(e.env,t));return{kind:`ok`,value:n===void 0?{kind:`unset`}:{kind:`set`,value:n.env[t],from:{scope:n.scope,path:n.path}}}}const ute=[`managed`,`project`],dte=e=>!ute.includes(e.scope),fte={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:jo(t.projectDir)}),user:e=>({scope:`user`,path:e})},sF=[`drawn`,`boxes`],cF=1024*1024,lF=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function pte(e){switch(e.kind){case`claude-settings`:return`${e.kind} ${e.path.join(`.`)}=${JSON.stringify(e.value)} file=${JSON.stringify(e.file.path)} scope=${e.file.scope}`;case`post-mortems-read`:return`${e.kind} through=${e.through}`}}function uF(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const dF=fc.truecolor;function fF(e,t){switch(e.kind){case`unreported`:return{ok:!1,reason:"the client reported no tmux facts — re-run `cc-candybar install` to stage a current client"};case`outside`:return{ok:!0};case`inside`:return e.client.kind===`failed`?{ok:!1,reason:`tmux could not be asked: ${e.client.reason}`}:e.client.value===null?{ok:!0}:t(e.client.value,e.hint)}}const mte={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>fF(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=oF(t.sources,dF);if(r.kind===`failed`)return{ok:!1,reason:r.reason};let i=r.value;if(i.kind===`set`&&typeof i.value==`string`&&i.value!==``)return{ok:!1,reason:`${dF} is set in ${i.from.path} — restart Claude Code to apply`};let a=`Claude Code renders the bar in 256 colours inside tmux`,o=e=>({ok:!1,reason:a,fix:{kind:`claude-settings`,file:e,path:[`env`,dF],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=fte[i.from.scope](i.from.path,t.at);return s===null?{ok:!1,reason:`${a} — the value that counts is in managed settings, ${i.from.path}: set ${dF} to "1" there`}:o(s)})},hte={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>fF(e,e=>e.utf8?{ok:!0}:{ok:!1,reason:"tmux draws this terminal without UTF-8, so every glyph on the bar arrives as `_` — attach with `tmux -u`, or set a UTF-8 LC_ALL/LC_CTYPE/LANG in the shell that runs tmux"})},gte={name:`termWidth`,label:`terminal width`,takesMark:!1,probe:({width:e})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.columns===null?{ok:!1,reason:`${lF(e.value.of)} measured no width (no COLUMNS, and no terminal to ask — or the daemon refused the width sent, which the bar's diagnostics name), so the bar is laid out as if the terminal were 120 columns wide`}:{ok:!0,note:`${e.value.columns} columns, as ${lF(e.value.of)} measured`}},_te={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},vte={argument:`command argument`,environment:`$${FN}`,pick:`load-config pick`,unknown:`source unknown`};function yte({target:e,layers:t}){return e.source===`search`?t.length===0?zN(t):`${zN(t)} (searched)`:`${e.path} (${vte[e.source]})`}function bte(e){switch(e.kind){case`failed`:{let t=[...e.error.split(`
|
|
179
|
+
`).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return t.length===0?[`the config failed to load`]:t}case`loaded`:return[...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${_te[e]}`)]}}const xte={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{let t=yte(e),n=uF(bte(e));return n.ok?{ok:!0,note:t}:{...n,reason:`${t}: ${n.reason}`}}},pF="re-run `cc-candybar install`";function Ste(e){if(e.kind===`failed`)return[`Launch Services could not be asked which app opens cc-candybar:// — ${e.reason}`];if(e.value===null)return[`no app is registered for cc-candybar:// — ${pF}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${pF}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${pF}`)}const Cte={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${pF}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${pF}`};case`lost`:return uF([...Ste(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}};function mF({bundle:e,checkout:t},n){return{bundle:n.bundle.kind===`failed`?{kind:`unresolved`,reason:n.bundle.reason}:n.bundle.value===e?{kind:`same`}:{kind:`other`,path:n.bundle.value},source:n.client!==`native`||t===null?{kind:`uncompared`}:t.rustSource.kind===`failed`?{kind:`unreadable`,root:t.root,reason:t.rustSource.reason}:n.source===null?{kind:`unstamped`}:n.source===t.rustSource.value?{kind:`same`}:{kind:`other`,root:t.root}}}function hF(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${Vb.join(`|`)}>\``:e.checkout===null?pF:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function wte(e,t,n){let{checkout:r}=e;if(n.kind===`unreported`)return[`the bar is drawn by a statusline client too old to say what it is — ${hF(e,`native`)}`];let{bundle:i,source:a}=mF(e,n);switch(i.kind){case`unresolved`:return[`the statusline client's bundle cannot be resolved: ${i.reason}`];case`other`:return[`the statusline client runs ${i.path}, not the daemon's ${e.bundle} — ${hF(e,n.client)}`];case`same`:break}if(n.client===`node`&&(t||r!==null))return[`the bar is drawn by the Node fallback, which starts node on every render — ${hF(e,`native`)}`];switch(a.kind){case`uncompared`:case`same`:return[];case`unreadable`:return[`${a.root}/rust-client could not be read: ${a.reason}`];case`unstamped`:return["the native client carries no source stamp, so which source it was built from is unknown — run `just install-rust`"];case`other`:return[`the native client was built from other source than ${a.root}/rust-client holds — run \`just install-rust\``]}}const gF=e=>{let t=`restarted since the bar was drawn, or has served 64 newer sessions`;return e.kind===`clicked`?`this daemon holds no render of this bar (it ${t})`:`this daemon holds no render of session ${e.sessionId}'s bar (its statusLine does not run cc-candybar — a \`claude -p\` session draws none — or the daemon ${t}; unset CLAUDE_CODE_SESSION_ID to judge every bar drawn recently)`},Tte={name:`install`,label:`install`,takesMark:!1,probe:({install:e,sighted:t})=>{if(e.kind===`failed`)return{ok:!1,reason:`the daemon could not be asked which clients draw the bar: ${e.reason}`};let{daemon:n,nativeShipped:r,clients:i}=e.value;return i.length===0?{ok:!1,reason:t.kind===`recent`?`no statusline client has drawn a bar for this daemon in the last ${300/60} minutes — run the doctor again once the bar has redrawn; if it never does, the statusLine command does not run cc-candybar`:`${gF(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:uF([...new Set(i.flatMap(e=>wte(n,r,e)))])}};function _F({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||_r(e.identity,t.value.through)):[]}function vF(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const Ete={name:`daemon`,label:`daemon`,takesMark:!1,probe:({daemon:{serving:e,processes:t,read:n}})=>{let r=t.kind===`failed`?[`the process table could not be read: ${t.reason}`]:[],i=t.kind===`ok`?vF(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return uF([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=_F(e.value,n),u=uF([...l.map(e=>`the daemon ran out of memory and restarted (${e.identity}) — post-mortem: ${Object.values(e.artifacts).join(`, `)}`),...c.kind===`failed`?[`the daemon's post-mortems could not be listed: ${c.reason}`]:[],...n.kind===`failed`&&!(c.kind===`ok`&&c.value.length===0)?[`which post-mortems were read could not be read: ${n.reason}`]:[],...r,...i.map(e=>`daemon ${e.pid} (started ${e.started}, rss ${mr(e.rss)} MB${e.ppid===1?``:`, child of ${e.ppid}`}) runs beside the one serving the bar (${a}) — \`kill ${e.pid}\``),...o.kind===`measured`&&o.charge.kind===`stand-in`?[`the daemon could not read what macOS charges it (${o.charge.unread}), so its memory limit judges ${o.charge.gap===0?`RSS, which counts pages macOS has reclaimed`:`RSS less the ${mr(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&br(o.charge.bytes,s)?[`the daemon holds ${wr(o.charge)} of its ${mr(s)} MB limit — at the limit it records a post-mortem and restarts`]:[]]);if(u.ok&&o.kind===`unmeasured`)return{ok:!0,note:`the daemon has not measured its memory yet`};let d=l[0];return u.ok||d===void 0?u:{...u,fix:{kind:`post-mortems-read`,through:d.identity}}}},yF=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function Dte(e,t){let n=rF(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?cte(e.terminal):{kind:`unknown`}}function Ote({identified:e,tmuxClient:t},n){let r=iF(e),i=Dte(e,n),a=rF(e)===null?yF:`${yF}, and the doctor remembers it for this terminal`,o=(()=>{switch(i.kind){case`draws`:return[];case`none`:return[`${r} draws no links (OSC 8), so nothing on the bar can be clicked — run Claude Code in a terminal that draws them: ${lte}`];case`older`:return[`${r} ${i.version} draws no links (OSC 8 came in ${i.since}) — update ${r}`];case`unsaid`:return[`${r} draws links (OSC 8) since ${i.since}, and did not say which release this is — ${a}`];case`unknown`:return[`the doctor does not know whether ${r} draws links (OSC 8) — ${a}`]}})(),s=n.kind===`failed`&&i.kind!==`draws`?[`the terminals a doctor click came back from could not be read: ${n.reason}`]:[],c=i.kind===`none`||t===null||t.features.includes(`hyperlinks`)?[]:[`tmux does not pass links through to ${r} — add \`set -as terminal-features ",${t.termname}:hyperlinks"\` to tmux.conf, then detach and reattach (tmux 3.4 or later)`];return[...o,...s,...c]}const kte={name:`links`,label:`links`,takesMark:!1,probe:({sighted:e,terminal:t,clicked:n})=>{if(e.kind===`clicked`&&e.via===`link`)return{ok:!0};switch(t.kind){case`unreported`:return{ok:!1,reason:"the client reported no terminal — re-run `cc-candybar install` to stage a current client"};case`unasked`:return{ok:!1,reason:`tmux could not be asked which terminal is attached: ${t.reason}`};case`seen`:return uF(Ote(t,n))}}},bF=e=>e.filter(e=>e.role===`statusline`),xF={name:`effectRefresh`,label:`effect refresh`,takesMark:!1,probe:({frames:e,claudeSettings:{origin:t,elsewhere:n},sighted:r})=>{let i=[t,...n].flatMap(({sources:e,bars:t})=>wF(e,SF(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:CF(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:gF(r));let[o,...s]=i.flatMap(e=>e.ok?[]:[e]);if(o===void 0)return a;let c=[...new Set(s.map(e=>e.reason))].filter(e=>e!==o.reason);return c.length===0?o:{...o,more:c}}},SF=e=>{let t=bF(e).map(e=>e.frame);return t.includes(`moves`)?{kind:`moving`,wearing:`the bar moves (an effect, a fade, an animated segment, or an open menu counting down to its close)`}:t.includes(`can-move`)?{kind:`moving`,wearing:`the bar can start moving (an open menu, which flashes and closes on its own, a globals.effect rule, placements that fade in and out, or a placement with an effect of its own that is not drawn now)`}:t.includes(`still`)?{kind:`still`}:t.includes(`drawing`)?{kind:`unknown`,unseen:`the bar's latest render has not finished`}:t.length>0?{kind:`unknown`,unseen:`the bar's recent renders failed`}:e.length>0?{kind:`unknown`,unseen:"only a `cc-candybar frames` display has drawn this bar, not Claude Code's statusline"}:{kind:`none`}},CF=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function wF(e,t){let n=aF(e);if(n.kind===`present`&&n.refreshInterval===1)return{ok:!0,note:`statusLine.refreshInterval is 1 in ${n.from.path}`};switch(t.kind){case`none`:return null;case`still`:return{ok:!0};case`unknown`:return CF(t.unseen);case`moving`:break}let{wearing:r}=t;switch(n.kind){case`unread`:return{ok:!1,reason:`${r}, and Claude Code's settings could not be read: ${n.reason}`};case`absent`:return{ok:!1,reason:`${r}, and no settings file Claude Code reads here sets a statusLine (read: ${n.read.join(`, `)||`none`}) — the one that runs the bar comes from --settings, MDM or server-managed settings, which the doctor cannot read; set "refreshInterval": 1 beside its command there`};case`not-an-object`:return{ok:!1,reason:`${r}, and ${n.from.path} sets statusLine to ${JSON.stringify(n.value)}, not a statusLine object — ${n.from.scope===`user`?"re-run `cc-candybar install` to write one":`replace it there with the statusLine object that runs cc-candybar`}`};case`present`:{let{from:e,refreshInterval:t}=n,i=t===void 0?`its statusLine sets no refreshInterval, so Claude Code redraws it only on events`:typeof t==`number`&&t>1?`its statusLine redraws it only every ${t} s`:`its statusLine.refreshInterval is ${JSON.stringify(t)}, not a number of seconds Claude Code accepts (its minimum is 1)`;return dte(e)?{ok:!1,reason:`${r}, but ${i} (statusLine from ${e.path})`,fix:{kind:`claude-settings`,file:e,path:[`statusLine`,`refreshInterval`],value:1}}:{ok:!1,reason:`${r}, but ${i} — its statusLine is in ${e.scope===`managed`?`managed settings`:`the project's shared settings`}, ${e.path}: set "refreshInterval": 1 there`}}}}const TF=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function EF(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return iF(e);case`bundling`:case`unread`:case`configured`:return[QP(e.name),e.version].filter(e=>e!==null).join(` `)}}function DF(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return rF(e);case`bundling`:case`unread`:return QP(e.name);case`configured`:{let t=QP(e.name);return e.font.kind===`ok`?`${t} with ${e.font.value.font} (${e.font.value.from})`:`${t}, its font unread: ${e.font.reason}`}}}function OF(e){let t=DF(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${TF(e.glyphs)}`}}const kF={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=OF(e),r=e=>t.kind===`failed`&&n!==void 0?{ok:!1,reason:e,more:[`the mark book could not be read: ${t.reason}`]}:{ok:!1,reason:e,...n!==void 0&&{sighting:n}},i=e.terminal,a=EF(i);switch(n===void 0||t.kind===`failed`?null:t.value.nerdFont?.[n.id]??null){case`drawn`:return{ok:!0};case`boxes`:return r(`${a} draws ${TF(e.glyphs)} as boxes — set a Nerd Font as its font`);case null:break}switch(i.kind){case`unreported`:return r("the client reported no terminal — re-run `cc-candybar install` to stage a current client");case`unasked`:return r(`tmux could not be asked which terminal is attached: ${i.reason}`);case`unknown`:case`unnamed`:case`unread`:return r(`the doctor cannot read ${a}'s font`);case`bundling`:{let e=XP[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:tF(i.version,e);if(t===!0)return{ok:!0};let n=QP(i.name);return r(t===null?`${n} ships Nerd Font symbols since ${e}, and did not say which release this is`:`${a} ships no Nerd Font symbols (they came in ${e}) — update ${n}, or set a Nerd Font as its font`)}case`configured`:{if(i.font.kind===`failed`)return r(`the doctor cannot read ${a}'s font: ${i.font.reason}`);let{font:e,from:t,lacks:n}=i.font.value;return n===null?r(`${a} is set to ${e} (${t}), which is not installed — install it or set a Nerd Font`):n.length===0?{ok:!0}:r(`${a} draws with ${e} (${t}), which has no ${TF(n)} — set a Nerd Font as its font`)}}}};function AF(e){return e.join(`, `)}function jF(e){return`or set missingData: "ignore" on ${AF(e)}`}function MF(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${AF(t)}: whether the forge CLI is ready could not be asked: ${n.reason}`];if(n.value===null)return[];let{cli:r,host:i,status:a}=n.value;return a===`ready`?[]:a===`missing`?[`${AF(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${jF(t)}`]:[`${AF(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${jF(t)}`]}function NF(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${AF(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${AF(n)}: no session of this Claude Code has drawn a bar for this daemon in the last ${300/60} minutes, so whether it sends rate_limits is unseen — run the doctor again once the bar has redrawn`:`${AF(n)}: ${gF(t)}, so whether Claude Code sends rate_limits is unseen — run the doctor again once the bar has redrawn`]:r.value.includes(`missing`)&&!r.value.includes(`carried`)?[`${AF(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${AF(n)}`]:[]}const PF={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>uF([...MF(e.pullRequests),...NF(e.rateLimits,t)])};function FF({path:e,answered:t,read:n}){switch(n.kind){case`absent`:return t?[`the transcript ${e} does not exist, though Claude Code has answered in its session — the bar's session cost, metrics and activity read nothing`]:[];case`failed`:return[`the transcript ${e} cannot be read: ${n.reason}`];case`ok`:{let{lines:t,unparsed:r,whole:i}=n.value;return r===0?[]:[`${r} of the ${t} lines ${i?`in`:`in the last ${cF/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const IF=[xte,Tte,Ete,Cte,kte,mte,hte,gte,xF,kF,PF,{name:`sessionData`,label:`session data`,takesMark:!1,probe:({transcripts:e,sighted:t})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.length===0?{ok:!1,reason:t.kind===`recent`?`no session has drawn a bar for this daemon in the last ${300/60} minutes, so no transcript was named — run the doctor again once the bar has redrawn`:`${gF(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:uF(e.value.flatMap(FF))}],LF=IF.filter(e=>e.takesMark);function RF(e){return IF.map(t=>({check:t,verdict:t.probe(e)}))}function zF(e){return IF.find(t=>t.name===e)}const BF=`${pi}doctor.`;function VF(e){let t=`${BF}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function HF({target:e}){return`configTarget=${e.source}`}function UF(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?rF(e.identified):null,i=t.kind===`failed`?`unread`:r===null?`-`:t.value.includes(r)?`yes`:`no`;return`tmuxLinks=${n===null?`-`:n.features.includes(`hyperlinks`)?`yes`:`no`} clicked=${i}`}function WF(e,t){let n=e.kind===`seen`?e.tmuxClient:null;return`cols=${t.kind===`failed`?`failed widthOf=-`:`${t.value.columns??`-`} widthOf=${t.value.of.kind}`} clientUtf8=${n===null?`-`:n.utf8?`yes`:`no`}`}function GF(e){if(e.kind===`failed`)return`clients=unasked`;let{daemon:t,clients:n}=e.value;return`clients=${n.map(e=>{if(e.kind===`unreported`)return`unreported/-/-`;let{bundle:n,source:r}=mF(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const KF=e=>`${e>=0?`+`:``}${mr(e)}`;function qF({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${vF(e,t.value).map(e=>e.pid).join(`,`)||`-`}`;if(e.kind===`failed`)return`${r} memory=unasked postMortems=unasked`;let{memory:i,limit:a,postMortems:o}=e.value,s=o.kind===`failed`||n.kind===`failed`?`unread`:`${_F(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Tr(i.charge)}${i.charge.kind===`stand-in`?`(${KF(-i.charge.gap)})`:``}:${mr(i.charge.bytes)}`}/${mr(a)} postMortems=${s}`}function JF(e){return`data=pr:${(()=>{if(e.pullRequests.kind===`unneeded`)return`-`;let t=e.pullRequests.fact;if(t.kind===`failed`)return`failed`;if(t.value===null)return`no-forge`;let{status:n}=t.value;return typeof n==`string`?n:`logged-out`})()},rateLimits:${(()=>{if(e.rateLimits.kind===`unneeded`)return`-`;let t=e.rateLimits.fact;if(t.kind===`failed`)return`failed`;let n=e=>t.value.filter(t=>t===e).length;return`${n(`carried`)}/${n(`missing`)}/${n(`unanswered`)}`})()}`}function YF(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>XF(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${R(i)}`;let a=bF(r.flatMap(e=>e.bars));return`frames=${YP.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${R(i)}`}function XF(e){let t=aF(e);switch(t.kind){case`unread`:return`failed`;case`absent`:case`not-an-object`:return t.kind;case`present`:return`${t.from.scope}:${t.refreshInterval===void 0?`-`:JSON.stringify(t.refreshInterval)}`}}function ZF(e){let t=oF(e,dF);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${R(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function QF(e){if(e.kind===`failed`)return`transcripts=failed`;let t=t=>e.value.filter(e=>e.read.kind===t).length,n=e.value.reduce((e,t)=>e+(t.read.kind===`ok`?t.read.value.unparsed:0),0);return`transcripts=${t(`ok`)}/${t(`absent`)}/${t(`failed`)} unparsed=${n}`}function $F(e,t){if(e.kind===`none`)return`glyphs=- terminal=- font=- mark=-`;let{glyphs:n,terminal:r}=e,i=[...n].map(e=>e.codePointAt(0).toString(16)),a=(()=>{switch(r.kind){case`unreported`:case`unasked`:return r.kind;case`unknown`:return`unknown:${JSON.stringify(r.called)}`;case`unnamed`:return`unnamed:${JSON.stringify(r.term)}`;case`bundling`:case`unread`:case`configured`:return`${r.name}@${r.version??`-`}`}})(),o=(()=>{if(r.kind!==`configured`)return`-`;if(r.font.kind===`failed`)return`failed`;let{font:e,lacks:t}=r.font.value;return`${JSON.stringify(e)}:${t===null?`not-installed`:`lacks${t.length}`}`})(),s=OF(e),c=t.kind===`failed`?`unread`:s===void 0?`-`:t.value.nerdFont?.[s.id]??`-`;return`glyphs=${i.join(`,`)} terminal=${a} font=${o} mark=${c}`}function eI(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function tI(e){return e.flatMap(({check:e,verdict:t})=>{let n=VF(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:wy},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:eI(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?wy:Cy},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const nI={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function rI(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries(nI).map(([t,n])=>[`${e}${t}`,n]))}}const iI=`armed`,aI=`disarmed`,oI=`.armed`,sI=e=>e.endsWith(oI);function cI(e,t,n){let r=[...new Set(n.map(e=>e.when))].filter(e=>e!==`true`),i=t=>r.length===0?e:`${e}.${t}`,a={};for(let e=0;e<2**r.length;e++)a[i(e)]={do:[t,...n.filter(t=>t.when===`true`||e&1<<r.indexOf(t.when)).map(e=>e.action)]};let o=(e,t)=>e===r.length?`"${i(t)}"`:`(ternary ${o(e+1,t|1<<e)} ${o(e+1,t)} (${r[e]}))`;return{link:o(0,0),actions:a}}function lI(e,t,n){let r=`${e}${oI}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${iI}")`,s=cI(e,a,n);return{template:`{{ if ${o} }}{{ action ${s.link} "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:iI},[a]:{set:r,to:aI},...s.actions},armed:o,variables:{[e]:{kind:`state`,key:r,default:aI}},disarm:a}}const uI=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function dI(e){return typeof e==`string`&&uI.test(e)?{kind:`line`,line:e}:{kind:`refused`,reason:`a slash command is "/" then its name, e.g. "/compact" or "/model opus", on one line with no control characters, got ${JSON.stringify(e)}`}}function fI(e){let t=dI(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const pI=[`/compact`,`/model`],mI=`/clear`;function hI(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=lI(`${e}clear`,{arm:mI,confirm:`${mI} ✓ confirm`},[{action:n,when:`true`}]);return{template:pI.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${zb} }}`,actions:{...Object.fromEntries(pI.map(e=>[t(e),{slash:fI(e)}])),...r.actions,[n]:{slash:fI(mI)}},variables:r.variables,disarm:r.disarm}}const gI=Array.from({length:10},(e,t)=>(t+1)*1e5),_I=gI[0],vI=gI[gI.length-1];function yI(e){let t;try{t=ko(e)}catch(e){return L(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?F(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=_I&&n<=vI?F(n):L(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${_I}–${vI} tokens)`)}function bI(e,t){let n=Math.min(t??vI,vI),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:gI.filter(e=>e<r).at(-1)??0,higher:gI.find(e=>e>r&&e<=n)??0}}function xI(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${zb} }}{{ if gt .autocompact.lower 0 }} {{ action (printf "${e}%d" .autocompact.lower) "−" }}{{ end }}{{ if gt .autocompact.higher 0 }} {{ action (printf "${e}%d" .autocompact.higher) "+" }}{{ end }}{{ if gt .autocompact.window 0 }} {{ action "${e}auto" "↺" }}{{ end }}{{ end }}{{ end }}`,bg:`{{ if ne .autocompact.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .autocompact.window 0) (ne .autocompact.error "") }}`,actions:{[`${e}auto`]:{slash:fI(`/autocompact auto`)},...Object.fromEntries(gI.map(t=>[`${e}${t}`,{slash:fI(`/autocompact ${t}`)}]))}}}const SI=e=>`{{ if ge ${e} 1000000 }}{{ printf "%.1f" (divf ${e} 1000000) }}M{{ else if ge ${e} 1000 }}{{ printf "%.1f" (divf ${e} 1000) }}K{{ else }}{{ ${e} }}{{ end }}`,CI=`${pi}edit`,wI=`${pi}toolbar`,TI=rI(pi),EI=`${pi}commands`,DI=hI(`${EI}.`),OI=`${pi}autocompact`,kI=xI(`${OI}.`,SI),AI=e=>({kind:`segment`,name:e}),jI=`${pi}tab`,MI=e=>`${jI}.${e}`,NI=e=>`${MI(e)}.toggle`,PI=e=>({variable:jI,key:jI,member:e}),FI=`${pi}save`,II=`${pi}preset.save`,LI=`${pi}preset.delete`,RI=e=>`${pi}${e}`,zI=e=>`${pi}apply.${e}`,BI=e=>`${pi}reset.${e}`,VI=`${pi}themeDefault.save`,HI=`${pi}themeDefault.differs`,UI=`${pi}themeDefault.theme`,WI={when:`{{ .${HI} }}`,template:`{{ action "${VI}" (printf "⤓ default for %s" .${UI}) }} {{ swatch "${zI(`theme`)}" .${UI} }}`},GI=`${pi}resetAll`,KI=`${gi}.toggle`,qI=`${pi}undo`,JI=`${pi}back`,YI=`${JI}.step`,XI=`${pi}navigation.back`,ZI=JI,QI={template:`{{ if gt .${XI} 0 }}{{ action "${JI}" "◁" }}{{ else }}{{ fg (${jN}) "◁" }}{{ end }}`},$I=`${pi}redo`,eL=`${pi}doctor`,tL=`${eL}.run`,nL=e=>`${eL}.fix.${e}`,rL=(e,t)=>`${eL}.mark.${e}.${t}`,iL=e=>`${eL}.${e}`,aL={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},oL=Gj(`${pi}pickers`),sL=e=>`${pi}${e}`,cL=e=>`${sL(e)}.toggle`,lL=e=>lM(e)?Gj(`${pi}${e}Pickers`):oL,uL=e=>{let t=lL(cM[oM[e].beside]);return{variable:t,key:t,member:e}},dL={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${LI}" (printf "🚮 delete %s" .${Mx.preset.effectiveVar}) }}`}},fL=(e,t)=>`${pi}list.${e}.${t}`,pL=e=>`${pi}resettable.${e}`,mL=e=>e.length===0?`false`:`(or ${e.map(e=>`(and (${e.shown}) .${pL(e.name)})`).join(` `)})`,hL=Vb.map(e=>[Bb[e].switch.setting,e]),gL={variables:{},actions:{},segments:{}},_L=Object.fromEntries(hL.map(([e,t])=>[e,gN(`${pi}help.${e}`,kN[t],[],gL)])),vL=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],yL=e=>{let t=t=>`.${Kb(e,t)}`,n=vL.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if eq .${Mx[Bb[e].switch.setting].effectiveVar} ${JSON.stringify(Bb[e].switch.on)} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},bL=`{{ if .diagnostics.label }} {{ bg .diagnostics.bg (fg .diagnostics.fg (action "${yi}" .diagnostics.label .diagnostics.open)) }}{{ end }}`,xL=`${pi}fps`,SL=`{{ if eq .${Wb(`by`)} "feed" }}{{ printf "%3s" (printf "≤%d" (int .${Wb(`fps`)})) }} fps{{ else }}${`polled`.padStart(7)}{{ end }}`,CL=Object.fromEntries(hL.map(([e,t])=>[e,yL(t)])),wL=e=>sM.filter(t=>oM[t].beside===e),TL=Object.keys(Mx).map(e=>{let t=Mx[e],n=cM[e];return{...t,name:e,place:n,control:nM({label:t.label,domain:gM(t.configKey)},t.sessionKey,t.effectiveVar,zI(e),lL(n)),beneath:t.previews.map(e=>dL[e]),help:[_L[e]].filter(e=>e!==void 0),submenus:wL(e)}}),EL=e=>TL.filter(t=>t.place===e),DL=e=>TL.filter(t=>uM(t.place,e)),OL=e=>t=>`(print ${oi(t)} (ternary ${oi(` •`)} "" ${mL(DL(e))}))`,kL=e=>EL(e).flatMap(e=>[VL(e),...e.help,...e.submenus.map(e=>ti(sL(e),uL(e),JL(e),`drop`))].map(t=>({...t,when:`{{ ${e.shown} }}`})));new Set(TL.flatMap(e=>[e.sessionKey,e.configKey]));const AL=lI(GI,{arm:`⟲`,confirm:`⟲ reset all?`},TL.map(e=>({action:BI(e.name),when:e.shown}))),jL=[`unsaved`,`history.undo`,`history.redo`],ML=e=>`${pi}${e}`,NL=ML(`unsaved`),PL=(e,t)=>({body:t,shown:`(gt .${ML(e)} 0)`}),FL=[PL(`unsaved`,`{{ action "${FI}" (printf "💾 save %d" .${NL}) }}`),PL(`history.undo`,`{{ action "${qI}" "↶" }}`),PL(`history.redo`,`{{ action "${$I}" "↷" }}`),{body:AL.template,shown:`(or ${mL(TL)} ${AL.armed})`}],IL={when:`{{ or ${FL.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+FL.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},LL=[{step:AL,place:`door`},{step:DI,place:`session`}],RL=e=>e.map(e=>e.step.disarm),zL=RL(LL),BL=RL(LL.filter(e=>e.place!==`door`));function VL(e){let t=RI(e.name);return e.control.kind===`inline`?AI(t):ti(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>AI(fL(e.name,n)))},`drop`)}function HL(e){return e===gi}function UL(e){let t=AI(gi);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[UL(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[t,e]};if(e.when===void 0)return{...e,children:[t,...e.children]};let{when:n,children:r,...i}=e;return{...i,children:[t,{kind:`container`,direction:i.direction,when:n,children:r}]}}function WL(e){return GL(e)>0?e:UL(e)}function GL(e){let t=0;for(let n of Fy(e))n.kind===`segment`&&HL(n.name)&&(t+=1);return t}function KL(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&HL(e.name)||e.opens!==void 0&&KL(e.opens.body,!0):e.children.some(e=>KL(e,n))}const qL={door:{direction:`horizontal`,content:[AI(ZI)],after:[AI(CI),AI(FI)]},session:{direction:`vertical`,content:[AI(wI),{kind:`container`,direction:`horizontal`,children:[AI(EI),AI(OI)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[AI(II)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[AI(eL),...IF.map(e=>AI(iL(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[AI(VI)]},toggles:{direction:`horizontal`,content:[],after:[]}};function JL(e){let{direction:t,content:n,after:r}=qL[e];return{kind:`container`,direction:t,children:[...n,...kL(e),...r]}}function YL(e){return e.kind===`segment`?HL(e.name)?{kind:`container`,direction:`horizontal`,children:[ti(e.name,vi,ZL,`above`),AI(xL)]}:e:QL(e)}function XL(){return{kind:`container`,direction:`vertical`,children:[JL(`door`),{kind:`container`,direction:`horizontal`,children:iM.map(({member:e})=>ti(MI(e),PI(e),JL(e),`drop`))}]}}const ZL=XL();function QL(e){return{...e,children:e.children.map(e=>YL(e))}}function $L(e){let t={variables:{[gi]:si(gi,Yr),[yi]:{kind:`state`,key:yi,default:`0`}},actions:{[KI]:P(gi,_i),[yi]:{set:yi,int:!0},[gi]:{do:[KI,...zL]},[tL]:{doctor:`run`},...TI.actions,...DI.actions,...kI.actions,[FI]:{save:!0},[qI]:{undo:!0},[YI]:{back:!0},[JI]:{do:[YI,...zL]},[$I]:{redo:!0},[II]:{preset:`save`},[VI]:{themeDefault:`save`},[LI]:{preset:`delete`,name:`{{ .${Mx.preset.effectiveVar} }}`}},segments:{[gi]:{template:`{{ $door := ${ai(gi,oi(e),oi(`✖`))} }}{{ if ${ri(vi)} }}{{ fg (keptOn (roleTextOn "error" (bgOf)) (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+bL},[xL]:{template:SL},[wI]:{template:TI.template},[EI]:{template:DI.template,when:DI.when},[OI]:{template:kI.template,bg:kI.bg,when:kI.when},[ZI]:QI,[FI]:IL,[VI]:WI,[II]:{template:`{{ action "${II}" "+ preset" }}`},[eL]:{template:`{{ action "${tL}" "🩺 doctor" }}`},[CI]:{template:`{{ action "${oN}" "✎ arrange" "✎ done" }}`}}};t.variables[HI]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[UI]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[XI]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of jL)t.variables[ML(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[jI]=si(jI,Yr);for(let{member:e,label:n}of iM){t.actions[NI(e)]=P(jI,e),t.actions[MI(e)]={do:[NI(e),...BL]};let r=OL(e);t.segments[MI(e)]={template:`{{ ${ai(MI(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,DI.variables,AL.variables),tR(t),eR(t),t}function eR(e){for(let t of IF){let n=VF(t.name),r=nL(t.name);for(let t of Object.values(n))e.variables[t]={kind:`state`,key:t,default:``};e.actions[r]={doctor:`fix`,check:t.name};let i=t.takesMark?sF:[];for(let n of i)e.actions[rL(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${rL(t.name,e)}" "${aL[e]}" }}`).join(``);e.segments[iL(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ if ne .${n.reason} "" }} — {{ .${n.reason} }}{{ end }}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${Cy}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function tR(e){for(let t of TL){Object.assign(e.actions,t.control.actions);let n=BI(t.name);e.actions[n]={reset:t.configKey},e.variables[pL(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${pL(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[RI(t.name)]={template:`${t.control.template}${CL[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[fL(t.name,r)]=n})}Object.assign(e.actions,AL.actions),Object.assign(e.variables,gL.variables),Object.assign(e.actions,gL.actions),Object.assign(e.segments,gL.segments);for(let t of sM){let n=uL(t);e.actions[cL(t)]=P(n.key,n.member),e.segments[sL(t)]={template:`{{ action "${cL(t)}" ${OL(t)(oM[t].trigger)} }}`}}}function nR(e){let{variables:t,actions:n}=hN();Object.assign(e.variables,t),Object.assign(e.actions,n)}function rR(e){let t=$L(e.globals.menuGlyph??`🍫`);nR(t);let n={...e.presets},r=[];for(let t of mS(e.presets)){let{node:i}=_S(e,t),a=YL(WL(i));r.push(a),n[t]={...gS(e.presets,t),root:a}}let i=Vj(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const iR=`${fi}live`,aR=[`☐ live`,`☑ live`],oR=`${fi}done`,sR=`${fi}cancel`,cR=`${fi}rewind`,lR=`${fi}changes`,uR=`(gt .${lR} 0)`,dR=`(or ${uR} (gt .${NL} 0))`,fR={variable:iR,key:iR,member:Xr};function pR(e){return`${fi}configuring.p${e}`}function mR(e){return`and ${ri(uN)} (not ${ri(fR)}) (ne .${pR(e)} "true")`}function hR(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${aN} "${ei(e)}")`).join(` `)} false }}`}}function gR(e,t,n){return`{{ if ${mR(e)} }}${t}{{ else }}${n}{{ end }}`}const _R=`{{ and ${ri(uN)} .preset.customized }}`,vR=hi;function yR(e){return new Map([...wS(e),...xR(e)])}const bR=`${fi}addable`;function xR(e){return new Map([[bR,{members:Object.keys(e.segments).filter(e=>!vR(e)),library:{groups:QM.map(e=>({id:e,label:$M[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function SR(e,t,n){return n.segments[e]={template:t,when:dN,bg:vN},{kind:`segment`,name:e}}function CR(e,t,n){let r=`${fi}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${yv}`}) (action "${r}" "✖") }}`}function wR(e){return`{{ if ${ri(uN)} }}${e}{{ end }}`}function TR(e,t){return e.reduce((e,t)=>`{{ if and ${ri(uN)} ${ri(t)} }}true{{ else }}${e}{{ end }}`,t)}function ER(e){return e.flatMap(e=>[...Fy(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function DR(e,t,n){return`${cN}${e}.${t}.${n}`}function OR(e,t,n,r){let i=jy(n),a=`${fi}${e.presetIdent}`,o=lN(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=Gj(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:Yr},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:aN,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=DR(e.presetIdent,i,r),l=`${cN}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:tb(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=nM(eM(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};e.artifacts.segments[d]={template:f.template};let p=f.list.rows.map((t,n)=>{let r=`${d}.list.${n}`;return e.artifacts.segments[r]={template:t},{kind:`segment`,name:r}});return ti(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${wN}" }}`,ref:{variable:aN,key:aN,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const kR=`${fi}label:`;function AR(e){if(e.startsWith(kR)){let t=e.slice(kR.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function jR(e,t,n,r){let i=jy(e),a=MR(n,i,e,t,i),o=Object.fromEntries(Xy.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...ti(a,r.ref,r.body,`drop`,TR([r.ref],`{{ ${mR(n.presetIdent)} }}`)),...Object.keys(o).length>0&&{settings:o},drafts:Object.fromEntries(Xy.map(e=>[e,r.drafts[e]]))}}function MR(e,t,n,r,i){let a=`${kR}${t}:${n.name}`;return e.artifacts.segments[a]={template:`{{ "${ei(i)}" }}`,...r.palette!==void 0&&{palette:r.palette}},a}function NR(e,t,n,r){let i=jy(e),a=n?[IR(r,String(r.posCounter.n++),i,`before`)]:[],o=String(r.posCounter.n++),s=IR(r,o,i,`after`),c=CR(r,o,i),l=r.segments[e.name],u=OR(r,o,e,Zy(l)),d=wR(c),f=wR(u.term);return[...a.map(e=>SR(e.host,e.template,r.artifacts)),{...jR(e,l,r,u),lead:d,trail:f},{...t,when:gR(r.presetIdent,`false`,e.when??`true`),lead:d,trail:f,drafts:u.drafts},SR(s.host,s.template,r.artifacts)]}function PR(e){return E.join(E.basename(E.dirname(e)),E.basename(e))}function FR(e,t,n,r){let i=r.segments[e.name],a=jy(e);return[{kind:`segment`,name:MR(r,`${a}/${r.presetIdent}`,e,i,`${a} · ${PR(t.file)} ${t.entry}`),when:`{{ ${mR(r.presetIdent)} }}`},{...n,when:gR(r.presetIdent,`false`,e.when??`true`)}]}function IR(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${fi}${i}.insert.${t}`,s=`${fi}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:bR,anchor:n,relation:r};let c=Uj(o),l=Wj(s,o,void 0),u=qj(l),d=Kj(l,c);return a.variables[l]={...si(l,Yr),within:[uN]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=P(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${ri({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${yv}`}) $m }}{{ end }}`}}function LR(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!vR(e.name)&&e.insertedBy===void 0),i=e=>LR(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Py(o,i);if(vR(o.name)){n.push(s);continue}let c={kind:`container`,direction:`horizontal`,children:o.insertedBy===void 0?NR(o,s,a===r,t):FR(o,o.insertedBy,s,t),unit:!0};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[c]}:c)}return{...e,children:n,...e.when!==void 0&&{when:TR(ER(n),gR(t.presetIdent,`true`,e.when))}}}function RR(e,t,n,r,i,a,o){let s=`${fi}${t}.resetLayout`,c=`${fi}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:_R},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},zR(e,o)]}}function zR(e,t){if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t]};let n=e.children.at(-1);return e.direction===`vertical`&&n!==void 0&&(n.kind===`segment`||n.when===void 0)?{...e,children:[...e.children.slice(0,-1),zR(n,t)]}:{...e,children:[...e.children,t]}}function BR(e,t,n,r,i,a){let{node:o}=_S(e,t),s={presetIdent:Hj(t),rootKey:GM(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=LR(o,s);return n.variables[pR(s.presetIdent)]=hR(s.configured),RR(c,s.presetIdent,s.rootKey,n,r,i,a)}function VR(e){let t={variables:{},actions:{},segments:{}},n=gN(`${fi}help`,ON,[uN],t);t.variables[iR]=si(iR,Yr),t.actions[iR]=P(iR,fR.member),t.segments[iR]={template:ii(iR,...aR),when:dN};let r={kind:`segment`,name:iR},i=n;t.variables[lR]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[oR]={do:[FI,oN]},t.segments[oR]={template:`{{ if ${dR} }}{{ action "${oR}" "✓ save" }}{{ else }}{{ action "${oR}" "✓ done" }}{{ end }}`,when:dN},t.actions[cR]={rewind:!0},t.actions[sR]={do:[cR,oN]},t.segments[sR]={template:`{{ action "${sR}" "↩ cancel" }}`,when:`{{ and ${ri(uN)} ${uR} }}`};let a=[{kind:`segment`,name:oR},{kind:`segment`,name:sR}],o={...e.presets},s=[];for(let n of mS(e.presets)){let c=BR(e,n,t,a,r,i);s.push(c),o[n]={...gS(e.presets,n),root:c}}let c=Vj(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function HR(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function UR(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function WR(e,t,n){let r=Ny(e,new Set(n.map(My).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const GR=/^-?\d+$/;function KR(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function qR(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!GR.test(t))return{ok:!1,reason:`${e} must be an integer, got "${t}"`};let n=t[0]===`-`,r=(n?t.slice(1):t).replace(/^0+/,``);return r===``?{ok:!0,value:`0`}:{ok:!0,value:n?`-${r}`:r}}}function JR(e,t,n){return r=>r?GR.test(r)?{ok:!0,value:String(Math.max(e,Math.min(t,parseInt(r,10))))}:{ok:!1,reason:`${n} must be an integer, got "${r}"`}:{ok:!1,reason:`${n} value is required`}}function YR(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!GR.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i}}return{kind:`int`}}function XR(e){return e===`config`?`set-config`:`set-state`}function ZR(e,t,n){return t.kind===`int`?qR(`menu page "${e}"`):t.kind===`range`?JR(t.min,t.max,`${n} stepper "${e}"`):KR(t.allowed,`${n} "${e}"`,XR(n))}function QR(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:YR(e,n,t)}))}function $R(e,t,n,r){let i=new Map(Object.entries(e)),a=new Map,o=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of n)if(o.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let s=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...n];for(let{key:t,spec:n}of QR(s,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,ZR(t,n,r)),n.kind===`range`&&a.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>a.get(e)??null}}function ez(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};$R(e,[o],[],t),r.push(o),i++;let s=!0;return()=>{s&&(s=!1,r.splice(r.indexOf(o),1),i++)}},gateFor(o){let s=a.get(o);if(s?.epoch===i)return s.gate;let c=$R(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}function tz(){return ez({},`config`,az)}function nz(e,t){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:ES(e.from,t).members}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[HR({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[HR({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:ES(e.insertSegmentFrom,t).members.map(t=>HR({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function rz(e){let t=new Set;for(let n of Object.values(e.actions)){`reset`in n&&t.add(n.reset);let e=`persist`in n?YM(n.persist):null;e?.scope===`preset-root`&&t.add(GM(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function iz(e){let t=yR(e);return[...rz(e),...Object.values(e.actions).flatMap(e=>nz(e,t))]}function az(e){return QR(iz(e),`config`)}const oz=qv(),sz=new Set(oz),cz=new Set(hy),lz=e=>e?sz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${oz.join(`, `)})`}:{ok:!1,reason:`theme name is required`},uz=e=>e?cz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${hy.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},dz=new Set([`1`,`true`]),fz=new Set([`0`,`false`]),pz={endcaps:uz,theme:lz,"toolbar-expanded":e=>dz.has(e)?{ok:!0,value:`1`}:fz.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}};function mz(){return ez(pz,`state`,vz)}function hz(e,t){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:ES(e.from,t).members}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function gz(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(pz,e.key))}function _z(e){let t=yR(e);return gz(Object.values(e.actions).flatMap(e=>hz(e,t)))}function vz(e){return QR(_z(e))}function yz(e){let t=mz(),n=tz();for(let{key:n,allowed:r}of e.state)t.register(n,r);for(let{key:t,allowed:r}of e.config)n.register(t,r);return{state:t,config:n}}const bz=`update.dismissed`,xz=`updateNotice`,Sz=Mx.updateNotice.sessionKey;function Cz(){return yz({config:[{key:xz,allowed:[`false`]}],state:[{key:Sz,allowed:[`false`]},{key:bz,allowed:[]}]})}function wz(e){try{return l.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function Tz(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:Oz(t.segments,Ez(t.segments,e.segments??{})),root:oS(e.root??$x,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:Oz(t.presets,Dz(t.presets,e.presets??{})),themeDefaults:Oz(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function Ez(e,t){let n=(t,n,r)=>r[n]===void 0?r:{...r,[n]:{...e[t]?.[n],...r[n]}};return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,n(e,`partials`,n(e,`settings`,t))]))}function Dz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.globals===void 0?n:{...n,globals:{...e[t]?.globals,...n.globals}}]))}function Oz(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const kz=new Map([[`gitTaculous`,{kind:`built-in`,to:`gitaculous`}],[`git`,{kind:`built-in`,to:`gitaculous`}],[`settings.menu`,{kind:`built-in`,to:`candybar.menu`}],[`ticket`,{kind:`plugin`,to:`plugins.lit.ticket`,source:`promptctl/links-issue-tracker`}],[`ceiling`,{kind:`removed`,why:`the program it showed draws it through a cc-candybar plugin of its own now — delete this reference, or place that plugin's segment`}],[`themeSwitcher`,{kind:`removed`,why:'the settings menu\'s 🎨 theme control steps themes — delete this reference, or write your own `{{ carousel "apply" "open" "label" }}`'}]]);function Az(e){let t=kz.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`;case`removed`:return` (the built-in segment "${e}" was removed: ${t.why})`}}function jz(e,t,n,r){return n.cache===void 0?(e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${Vy.join(`, `)})`,line:q(e.source,t.split(`.`))}),null):Pz(e,`${t}.cache`,n.cache)}function Mz(e){return{required:!0,json:Fz(),parse:(t,n,r,i)=>jz(t,n,i,e)??void 0}}const Nz={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Lz(n)?{ttl:n}:vb(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${J(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return vb(e,t,`cache.watch_file must be a path string, got ${J(n)}`);let r=Ab(`cache.watch_file`,n);return r===null?{watch_file:n}:vb(e,t,r)}},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:vb(e,t,`cache.depends_on must be an array of variable-name strings, got ${J(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:vb(e,t,`cache.key must be a non-empty template string, got ${J(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:vb(e,t,`cache.never must be the literal boolean true, got ${J(n)}`)}}};function Pz(e,t,n){return yb(e,Nz,t,n)}function Fz(){return Lb(Nz)}const Iz=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Lz(e){return Iz.test(e)}const Rz=new Map([[`session.budget.amount`,{segment:`session`,setting:`budget`}],[`session.budget.warningThreshold`,{segment:`session`,setting:`warnAt`}],[`today.budget.amount`,{segment:`today`,setting:`budget`}],[`today.budget.warningThreshold`,{segment:`today`,setting:`warnAt`}],[`block.budget.heatThreshold`,{segment:`block`,setting:`warnAt`}],[`block.budget.warningThreshold`,{segment:`block`,setting:`errorAt`}],[`weekly.budget.heatThreshold`,{segment:`weekly`,setting:`warnAt`}],[`weekly.budget.warningThreshold`,{segment:`weekly`,setting:`errorAt`}],[`burn.eta.errorMinutes`,{segment:`burnrate`,setting:`errorWithin`}],[`burn.eta.warnMinutes`,{segment:`burnrate`,setting:`warnWithin`}]]);function zz(e){return`it became the "${e.setting}" setting of each "${e.segment}" placement — set it on the placement where a row places "${e.segment}" ({ seg: "${e.segment}", settings: { ${e.setting}: <value> } }), or redeclare segments.${e.segment}.settings.${e.setting} with the default every placement should start from`}function Bz(e){let t=Rz.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${zz(t)}`}function Vz(e){let t=Rz.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${zz(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const Hz=new Map([[`git.timeSinceCommit`,`the payload stores the commit's date as "git.committedAt" (epoch seconds), and the bundled template variable "git.timeSinceCommit" computes its age at the draw: drop this declaration`],[`block.etaMinutes`,`the bundled template variable "block.etaMinutes" computes it at the draw: drop this declaration`],[`weekly.etaMinutes`,`the bundled template variable "weekly.etaMinutes" computes it at the draw: drop this declaration`]]),Uz=new Map([[`branch`,{read:`.git.branch`,declare:{kind:`input`,path:`git.branch`,default:``},note:`when HEAD is on no branch it reads "detached", where this kind read ""`}],[`sha`,{read:`.git.sha`,declare:{kind:`input`,path:`git.sha`,default:``}}],[`dirty`,{read:`(ne .git.status "clean")`,declare:{kind:`template`,template:`{{ ne .git.status "clean" }}`,type:`boolean`}}],...[`ahead`,`behind`,`stash`].map(e=>[e,{read:`.git.${e}`,declare:{kind:`input`,path:`git.${e}`,type:`number`,default:0}}])]);function Wz(e){let t=e=>typeof e==`string`&&e.includes(`"`)&&!e.includes(`'`)?`'${e}'`:JSON.stringify(e);return`{ ${Object.entries(e).map(([e,n])=>`${e}: ${t(n)}`).join(`, `)} }`}function Gz(e){let t=`kind "git" is retired: every git fact is an input over the payload's git lane, which the bundled default already declares — drop this declaration and`,n=typeof e.field==`string`?Uz.get(e.field):void 0;if(n===void 0){let e=[...Uz.values()].map(({read:e})=>e);return`${t} read whichever of ${e.slice(0,-1).join(`, `)} or ${e.at(-1)} it stood for, where it was read`}let r=n.note===void 0?``:` (${n.note})`;return`${t} read ${n.read} where it was read${r}, or declare ${Wz(n.declare)} under a name of your own`}function Kz(e,t,n){if(n===void 0)return{};if(!db(n))return e.issues.push({path:t,message:`${t} must be an object, got ${fb(n)}`,line:q(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=bb(e,gB,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function qz(){return{required:!0,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.value;if(typeof i!=`string`&&typeof i!=`number`&&typeof i!=`boolean`){e.issues.push({path:`${t}.value`,message:`literal value must be string|number|boolean, got ${fb(i)}`,line:q(e.source,t.split(`.`))});return}return i}}}function Jz(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Iee(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const Yz={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:vb(e,t,`parse.text must be the literal boolean true, got ${J(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?Xz(e,t,n):vb(e,t,`parse.regex must be a pattern string, got ${J(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:vb(e,t,`parse.json must be the literal boolean true, got ${J(n)}`)}}};function Xz(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return vb(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:vb(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function Zz(){return{required:!1,json:Lb(Yz),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:q(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:yb(e,Yz,`${t}.parse`,r.parse)??void 0)}}function Qz(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>db(r.parse)&&`json`in r.parse?$z(e,t,r.default):cb(e,t,r,`default`)}}function $z(e,t,n){if(n!==void 0)return eB(n)?n:vb(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${J(n)}`)??void 0}function eB(e){return e!==null&&tB(e)}function tB(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(tB);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(tB)}default:return!1}}const nB={value:qz(),default:wb()};function rB(){let e=kb();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:Hz.get(a);return o===void 0?a:vb(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const iB={path:rB(),type:Mb([`string`,`number`,`boolean`]),default:Jz()},aB={name:kb(),default:wb()},oB={path:jb(),readMode:Mb([`whole`,`first-line`]),parse:Zz(),cache:Mz(`file`),default:Qz()},sB={command:kb(),parse:Zz(),cache:Mz(`shell`),default:Qz()};function cB(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const lB={template:kb(),type:Mb([`string`,`number`,`boolean`]),default:Jz()},uB=cB(`a template variable recomputes whenever a variable it reads changes`),dB={layout:kb(),default:wb()},fB=cB(`a time variable reads the instant its render is drawn at`),pB={key:kb(),default:wb()},mB=`kind`;function hB(e,t,n={}){return{...xb(mB,e,t),parse:(r,i,a)=>{mb(r,n,i,a);let o=hb(r,t,i,a);return o===null?null:{kind:e,...o}}}}const gB={tag:mB,noun:`source kind`,memberNoun:`variable`,arms:{literal:hB(`literal`,nB),input:hB(`input`,iB),env:hB(`env`,aB),file:hB(`file`,oB),shell:hB(`shell`,sB),template:hB(`template`,lB,uB),time:hB(`time`,dB,fB),state:hB(`state`,pB)},retired:{git:Gz}};function _B(){return Ib(gB)}function vB(){return{type:`object`,additionalProperties:_B()}}const yB=/^[A-Za-z_][A-Za-z0-9_]*$/,bB={pattern:yB.source},xB={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},SB={type:`object`,additionalProperties:!1,required:[`label`,`domain`,`default`],properties:{label:{type:`string`,pattern:`^[^\\n\\r]+$`},domain:{anyOf:[{const:`bool`},{type:`array`,items:{type:`string`,pattern:`^[^/\\n\\r]+$`},minItems:1,uniqueItems:!0},{type:`object`,additionalProperties:!1,required:[`min`,`max`],properties:{min:{type:`integer`},max:{type:`integer`},step:{type:`integer`,minimum:1},atLeast:{type:`string`,...bB}}}]},default:xB}},CB=[`label`,`domain`,`default`],wB=[`min`,`max`,`step`,`atLeast`];function TB(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,t.split(`.`))})}function EB(e,t,n){if(n===`bool`)return`bool`;if(Array.isArray(n)){let r=n.filter(e=>typeof e==`string`);if(n.length===0||r.length!==n.length)return TB(e,t,`a list domain must be a non-empty list of words, got ${JSON.stringify(n)}`);if(new Set(r).size!==r.length)return TB(e,t,`a list domain names each word once, got ${JSON.stringify(n)}`);let i=r.filter(e=>e===``||e.includes(`/`)||/[\n\r]/.test(e));return i.length>0?TB(e,t,`a list domain's words must be non-empty, slash-free, and newline-free — configure mode writes each on the set-state wire — got ${JSON.stringify(i)}`):r}if(db(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!wB.includes(e)).length===0&&Number.isInteger(r)&&Number.isInteger(i)&&r<=i&&Number.isInteger(a)&&a>=1&&(o===void 0||typeof o==`string`)?{min:r,max:i,step:a,...o!==void 0&&{atLeast:o}}:TB(e,t,`a range domain is { min, max, step?, atLeast? } with integers min ≤ max, a whole step ≥ 1, and atLeast naming another range setting, got ${JSON.stringify(n)}`)}return TB(e,t,`domain must be "bool", a list of words, or { min, max }, got ${J(n)}`)}function DB(e,t,n){if(!db(n))return TB(e,t,`${t} must be { label, domain, default }, got ${fb(n)}`);for(let r of Object.keys(n))CB.includes(r)||TB(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${CB.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||TB(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${J(r)}`);let a=EB(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!OB(n.default)||!eb(o,n.default)?TB(e,`${t}.default`,`default must be ${rb(o)}, got ${J(n.default)}`):o}function OB(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const kB={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${Jy}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function AB(e){return Xy.includes(e)}function jB(){return{required:!1,json:{type:`object`,propertyNames:{...bB,not:{enum:[...Xy]}},additionalProperties:SB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!db(i))return TB(e,a,`${a} must be an object of name → { label, domain, default }, got ${fb(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!yB.test(t)){TB(e,`${a}.${t}`,`setting name "${t}" is read as .settings.${t} in a template, so it must be an identifier (letters, digits, _; not starting with a digit)`);continue}if(AB(t)){TB(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${kB[t]}`);continue}let r=DB(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const MB=mi.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function NB(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${MB})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!hi(i)?i:TB(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${mi.map(e=>`"${e}"`).join(`, `)} namespaces, got ${J(i)}`)}}}function PB(){return{required:!1,json:{type:`object`,propertyNames:bB,additionalProperties:xB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!db(i))return TB(e,a,`a placement's "settings" must be an object of setting name → value, got ${fb(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))OB(n)?o[t]=n:TB(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${fb(n)}`);return o}}}function FB(e){return new Set(Object.keys(e.segments).filter(e=>!hi(e)))}function IB(e,t,n){if(t===void 0)return{};if(!db(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${fb(t)}`,line:q(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=pb(e,n.has(i)?KB:GB,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function LB(e,t,n,r){let i=r[n];if(typeof i==`string`)return i;if(Array.isArray(i)){let r=!0,a=[];for(let[o,s]of i.entries()){if(typeof s==`string`){a.push(s);continue}r=!1,e.issues.push({path:`${t}.${n}[${o}]`,message:`${t}.${n}[${o}] must be a string, got ${fb(s)}`,line:q(e.source,[...t.split(`.`),n])})}return r?a.join(``):void 0}e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be a string or an array of strings, got ${fb(i)}`,line:q(e.source,[...t.split(`.`),n])})}const RB={anyOf:[{type:`string`},{type:`array`,items:{type:`string`}}]};function zB(){return{required:!0,json:RB,parse:(e,t,n,r)=>r[n]===void 0?vb(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own${Az(t.slice(9))}`)??void 0:LB(e,t,n,r)}}function BB(){return{required:!1,json:RB,parse:(e,t,n,r)=>r[n]===void 0?void 0:LB(e,t,n,r)}}function VB(){return{required:!1,json:{type:`object`,additionalProperties:RB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;if(!db(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be an object, got ${fb(i)}`,line:q(e.source,[...t.split(`.`),n])});return}let a=Object.create(null);for(let r of Object.keys(i)){let o=LB(e,`${t}.${n}`,r,i);o!==void 0&&(a[r]=o)}return a}}}function HB(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${J(i)}`,line:q(e.source,[...t.split(`.`),n])})}}}}function UB(){return{required:!1,json:vB(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return Kz(e,`${t}.${n}`,i)}}}const WB={template:zB(),description:wb(),group:Mb(ZM),width:HB(),justify:Mb(Eee),truncate:Mb(Dee),bg:wb(),fg:wb(),when:wb(),palette:Ob(),vars:UB(),settings:jB(),missingData:Mb(Gy),partials:VB()},GB={noun:`segment key`,fields:WB},KB={noun:`segment key`,fields:{...WB,template:BB()}};function qB(e,t){if(t===void 0)return{};if(!db(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${fb(t)}`,line:q(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${J(i)}`,line:q(e.source,[`helpers`,r])});continue}n[r]=i}return n}function JB(e,t,n){if(t===void 0)return{};if(!db(t))return X(e,`actions`,`actions must be an object, got ${fb(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=YB(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function X(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,t.split(`.`))})}function YB(e,t,n,r){if(!db(n))return X(e,t,`${t} must be an action object, got ${fb(n)}`),null;if(`persistWhen`in n)return X(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let i=kS.filter(e=>e in n);return i.length===1?ZB(r)[i[0]](e,t,n):(X(e,t,`action must declare exactly one of: ${kS.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function XB(e){return e===`<default>`?{dir:null}:E.isAbsolute(e)?{dir:E.dirname(e)}:{text:e}}const ZB=e=>({set:(e,t,n)=>NV(e,t,n,`set`,kV),persist:(e,t,n)=>NV(e,t,n,`persist`,AV),copy:QB(`copy`),open:QB(`open`),reset:$B,undo:tV(`undo`),redo:tV(`redo`),back:tV(`back`),rewind:tV(`rewind`),save:tV(`save`),preset:nV,themeDefault:rV,doctor:aV,slash:oV,run:lV(e),do:uV});function QB(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&X(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=sb(t,n,r,e);return i===null?null:{[e]:i}}}function $B(e,t,n){for(let r of Object.keys(n))r!==`reset`&&X(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=dV(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}const eV={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,back:`it steps the session's navigation history`,rewind:`it steps the session's settings history back to where edit mode opened`,save:`it saves the session's unsaved settings`};function tV(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&X(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(X(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${eV[e]}), got ${J(r[e])}`),null)}}function nV(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||X(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return X(e,`${t}.preset`,`preset must be "save" or "delete", got ${J(r)}`),null;if(r===`save`)return{preset:`save`};let a=sb(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function rV(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&X(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(X(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${J(n.themeDefault)}`),null)}const iV={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function aV(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(iV,r),a=i?iV[r]:[...new Set(Object.values(iV).flat())];for(let r of Object.keys(n))a.includes(r)||X(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return X(e,`${t}.doctor`,`doctor must be ${Object.keys(iV).map(e=>`"${e}"`).join(`, `)}, got ${J(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?LF:IF;if(typeof o!=`string`||!s.some(e=>e.name===o))return X(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${J(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return sF.includes(c)?{doctor:`mark`,check:o,mark:c}:(X(e,`${t}.mark`,`doctor mark must be ${sF.map(e=>`"${e}"`).join(` or `)}, got ${J(c)}`),null)}function oV(e,t,n){for(let r of Object.keys(n))r!==`slash`&&X(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=dI(n.slash);return r.kind===`refused`?(X(e,`${t}.slash`,r.reason),null):{slash:r.line}}const sV=[`run`,`env`,`refreshes`],cV=/^[A-Za-z_][A-Za-z0-9_]*$/;function lV(e){return(t,n,r)=>{for(let e of Object.keys(r))sV.includes(e)||X(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${sV.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&X(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${J(a)}`);let o=r.env??{};(!db(o)||Object.entries(o).some(([e,t])=>!cV.test(e)||typeof t!=`string`))&&X(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${J(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&X(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${J(s)}`),`dir`in e||X(t,`${n}.run`,`a run action runs in the directory of the file that declares it, and ${e.text} is no file`),t.issues.length>i||!(`dir`in e)?null:{run:a,env:o,refreshes:s,cwd:e.dir}}}cV.source;function uV(e,t,n){for(let r of Object.keys(n))r!==`do`&&X(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(X(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${J(r)}`),null):{do:r}}function dV(e,t,n,r,i,a){let o=sb(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(X(e,s,i),null):o.includes(`/`)?(X(e,s,a(o)),null):o}const fV={set:`the SessionState key to write`,persist:`the config globals field to write`};function pV(e,t,n,r){let i=fV[r],a=dV(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);return a===null?null:{[r]:a}}function mV(e){return e===`set`?`set-state`:`set-config`}const hV={to:PV(`set`)},gV={to:PV(`persist`)},_V={from:FV(`set`)},vV={from:FV(`persist`)},yV={min:BV(),max:BV(),by:BV()},bV={int:LV()},xV={cycle:IV(`set`)},SV={cycle:IV(`persist`)},CV={removeSegment:RV(`removeSegment`)},wV={insertSegment:RV(`insertSegment`),anchor:RV(`anchor`),relation:zV()},TV={insertSegmentFrom:FV(`persist`),anchor:RV(`anchor`),relation:zV()},EV={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},DV={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function OV(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>hb(e,t,n,r),c=Nb(t);return{detect:a,allowed:[...o,...i],label:i.join(`/`),json:{type:`object`,properties:{...Object.fromEntries(o.map(e=>[e,{type:`string`}])),...c.properties},required:[...o,...c.required??[]],additionalProperties:!1},parse:n.length?Cb(s,...n):s}}const kV=[OV(`set`,hV),OV(`set`,_V),OV(`set`,yV,[EV,DV]),OV(`set`,bV),OV(`set`,xV)],AV=[OV(`persist`,gV),OV(`persist`,vV),OV(`persist`,yV,[EV,DV]),OV(`persist`,SV),OV(`persist`,CV),OV(`persist`,wV,[],[`insertSegment`]),OV(`persist`,TV,[],[`insertSegmentFrom`])];function jV(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"endcaps"/"styles", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function MV(e){let t=jV(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function NV(e,t,n,r,i){let a=pV(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return X(e,t,`${MV(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||X(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function PV(e){let t=mV(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>dV(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function FV(e){let t=mV(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){X(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){X(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){X(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){X(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){X(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}X(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${J(o)}`)}}}function IV(e){let t=mV(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){X(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${fb(o)}`);return}let c=o;if(c.length<2){X(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){X(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){X(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){X(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function LV(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){X(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${J(r[n])}`);return}return!0}}}function RV(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=sb(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){X(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){X(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function zV(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){X(e,`${t}.${n}`,`relation must be "before" or "after", got ${J(i)}`);return}return i}}}function BV(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){X(e,`${t}.${n}`,`${n} must be an integer, got ${J(i)}`);return}return i}}}function VV(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const HV=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),UV=`plugin.json5`,WV=/^[a-z][a-z0-9_]*$/;function GV(e,t){let n=E.basename(E.dirname(e));return WV.test(n)?{path:e,scope:t,name:n}:{path:e,scope:t,name:void 0}}function KV(e){return`${e}.data`}function qV(e){return`${e}.json`}function JV(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:YV(e)}}}function YV(e){return e instanceof ib?e.issues.map(e=>e.path===``||e.message.includes(e.path)?e.message:`${e.path}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}function XV(e,t,n,r){return e.map(e=>GV(NN(E.dirname(t),e,r),n))}function ZV(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=n.path,o=n.name===void 0?void 0:FS(n),s=(t,r)=>{let i=new Map(e.rendering);return o!==void 0&&r!==e.config&&i.delete(o),{...e,config:r,rendering:i,dropped:[...e.dropped,{...n,reason:t}]}};if(E.basename(a)!==`plugin.json5`){let t=`a plugin is a folder holding its ${UV}, and the folder's name is the plugin's: move this file to <dir>/<name>/${UV} and list that`;return s(t,o===void 0?e.config:$V(QV(e.config,o),o,{...n,reason:t}))}if(n.name===void 0||o===void 0)return s(`its folder "${E.basename(E.dirname(a))}" is not a plugin name (one matching ${WV}: it prefixes every name the plugin declares)`,e.config);let c=i.get(o);if(c!==void 0)return s(`plugin "${n.name}" is already listed, from ${c}`,e.config);i.set(o,a);let u=QV(e.config,o),d=JV(()=>{let i=l.readFileSync(a,`utf-8`),s=Tz(aH(a,n,{source:i,json:ua.default.parse(i)},t),u);return bH(a,o,s),r(s,o,u!==e.config),s});if(d.ok)return{...e,config:d.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[o,n]])};let f={...n,reason:d.reason};return s(d.reason,$V(u,o,f))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function QV(e,t){let n=IS(t),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n(e)));return[e.variables,e.segments,e.helpers,e.actions].some(e=>Object.keys(e).some(n))?{...e,variables:r(e.variables),segments:r(e.segments),helpers:r(e.helpers),actions:r(e.actions)}:e}function $V(e,t,n){return{...e,variables:{...e.variables,[t]:{kind:`dropped`,reason:VV(n),definition:n.path}}}}function eH(e){let t=Object.entries(e.variables).flatMap(([e,t])=>t.kind===`dropped`?[{ns:e,definition:t.definition,notice:t.reason}]:[]);return e=>t.find(({ns:t})=>IS(t)(e))}function tH(e,t){let n=eH(e.config),r=[...e.rendering.keys()].map(IS),i=[...t,...e.dropped].filter(e=>e.name===void 0);return e=>{let t=RS(e);if(t===void 0)return[];let a=n(e);return a===void 0?r.some(t=>t(e))?[]:i.filter(e=>e.scope===t).map(e=>({definition:e.path,notice:VV(e)})):[{definition:a.definition,notice:a.notice}]}}function nH(e,t,n){let r=mS(e.presets).flatMap(t=>[...Fy(_S(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),i=[...new Set([...r.map(e=>e.name),...n,...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),a=Object.fromEntries(i.map(({name:e,cause:t})=>[e,rH(e,t.map(e=>e.notice),r.filter(t=>t.name===e))])),o=eH(e),s=Object.values(e.variables).some(e=>e.kind===`dropped`),c=s?Object.values(e.segments).flatMap(e=>[...lH.flatMap(t=>e[t]===void 0?[]:[e[t]]),...Object.values(e.partials??{})]):[],l=s?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],u=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:o(e);return n===void 0?[]:[[e,n]]}),d=u([...c.flatMap(t=>aC(t,e.helpers).map(e=>e.name)),...l],e.actions),f=u(c.flatMap(t=>[...fC(t,e.helpers)]),e.helpers),p=Object.entries(e.actions).flatMap(([t,n])=>{if(!(`run`in n))return[];let r=new Map(u(n.refreshes,e.variables));return r.size===0?[]:[{name:t,action:{...n,refreshes:n.refreshes.filter(e=>!r.has(e))},causes:[...r.values()]}]}),m=new Set([...i.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...d,...f].map(([,e])=>e.definition),...p.flatMap(({causes:e})=>e.map(e=>e.definition))]);return{config:{...e,segments:{...e.segments,...a},actions:{...e.actions,...Object.fromEntries(p.map(({name:e,action:t})=>[e,t])),...Object.fromEntries(d.map(([e,{ns:t}])=>[e,{copy:`{{ .${t} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(f.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:m}}function rH(e,t,n){let r=`⚠ ${e}: ${t.join(`; `)}`,i=new Map;for(let e of n)for(let[t,n]of Object.entries(e.settings??{})){let e=i.get(t);i.set(t,e===void 0?[n]:[...e,n])}let a=Object.fromEntries([...i].map(([e,t])=>[e,iH(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function iH(e,t){let[n]=t,r=t.filter(e=>typeof e==`number`);return typeof n==`boolean`?{label:e,domain:`bool`,default:n}:typeof n==`number`?{label:e,domain:{min:Math.min(...r),max:Math.max(...r),step:1},default:n}:{label:e,domain:[...new Set(t.map(String))],default:n}}function aH(e,t,{source:n,json:r},{checkout:i,home:a}){let o=FS(t),s=[],c=()=>{throw new ib(e,s)};if(!db(r))return s.push({path:``,message:`a plugin definition must be an object, got ${fb(r)}`}),c();for(let t of Object.keys(r))HV.has(t)||s.push({path:t,message:t===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${E.basename(E.dirname(e))}") — remove "plugin"`:`a plugin definition may not declare "${t}". Expected only: ${[...HV].join(`, `)}`});let u=r.data===void 0?void 0:CH(r.data,e,i,a,s),d=r.sources===void 0?{}:yH(r.sources,e,s);if(s.length>0)return c();let f={source:n,issues:s,allowedPalettes:new Set(qv()),groups:[],unplaced:[],inherited:[]},p=u===void 0?{}:Kz(f,`data`,{[KV(o)]:{kind:`file`,path:u,parse:{json:!0},cache:{watch_file:u},default:{}}}),m=Kz(f,`variables`,r.variables);for(let[e,t]of[[`variables`,Object.keys(m)],[`sources`,Object.keys(d)]])t.includes(`data`)&&s.push({path:`${e}.data`,message:`"data" names the plugin's data file (.${KV(o)}), declared by the definition's own "data" key: give this ${e===`sources`?`source`:`variable`} another name`});for(let e of Object.keys(d))Object.hasOwn(m,e)&&s.push({path:`sources.${e}`,message:`source "${e}" and variable "${e}" are one name (.${o}.${e}): give one of them another name`});let h={variables:{...p,...fH(o,d),...fH(o,Object.fromEntries(Object.entries(m).map(([e,t])=>[e,mH(o,t)])))},segments:fH(o,hH(o,IB(f,r.segments,new Set))),helpers:fH(o,qB(f,r.helpers)),actions:fH(o,gH(o,JB(f,r.actions,{dir:l.realpathSync(E.dirname(e))})))};s.push(...uH(h,t));let g=oH(o,h);for(let[e,t]of dH(g))try{eN.parse(t)}catch(t){s.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return s.length>0&&c(),g}function oH(e,t){let n=t=>mC(t,LS,e),r=t=>IS(`self`)(t)?`${e}${t.slice(4)}`:t,i=(e,t)=>Object.fromEntries(Object.entries(e??{}).map(([e,n])=>[e,t(n)]));return{...t,variables:i(t.variables,e=>sH(Uy(e,n),r)),segments:i(t.segments,e=>({...e,...Object.fromEntries(lH.flatMap(t=>e[t]===void 0?[]:[[t,n(e[t])]])),...e.partials!==void 0&&{partials:i(e.partials,n)},...e.vars!==void 0&&{vars:i(e.vars,e=>sH(Uy(e,n),r))}})),helpers:i(t.helpers,n),actions:i(t.actions,e=>cH(MS(e,n),r))}}function sH(e,t){return Hy(e)&&`depends_on`in e.cache?{...e,cache:{depends_on:e.cache.depends_on.map(t)}}:e}function cH(e,t){let n=`segments.`,r={...e};`do`in e&&(r.do=e.do.map(e=>t(e,`do`)));for(let n of[`removeSegment`,`insertSegment`,`anchor`])n in e&&(r[n]=t(e[n],n));return`persist`in e&&e.persist.startsWith(n)&&(r.persist=n+t(e.persist.slice(9),`persist`)),r}const lH=[`template`,`bg`,`fg`,`when`];function uH(e,t){let n=e.helpers??{},r=PS.filter(e=>e!==t.scope).map(e=>({scope:e,ns:FS({scope:e,name:t.name})})),i=new Map,a=(e,n,a)=>{let o=r.find(({ns:e})=>IS(e)(n));if(o===void 0)return;let s=a?`.`:``;i.set(`${e}\0${n}`,{path:e,message:`${e} names ${s}${n}, this plugin under "${o.scope}", but it loads as ${FS(t)}: a plugin names itself without its scope — write ${s}${LS}${n.slice(o.ns.length)}`})},o=[...[...dH(e)].filter(([e])=>!e.startsWith(`helpers.`)),...Object.entries(n).map(([e,t])=>[`helpers.${e}`,t])];for(let[e,t]of o){for(let[r,i]of tC(t,n))i===null&&a(e,r,!0);for(let{name:r,via:i}of aC(t,n))i===null&&a(e,r,!1);for(let n of fC(t,{}))a(e,n,!1)}for(let[t,n]of Object.entries(e.actions??{}))cH(n,(e,n)=>(a(`actions.${t}.${n}`,e,!1),e));let s=[...Object.entries(e.variables??{}).map(([e,t])=>[`variables.${e}`,t]),...Object.entries(e.segments??{}).flatMap(([e,t])=>Object.entries(t.vars??{}).map(([t,n])=>[`segments.${e}.vars.${t}`,n]))];for(let[e,t]of s)if(Hy(t)&&`depends_on`in t.cache)for(let n of t.cache.depends_on)a(`${e}.cache.depends_on`,n,!1);return[...i.values()]}function*dH(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of Wy(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of lH){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[e,r]of Object.entries(n.partials??{}))yield[`segments.${t}.partials.${e}`,r];for(let[e,r]of Object.entries(n.vars??{}))for(let[n,i]of Wy(r))yield[`segments.${t}.vars.${e}.${n}`,i]}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))for(let[e,r]of jS(n))yield[`actions.${t}.${e}`,r]}function fH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,n]))}function pH(e,t){return`${e}.${t}`}function mH(e,t){return t.kind===`state`?{...t,key:pH(e,t.key)}:t}function hH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.vars===void 0?n:{...n,vars:Object.fromEntries(Object.entries(n.vars).map(([t,n])=>[t,mH(e,n)]))}]))}function gH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:pH(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>pH(e,t))}:n]))}const _H=WV,vH={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function yH(e,t,n){if(!db(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${fb(e)}`}),{};let r=E.join(l.realpathSync(E.dirname(t)),`session`),i=JSON.stringify(vH),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!_H.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${_H}: it is the last segment of .<scope>.<plugin>.${t})`});continue}let s=SH(o,vH,e);for(let{field:e,is:t}of s)n.push({path:e,message:`${e} ${t}: what is built is a source ${i} — a session's JSON file in the plugin's managed storage, re-read when it changes`});s.length===0&&(a[t]={kind:`source`,storage:r})}return a}function bH(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=xH(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=IS(t),a=[...r].filter(([,e])=>e.length>1&&e.some(i)).map(([e,n])=>({path:`sources.${n.find(i).slice(`${t}.`.length)}`,message:`sources ${n.map(e=>`.${e}`).join(` and `)} read the same file, ${e}: a session's file is one document, read by one source`}));if(a.length>0)throw new ib(e,a)}function xH(e){return E.join(e.storage,qV(`<session id>`))}function SH(e,t,n){return!db(t)||!db(e)?JSON.stringify(e)===JSON.stringify(t)?[]:[{field:n,is:`is ${JSON.stringify(e)}`}]:[...new Set([...Object.keys(t),...Object.keys(e)])].flatMap(r=>{let i=`${n}.${r}`;return Object.hasOwn(t,r)?Object.hasOwn(e,r)?SH(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function CH(e,t,n,r,i){if(typeof e==`string`&&e!==``)return NN(E.dirname(t),e,r);if(db(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(E.isAbsolute(t)||t.startsWith(`~`)||E.normalize(t).split(E.sep)[0]===`..`){i.push({path:`data.checkout`,message:`data.checkout "${t}" must be a path inside the checkout, relative to its root (like ".lit/statusline.json"): no absolute path, "~" or ".."`});return}if(n===null){i.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return E.resolve(n.root,t)}if(db(e)&&`project`in e){i.push({path:`data.project`,message:`data: { project } is now data: { checkout }: the same path, relative to the root of the git checkout the session works in (a linked worktree is its own checkout)`});return}i.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { checkout: "<path>" } relative to the root of the session's checkout`})}function wH(e,t){let n=[...[...e.dataDirs].reverse().map(e=>E.join(e,`cc-candybar`,`plugins`)),TH(e)];return[...n.filter((e,t)=>n.lastIndexOf(e)===t).map(e=>({dir:e,scope:`plugins`})),...t===null?[]:[{dir:E.join(t,EH),scope:`repo`}]]}function TH(e){return E.join(e.dataHome,`cc-candybar`,`plugins`)}const EH=E.join(`.cc-candybar`,`plugins`);function DH(e,t){let n=wH(e,t),r=new Map,i=[],a=[];for(let{dir:e,scope:t}of n){let n=OH(e);if(`error`in n){i.push(n);continue}for(let i of n.folders){let n=GV(E.join(e,i,UV),t),a=`${t}\0${i}`;r.delete(a),r.set(a,n)}for(let r of n.files)a.push({path:E.join(e,r),scope:t,name:void 0,reason:`a plugin is a folder holding its ${UV}: move this file to ${E.join(e,`<name>`,UV)}`})}return{roots:n.map(e=>e.dir),definitions:[...r.values()],unchecked:i,strays:a}}function OH(e){try{let t=l.readdirSync(e,{withFileTypes:!0}).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),n=t=>t.isDirectory()||kH(e,t);return{folders:t.filter(n).map(e=>e.name),files:t.filter(e=>!n(e)).map(e=>e.name)}}catch(t){return t.code===`ENOENT`?{folders:[],files:[]}:{path:e,error:t.message}}}function kH(e,t){if(!t.isSymbolicLink())return!1;try{return l.statSync(E.join(e,t.name)).isDirectory()}catch{return!0}}const AH=[`approved`,`declined`];function jH(e){return e.link.kind===`linked`?e.link.main:e.dir}const MH=(e,t)=>Object.hasOwn(e,t)?e[t]:null;function NH(e,t){let n=jH(t);if(e.kind===`failed`)return{standing:`unread`,under:n};let r=MH(e.value,n),i=MH(e.value,t.dir);return r===null?i===null?{standing:`awaiting`,under:n}:{standing:i,under:t.dir}:{standing:i===null||i===r?r:`awaiting`,under:n}}function PH(e,t,n){let r=[...new Map([...t,...n?.ships?[n]:[]].map(e=>[e.dir,e])).values()],i=r.map(t=>({dir:t.dir,...NH(e,t)})),a=e=>i.filter(t=>t.standing===e),o=e=>[...new Set(a(e).map(e=>e.under))];return{plugins:n!==null&&NH(e,n).standing===`approved`?n.path:null,approved:a(`approved`).map(e=>e.dir),awaiting:o(`awaiting`),declined:o(`declined`),unproven:r.flatMap(e=>e.link.kind===`unproven`?[{dir:e.dir,reason:e.link.reason}]:[]),unread:e.kind===`failed`?e.reason:null}}function FH(e,t,n,r){if(e[t]===n&&r.length===0)return e;let i=Object.entries(e).filter(([e])=>!r.includes(e));return{...Object.fromEntries(i),[t]:n}}function IH(e){if(typeof e!=`object`||!e||Array.isArray(e))return{kind:`failed`,reason:`is not an object`};for(let[t,n]of Object.entries(e))if(!AH.includes(n))return{kind:`failed`,reason:`answers ${JSON.stringify(t)} ${JSON.stringify(n)}, not ${AH.join(` or `)}`};return{kind:`ok`,value:e}}function LH(e){return e.unread===null?null:`Repository config answers could not be read: ${e.unread} — no repository's config runs until they can be`}function RH(e){let t=LH(e);return[...t===null?[]:[t],...e.awaiting.map(e=>`awaiting approval: ${e} — its cc-candybar config runs once it is approved in the bar`),...e.declined.map(e=>`declined: ${e} — its cc-candybar config does not run`),...e.unproven.map(e=>`not proven a worktree: ${e.dir} — it answers for itself, because ${e.reason}`)]}const zH=[`json5`,`json`];function BH(e,t,n,r){if(r!==void 0)return[r];let i=n??process.cwd();return[...new Set([...t?zH.map(e=>E.join(t,`${VH}.${e}`)):[],...zH.map(e=>E.join(i,`${VH}.${e}`)),...zH.map(t=>`${HH(e)}.${t}`)])]}const VH=`.cc-candybar`;function HH(e){return E.join(e.configHome,`cc-candybar`,`config`)}function UH(e){return{path:e,scope:`plugins`}}function WH(e,t,n,r,i){let a=[],o=new Map;for(let t of BH(e,n,r,i)){let n=wz(t);if(n===`absent`)continue;if(n!==`present`){a.push(n);continue}let r=l.realpathSync.native(E.dirname(t)),s=E.join(r,E.basename(t).replace(/\.(json5|json)$/,``));o.has(s)||o.set(s,{file:t,repo:i!==void 0||GH(e,t)?null:{dir:r,link:uc(r)}})}let s=[...o.values()],c=PH(t,s.flatMap(e=>e.repo===null?[]:[e.repo]),KH(n)),u=s.filter(e=>e.repo===null||c.approved.includes(e.repo.dir)).reverse().map(e=>({path:e.file,scope:e.repo===null?`plugins`:`repo`}));if(i===void 0)return{kind:`chain`,layers:u,home:qH(e,u),unchecked:a,repos:c};let[d]=a,f=i;return u.length>0?{kind:`chain`,layers:u,home:f,unchecked:a,repos:c}:d===void 0?{kind:`missing`,path:i,home:f,repos:c}:{kind:`unreadable`,...d,home:f,repos:c}}function GH(e,t){return zH.some(n=>t===`${HH(e)}.${n}`)}function KH(e){if(e===void 0||wz(e)!==`present`)return null;let t=OH(E.join(e,EH)),n=l.realpathSync.native(e);return{dir:n,link:uc(n),path:e,ships:!(`error`in t)&&t.folders.length>0}}function qH(e,t){return t.find(t=>GH(e,t.path))?.path??`${HH(e)}.${zH[0]}`}function JH(e,t,n,r,i){let a=WH(e,t,n,r,i),o=a.kind===`chain`?a.layers:[];return{path:a.home,above:o.filter(e=>e.path!==a.home),repo:a.repos.plugins,cwd:r??null,locs:e}}function YH(e){return XH(e).join(`
|
|
180
|
+
`)||null}function XH(e){switch(e.kind){case`chain`:return e.unchecked.map(e=>`Config location could not be checked: ${e.path} — ${e.error}`);case`missing`:return[`Config file not found: ${e.path} — rendering the bundled default until it appears`];case`unreadable`:return[`Config file could not be read: ${e.path} — ${e.error} — rendering the bundled default until it can be`]}}function ZH(e,t,n){let r=BH(e,t,n).filter(e=>wz(e)===`present`),i=new Map;for(let e of r){let t=E.dirname(e),n=E.basename(e).replace(/\.(json5|json)$/,``),r=E.join(t,n);i.has(r)||i.set(r,[]),i.get(r).push(e)}let a=[...i.values()].filter(e=>e.length>1);return a.length===0?null:`config-extension collision: ${a.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function QH(e,t,n,r){let i=E.join(e,t),a=()=>{let e;try{e=l.readFileSync(i,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${i}: ${e.message}`}}let t;try{t=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${i} is not JSON: ${e.message}`}}let a=r(t);return a.kind===`ok`?a:{kind:`failed`,reason:`${i} ${a.reason}`}};return{read:a,update:e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return n!==t.value&&sn(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const $H={level:`error`,glyph:`⚠`,colors:tP},eU={level:`warning`,glyph:`⚠`,colors:nP},tU={level:`warning`,glyph:`⬆`,colors:nP},nU={level:`warning`,glyph:`🔒`,colors:nP},rU={level:`warning`,glyph:`🧪`,colors:nP};function iU(e,t){return{text:cP(e),link:t}}function aU(e,t,n,r,i){let a=new Set,o=(e,t)=>{let n=oU(e,t);for(let e of n)a.add(e);return n},s=[...n.flatMap(e=>o(e,$H)),...r,...i.flatMap(e=>o(e,eU))],c=sU(s);return s.map((n,r)=>a.has(n)?{...n,lines:[[iU(n.lines[0][0].text,cU(e,t,c[r],r+1))],...n.lines.slice(1)]}:n)}function oU({about:e,text:t,copy:n},r){let[i,...a]=t.split(/\r\n|\r|\n/).map(e=>iU(e,null)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:r,about:e,message:t,copy:n,lines:[i,...a]}]}function sU(e){return fU(e).map(e=>String(e*uU+1))}function cU(e,t,n,r){return ea([{verb:qi,args:[e,t,n]}],`copy diagnostic ${r}`)}function lU(e){return e.length===0?null:e.some(e=>e.severity.level===`error`)?`error`:`warning`}const uU=4096;function dU(e){let t=oe(`sha256`).update(`${e.severity.level}\0${e.severity.glyph}\0${e.about}`).digest(`hex`);return Number.parseInt(t.slice(0,9),16)%2**32}function fU(e){let t=new Map;return e.map(e=>{let n=dU(e),r=t.get(n)??0;return t.set(n,r+1),n*256+Math.min(r,255)})}function pU(e,t,n){return String(fU(e)[t]*uU+n+1)}const mU={error:tP,warning:nP};function hU(e){let t=lU(e),n=e.length,r=mU[t??`warning`];return{label:t===null?``:`⚠ ${n>9?`9+`:n}`,fg:r.fg,bg:r.bg,open:e.length===0?`0`:pU(e,0,0)}}function gU(e,t){let n=Number(e)-1,r=fU(t).indexOf(Math.floor(n/uU));return e===null||r===-1?null:{index:r+1,page:n%uU}}function _U(e,t){return Math.min(20,e??20,...t)}function vU(e,t,n,r,i){let{index:a}=t,o=e[a-1],s=xU(i),c=wU(o,s,[]),l=new U({bgcolor:o.severity.colors.bg,color:o.severity.colors.fg}),u=(e,t)=>SU(e,t===null?l:l.withLink(t)),d=(t,r)=>r===null?u(` `,null):u(t,bU(n,pU(e,r.index-1,r.page),`show diagnostic ${r.index} of ${e.length} page ${r.page+1}`)),f=(t,i)=>{let o=i>0?{index:a,page:i-1}:a>1?{index:a-1,page:0}:null,c=i<t-1?{index:a,page:i+1}:a<e.length?{index:a+1,page:0}:null,l=e.length>1||t>1,f=t>1?`[${a}/${e.length} ${i+1}/${t}]`:`[${a}/${e.length}]`;return CU([u(`✕`,bU(n,`0`)),...l?[d(`‹`,o)]:[],u(f,null),...l?[d(`›`,c)]:[],u(`⧉ copy`,cU(n,r,pU(e,a-1,0),a))],s)},p=1;for(;;){let e=Math.max(1,i.rows-p),n=Math.min(uU,Math.ceil(c.length/e)),r=Math.min(t.page,n-1),a=f(n,r);if(a.length>p){p=a.length;continue}let o=c.slice(r*e,(r+1)*e),l=c.length-(r+1)*e,d=r===n-1&&l>0?[...o.slice(0,-1),...CU([u(`… ${l+1} more rows: ⧉ copy has them all`,null)],{...s,wrap:!1})]:o;return[...a,...d]}}function yU(e,t,n,r){let{label:i,fg:a,bg:o,open:s}=hU(t),c=i===``?[]:[SU(i,new U({bgcolor:o,color:a}).withLink(bU(n,s)))];return wU(e,xU(r),c)}function bU(e,t,n){return ea([{verb:Si,args:[e,yi,t]}],n)}function xU(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,colorCompatibility:e.colorCompatibility}}const SU=(e,t)=>new K(`${e} `,{style:t,end:``,overflow:`ignore`}),CU=(e,t)=>WP(e,t).lines.map(e=>({kind:`diagnostic`,runs:e}));function wU(e,t,n){let r=new U({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),i=e=>e===null?r:r.withLink(e),a=Uc(Math.max(2,t.width-1));return e.lines.flatMap((o,s)=>{let c=SU(s===0?e.severity.glyph:` `,r),l=o.flatMap(e=>e.text.split(` `).flatMap(e=>Jc(e,a)).map(t=>SU(t,i(e.link)))),u=s===0?n:[];return CU([c,...l,...u],t)})}const TU=`repo-configs.json`;function EU(e){return E.join(e,`repo-configs`)}function DU(e){return E.join(EU(e),TU)}const OU=e=>{let t=QH(EU(e),TU,{},IH),n=QH(e,TU,{},IH),r=()=>l.existsSync(DU(e));return{read:()=>(r()?t:n).read(),update:e=>{if(r())return t.update(e);let i=n.read();return i.kind===`failed`?i:t.update(()=>e(i.value))}}};function kU(e,t,n){let r={superseded:[],absent:[],unchecked:[]},i=e.update(e=>{let i=Object.keys(e).filter(e=>e!==t).map(e=>({d:e,found:wz(e)}));return r={superseded:i.filter(({d:e,found:n})=>n===`present`&&jH({dir:e,link:uc(e)})===t).map(({d:e})=>e),absent:i.filter(({found:e})=>e===`absent`).map(({d:e})=>e),unchecked:i.flatMap(({found:e})=>typeof e==`object`?[e]:[])},FH(e,t,n,r.superseded)});return i.kind===`failed`?i:F(r)}function AU(e,t,n){return{sessionId:e,action:Ki,declaration:t,evaluated:n}}function jU(e,t,n){return e.awaiting.map(e=>{let r=`a cc-candybar config for ${e} — run it?`,i=AH.map(r=>iU(`[${r===`approved`?`approve`:`decline`}]`,ea([{verb:Ki,args:[t,e,r,n.sign(AU(t,e,r))]}]))),a=[iU(r,null),...i];return{severity:nU,about:`repo-question\0${e}`,message:r,copy:r,lines:[a]}})}const MU=`#/definitions/LayoutNode`,NU={kind:`container`,direction:`vertical`,children:[]};function PU(e){return{required:!0,json:{const:e},parse:()=>e}}function FU(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${J(i)}`,line:q(e.source,[`root`])}),``)}}}function IU(){return{required:!0,json:{enum:[...ky]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&ky.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${ky.join(`, `)} (got ${JSON.stringify(i)})`,line:q(e.source,[`root`])}),`vertical`)}}}function LU(e){return{required:!0,json:{type:`array`,items:{$ref:MU}},parse:(t,n,r,i)=>{let a=i[r];return Array.isArray(a)?a.map((i,a)=>e(t,`${n}.${r}[${a}]`,i)):(t.issues.push({path:`${n}.${r}`,message:`a container must have a "children" array of layout nodes, got ${fb(a)}`,line:q(t.source,[`root`])}),[])}}}const RU={noun:`layout-node key`,fields:{kind:PU(`segment`),name:FU(),when:wb(),id:NB(),settings:PB()}},zU=()=>Mb(tv),BU={noun:`layout-node key`,fields:{kind:PU(`container`),direction:IU(),children:LU(Sb(()=>GU)),when:wb(),distribution:zU()}};function VU(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${J(i)}`,line:q(e.source,[...t.split(`.`),n])}),``)}}}const HU={noun:`layout-node key`,fields:{seg:VU(),when:wb(),id:NB(),settings:PB()}},UU={noun:`layout-node key`,fields:{h:LU(Sb(()=>GU)),when:wb(),distribution:zU()}},WU={noun:`layout-node key`,fields:{v:LU(Sb(()=>GU)),when:wb(),distribution:zU()}},GU=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:q(e.source,[`root`])}),NU):{kind:`segment`,name:n};if(!db(n))return e.issues.push({path:t,message:`a layout node must be a string (segment name) or an object with "kind" / "seg" / "h" / "v", got ${fb(n)}`,line:q(e.source,[`root`])}),NU;if(n.kind===`container`)return pb(e,BU,t,n)??NU;if(n.kind===`segment`)return pb(e,RU,t,n)??NU;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
181
181
|
Old: { kind: "cells", segments: ["seg1", "seg2"] }
|
|
182
|
-
New: { h: ["seg1", "seg2"] }`,line:q(e.source,[`root`])}),PU;if(n.kind===`group`){let r=pb(e,tW,t,n);return r===null?PU:(e.groups.push({name:r.name,label:r.label,...r.open!==void 0&&{open:r.open},...r.direction!==void 0&&{direction:r.direction},...r.key!==void 0&&{key:r.key},...r.bg!==void 0&&{bg:r.bg},...r.fg!==void 0&&{fg:r.fg},...r.when!==void 0&&{when:r.when},path:t}),rW(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:q(e.source,[`root`])}),PU}if(a){let r=pb(e,UU,t,n);return r===null?PU:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when},...r.id!==void 0&&{id:r.id},...r.settings!==void 0&&{settings:r.settings}}}if(r){let r=pb(e,WU,t,n);return r===null?PU:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}if(i){let r=pb(e,GU,t,n);return r===null?PU:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:q(e.source,[`root`])}),PU};function qU(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Zx.source},additionalProperties:{$ref:NU}},parse:(e,t,n,r)=>{let i=r[n];if(!db(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${fb(i)}`,line:q(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!Zx.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:q(e.source,[...t.split(`.`),n,r])});continue}a[r]=KU(e,`${t}.${n}.${r}`,o)}return a}}}const JU={noun:`root key`,fields:{rows:qU(),when:wb(),distribution:BU()}};function YU(e,t,n){return db(n)&&`rows`in n?pb(e,JU,t,n)??{rows:{}}:KU(e,t,n)}const XU={noun:`insert key`,fields:{seg:HU(),id:PB(),before:wb(),after:wb()}};function ZU(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=pb(e,XU,i,t);if(a===null)return[];let o=[`before`,`after`].filter(e=>a[e]!==void 0);if(o.length!==1)return e.issues.push({path:i,message:`an insert cell names exactly one of "before" or "after" (the placement id it sits beside), got ${o.length===0?`neither`:`both`}`,line:q(e.source,i.split(`.`))}),[];if(hi(a.seg))return e.issues.push({path:`${i}.seg`,message:`an insert cell places a segment, and "${a.seg}" is the bar's own chrome — name a segment instead`,line:q(e.source,[...i.split(`.`),`seg`])}),[];let s=o[0],c=a[s];return hi(c)?(e.issues.push({path:`${i}.${s}`,message:`an insert cell sits beside a placement, and "${c}" is the bar's own chrome — anchor on a placement id instead`,line:q(e.source,[...i.split(`.`),s])}),[]):[{seg:a.seg,...a.id!==void 0&&{id:a.id},anchor:c,relation:s,by:{file:n,entry:i}}]}):(e.issues.push({path:`insert`,message:`"insert" must be a list of cells like { seg: "name", after: "placement" }, got ${fb(t)}`,line:q(e.source,[`insert`])}),[])}function QU(){return{required:!0,json:{type:`string`,pattern:Zx.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Zx.test(i)||i===`closed`){e.issues.push({path:`${t}.${n}`,message:`a group "name" must be an identifier (letters, digits, _; not starting with a digit) and not the reserved "${Yr}", got ${J(i)}`,line:q(e.source,[`root`])});return}return i}}}function $U(){return{required:!1,json:{type:`string`,minLength:1},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`string`||i===``||i.includes(`/`)){e.issues.push({path:`${t}.${n}`,message:`a group "key" must be a non-empty, slash-free SessionState key, got ${J(i)}`,line:q(e.source,[`root`])});return}return i}}}}function eW(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=sb(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:q(e.source,[...t.split(`.`),n])});return}return i}}}}const tW={noun:`layout-node key`,fields:{kind:FU(`group`),name:QU(),label:eW(),open:Tb(),direction:Mb(ky),key:$U(),bg:wb(),fg:wb(),when:wb(),distribution:BU(),children:RU(Sb(()=>KU))}};function nW(e){return e.key??`groups.`+e.name}function rW(e){let t=li+e.name;return ti(t,{variable:t,key:nW(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function iW(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,[`root`])})}function aW(e,t){nN(e,t,li,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&iW(e,t.path,`duplicate group name "${t.name}" — group names must be unique (they name the synthesized state var, action, and toggle segment)`),r.add(t.name);for(let t of n)for(let r of n)t!==r&&t.path.startsWith(`${r.path}.`)&&nW(t)===nW(r)&&iW(e,t.path,`group "${t.name}" shares key "${nW(t)}" with its ancestor group "${r.name}" — a shared key holds ONE open group, so an ancestor and a descendant cannot share one. Sibling accordions share a key; nested groups use distinct keys.`);let i=new Map;for(let t of n){let n=nW(t);if(i.has(n)||i.set(n,Yr),t.open===!0){let r=i.get(n);r!==`closed`&&iW(e,t.path,`groups "${r}" and "${t.name}" share key "${n}" and both declare open: true — a shared key holds one open group; pick one`),i.set(n,t.name)}}let a={},o={},s={};for(let e of n){let t=li+e.name,r=nW(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=si(r,i.get(r)),o[t]=P(r,e.name),s[t]={template:ii(t,`${l}${e.label} ▸`,`${l}${e.label} ▾`),...e.bg!==void 0&&{bg:e.bg},...e.fg!==void 0&&{fg:e.fg}}}t.variables={...t.variables??{},...a},t.actions={...t.actions??{},...o},t.segments={...t.segments??{},...s}}const oW=`menu`,sW=`a menu binds its trigger text the way a cycle action binds a display — write {{ menu "applyTheme" "▸" "▾" }} (one per state) or {{ menu "insertHere" "+" }} (one static display for both), with the rare knobs in ONE trailing dict: {{ menu "applyTheme" "▸" "▾" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key). The renderer no longer appends ▸/▾ of its own (candybar-settings-ui-aok.4), and the older positional tail ("pageAction" closeOnPick paged "key") was removed — the page cursor is synthesized from the menu's identity`,cW=e=>e.kind===`call`&&e.name===`dict`,lW=e=>e.kind===`literal`&&typeof e.value!=`object`,uW=e=>Qr(``,e,2)===void 0;function dW(e){let t=e=>({kind:`issue`,message:e}),[n,...r]=e.argExprs;if(n===void 0)return t(`with no arguments — it takes an apply-action name and its trigger text (e.g. {{ menu "applyTheme" "▸" "▾" }})`);if(n.kind!==`literal`||typeof n.value!=`string`)return t(`whose apply action is not a string literal — a menu's identity is its apply-action name, which must be a literal so it can be gated at load (e.g. {{ menu "applyTheme" "▸" "▾" }})`);let i=r[r.length-1],a=i!==void 0&&cW(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(cW))return t(`whose options (dict …) is not its last argument — ${sW}`);if(i!==void 0&&a===void 0&&!lW(i)&&uW(o.length-1))return t(`whose last argument is neither a literal nor a literal (dict …) — the renderer tells a display from the options dict by the value it evaluates to, so this call could be read as ${o.length} displays or as ${o.length-1} plus options, and both are legal. Make the options explicit as a trailing (dict …) — {{ menu "${n.value}" (printf "…") (printf "…") (dict) }} binds dynamic displays unambiguously — or bind the trigger text as literals`);let s=Qr(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${sW}`);let c=a===void 0?{}:ED(a);if(c===null)return t(`whose options (dict …) is not fully literal — every option value must be a literal so the menu can be gated at load (a dynamic entry like (dict "key" .x) cannot)`);let l;try{l=Xj(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=tN(u);if(e!==void 0)return t(`whose accordion key "${u}" lands in the reserved "${e}" namespace — a key is collapsed to an identifier (${JSON.stringify(u)} becomes "${Gj(u)}"), so it would share one open-state key with the synthesized accordion that owns that namespace instead of grouping only your own menus. Name the group without the reserved prefix`)}return{kind:`ok`,apply:n.value,options:l}}function fW(e){let t=FT({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===oW).map(dW)}catch{return`parse-failed`}}function pW(e,t){let n=fW(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:Wj(t,e.apply,e.options.key),member:Uj(e.apply)}]:[])}function mW(e){let t=FT({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(oW)}catch{return!1}}function hW(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,[`root`])})}function gW(e,t){nN(e,t,ui,`{{ menu }} helpers`),nN(e,t,di,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))mW(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:q(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n)){for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&mW(i)&&hW(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}for(let[n,i]of Object.entries(r.partials??{}))mW(i)&&e.issues.push({path:`segments.${t}.partials.${n}`,message:`segments.${t}.partials.${n} uses {{ menu }}, but a menu must live directly in a segment's "template" string — the synthesis pass that wires its state never follows a {{ template }} call into a partial. Inline the {{ menu }} call into the template itself.`,line:q(e.source,[`segments`,t,`partials`,n])})}if(t.root!==void 0)for(let n of Fy(iS(t.root)))typeof n.when==`string`&&mW(n.when)&&hW(e,`root`,`a layout node's "when" predicate uses {{ menu }} — a menu is only valid in a segment's "template", not a node predicate. Move it into a segment.`);for(let[t,{template:r}]of Object.entries(n)){if(r===void 0||!mW(r))continue;let n=fW(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:_W(r.apply);n!==void 0&&hW(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function _W(e){if(e===``)return`with an empty apply-action name — an empty member aliases the absent-state sentinel ("") so the menu would render open before any click. Name the apply action`;if(Uj(e)===`closed`)return`whose apply action is named "${Yr}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function vW(e,t){let n={},r={},i=new Map,a=new Set,o=(e,n)=>{let r=`segments.${e}`;a.has(`${r}\0${n}`)||(a.add(`${r}\0${n}`),t.push({path:r,message:n}))};for(let t of mS(e.presets)){let a=new Map,s=new Map;for(let c of Fy(_S(e,t).node)){if(c.kind!==`segment`)continue;let t=e.segments[c.name];if(t===void 0)continue;i.has(c.name)||i.set(c.name,fW(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=jy(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||_W(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=Uj(i),f=Wj(u,i,l.key),p=qj(f),m=l.key===void 0?`ind ${u} ${i}`:`key ${l.key}`,h=[f,p].find(e=>{let t=a.get(e);return t!==void 0&&t!==m});if(h!==void 0){o(c.name,`two {{ menu }} disclosures normalize to the same state key ("${h}") but were declared differently — distinct names that differ only by non-alphanumeric characters (e.g. "a-b" vs "a_b") collapse to one key and would silently share open-state. Rename so they don't collide.`);continue}a.set(f,m),a.set(p,m);let g=Kj(f,d),_=`${c.name}\0${e}`,v=s.get(g);if(v!==void 0&&v!==_){o(c.name,`two {{ menu }} disclosures resolve to the same identity ("${g}") — ${l.key===void 0?`a segment cannot contain two menus over the same apply action "${i}"`:`menus sharing key "${l.key}" must have distinct apply actions`}.`);continue}s.set(g,_),r[g]=P(f,d),n[f]=si(f,Yr),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}function yW(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const bW={noun:`style key`,fields:{hueShift:Db(),chromaScale:Db({min:0}),lightnessScale:Db(),lightnessShift:Db()}};function xW(e,t){if(!db(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${fb(t)}`,line:q(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:q(e.source,[`styles`,r])});continue}if(_y(r)){e.issues.push({path:`styles.${r}`,message:yW(`styles.${r}`,r,`globals.endcaps`),line:q(e.source,[`styles`,r])});continue}let t=pb(e,bW,`styles.${r}`,i);t!==null&&(n[r]={...au,...t})}return n}const SW={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:YU(e,`${t}.${n}`,r[n])},globals:{required:!1,json:NM(),parse:(e,t,n,r)=>r[n]===void 0?void 0:MM(e,`${t}.${n}`,r[n])}}};function CW(e,t){if(!db(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${fb(t)}`,line:q(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:q(e.source,[`presets`,r])});continue}let t=pb(e,SW,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function wW(e,t){let n=[...t].map(([e,t])=>[IS(e),t]);return t=>{if(UL(t)||Object.hasOwn(e,t))return{kind:`declared`};let r=n.find(([e])=>e(t));if(r!==void 0)return{kind:`plugin`,definition:r[1]};let i=RS(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function TW(e){return e.kind===`plugin`||e.kind===`missing`}function EW(e,t,n){let r=new Map,i=(e,t)=>{r.set(e,[...r.get(e)??[],t])},a=e=>eS(e)?Object.values(e.rows):[e],o=[e.root,...Object.values(e.presets).flatMap(e=>e.root===void 0?[]:[e.root])];for(let e of o.flatMap(a))for(let t of Fy(e))t.kind===`segment`&&i(jy(t),{seg:t.name});for(let e of t)i(e.id??e.seg,{seg:e.seg,anchor:e.anchor});let s=new Set,c=e=>n(e.seg).kind===`absent`||e.anchor!==void 0&&s.has(e.anchor);for(let e=!0;e;){e=!1;for(let[t,n]of r)!s.has(t)&&n.every(c)&&(s.add(t),e=!0)}return e=>s.has(e)}function DW(e){let t=0,n=wW(e.segments,new Map),r=e=>{let r=n(e).kind===`declared`;return r||(t+=1),r},i=e=>({...e,children:e.children.flatMap(e=>a(e))}),a=e=>e.kind===`container`?[i(e)]:r(e.name)?[Py(e,i)]:[],o=e=>a(e)[0]??OW,s=e=>({...e,rows:Object.fromEntries(Object.entries(e.rows).map(([e,t])=>[e,o(t)]))}),c=e=>eS(e)?s(e):o(e),l=e=>e.root===void 0?e:{...e,root:c(e.root)},u={...e,root:s(e.root),presets:Object.fromEntries(Object.entries(e.presets).map(([e,t])=>[e,l(t)]))};return t===0?e:u}const OW={kind:`container`,direction:`horizontal`,children:[]};function kW({names:e,helpers:t,actions:n}){let r=(e,t)=>{let i=Object.hasOwn(n,e)?n[e]:void 0;return i===void 0||t.has(e)?[]:(t.add(e),[...[...jS(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=XS(e=>{let i=cC(e,t)?Object.keys(n):aC(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]}),a=XS(n=>i(n).flatMap(n=>[...tC(n,t).keys()].map(t=>({path:t,reaches:_C(t,e)}))));return{ofTemplate:a,calls:XS(e=>new Set(i(e).flatMap(e=>[...uC(e,t)]))),ofVariable:t=>[...Wy(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...Hy(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function AW(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}const jW=new WeakMap;function MW(e){let t=jW.get(e);return t===void 0&&(t=kW({names:new Set([...gC(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),jW.set(e,t)),t}function NW(e,t){for(let n of t.reads.calls(e))if(t.clock.has(n))return`calls "${n}"`;for(let{reaches:n}of t.reads.ofTemplate(e))for(let e of n){let n=t.projections.get(e);if(n!==void 0)return`reads "${e}", which ${n}`}return null}const PW=new WeakMap;function FW(e){let t=PW.get(e);return t===void 0&&(t=LW(e),PW.set(e,t)),t}function IW(e){return FW(e).projections}function LW(e){let t=new Map(gC(e)),n=new Map,r={reads:MW(e),projections:n,clock:YA};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=AW(e,r),i=t===void 0?null:Lj(t);i&&n.set(e,`reads the draw's "${i}" (${Ij[i]})`)}let i=zW(e),a=new Map;for(let e=!0;e;){e=!1;for(let[i,a]of t){if(a.kind!==`template`||n.has(i))continue;let t=NW(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of Qv)if(!a.has(t))for(let n of i[t]){let i=NW(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=AW(r,i);if(t===void 0||n.has(r))continue;let o=zj(t),s=o===void 0?void 0:a.get(o);s!==void 0&&(n.set(r,`reads the ${o} rule, which ${s}`),e=!0)}}return r}function RW(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>Qv.flatMap(n=>{let r=t[n];return $v(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function zW(e){let t=RW(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function BW(e,t){return NW(e,FW(t))}function VW(e){return t=>NW(t,e)!==null}const HW={nested:e=>`${e} sets "distribution" on a container inside a row — the row's own container places every cell along it, through any { h } or { v } nested in it, so this one would place nothing. Set it on the row (the outermost horizontal container), or, on the bar, on the root, which places the rows.`,bar:e=>`${e} sets "distribution" on a vertical container none of whose children is a segment or a horizontal container — a bar row's hue is placed by the innermost vertical container it stacks through, so it would place nothing. Set it on that container, or on the row whose children are the cells (the horizontal container).`,band:e=>`${e} sets "distribution" on a vertical container in a disclosure body — a body's items are placed along their rows, never by which row they sit on, so it would place nothing. Set it on the row whose children are the items (the horizontal container), or give a group \`direction: 'horizontal'\`.`};function UW(e,t){let n=new Map;for(let e of Object.keys(t)){let t=Hj(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:q(e.source,[`presets`])})}function WW(e,t){let n=[[`root`,e.root],...Object.entries(e.presets??{}).map(([e,t])=>[`presets.${e}.root`,t.root])];for(let[e,r]of n)if(r!==void 0){for(let[n,i]of aS(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const GW=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${FS(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${KW(FS(r.definition),n)}${qW(t,n)}`:`${e} entry "${t}" does not match any declared segment${qW(t,n)}`;function KW(e,t){let n=Object.keys(t).filter(IS(e)).sort();return n.length===0?`no segments`:n.map(e=>{let n=Object.keys(t[e].settings??{});return`${e} (${n.length===0?`no settings`:`settings: ${n.join(`, `)}`})`}).join(`, `)}function qW(e,t){return jz(e)+zS(e,e=>Object.hasOwn(t,e))}function JW(e,t,n,r){let i=[[[`globals`],t.globals.style,`globals.endcaps`],[[`editGlobals`],t.editGlobals.style,`editGlobals.endcaps`],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style,`presets.${e}.globals.endcaps`]),...Object.entries(t.themeDefaults).map(([e,t])=>[[`themeDefaults`,e],t.style,`globals.endcaps`])];for(let[n,r,a]of i){if(r===void 0||$v(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:_y(r)?yW(i,r,a):`${i} "${r}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:q(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:q(e.source,[`globals`,`preset`])}),UW(e,t.presets);let a=yC(t);for(let t of a.names)t!==`settings`&&!t.startsWith(ZW)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:q(e.source,[`variables`,t])});let o=(t,n,i)=>{KL(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${gi}" ${KL(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:i}),qL(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${gi}" under a \`when\` or inside a disclosure body — the menu is visible under every condition, so its placement may not be gated. Move it to an ungated position, or remove it to put the menu at its default position.`,line:i});let a=s(t,`bar`);a!==void 0&&e.issues.push({path:n,message:HW[a](n),line:i});let o=new Map;for(let e of Fy(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=jy(e);o.set(t,[...o.get(t)??[],e])}for(let[t,r]of o){if(r.length<2)continue;let a=r[1].name,s=Ny(a,new Set(o.keys()));e.issues.push({path:n,message:`${n} has ${r.length} placements with the id "${t}" — an id names one placement (its settings, its menus' open state, and edit mode all address it), so give each its own: { seg: "${a}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:i})}};function s(e,t){if(e.kind===`segment`||e.distribution===void 0)return;if(t===`nested`)return`nested`;let n=t===`bar`&&e.children.some(e=>e.kind===`segment`||Ay[e.direction]===`cell`);return Ay[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:Ay[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,Iy(t,n)]):e.opens===void 0?[]:[[e.opens.body,Ly(t)]];function*u(e,t){for(let[n,r]of e){let e=s(n,t);e!==void 0&&(yield[e,r]),yield*u(l(n,r),c(n,t))}}let d=new Set,f=(n,i)=>{let o=iS(n),s=eS(n)?Object.entries(n.rows).map(([e,t])=>[t,`${i}.rows.${e}`]):l(o,i);for(let[t,n]of u(s,c(o,`bar`)))e.issues.push({path:n,message:HW[t](n),line:q(e.source,n.split(`.`))});for(let[o,s]of aS(n,i)){let n=q(e.source,s.split(`.`));if(o.when!==void 0&&(pG(e,`${s}.when`,o.when,a,{line:n}),dG(e,`${s}.when`,o.when,n),fG(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if(UL(o.name)){(o.id!==void 0||o.settings!==void 0)&&e.issues.push({path:s,message:`${i} gives the global settings menu anchor "${gi}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${gi}"`,line:n});continue}let c=r(o.name);TW(c)&&(d.add(o.name),e.unplaced.push({path:s,message:GW(i,o.name,t.segments,c),line:n})),aG(e,t,o,s,n)}};n.root!==void 0&&f(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&f(t.root,`presets.${e}.root`);let p=new Map([[`root`,rS(t.root)]]);for(let e of mS(t.presets)){let{node:n,path:r}=_S(t,e);p.set(r,n)}for(let[t,n]of p)o(n,t,q(e.source,t.split(`.`)));for(let[n,i]of p)for(let[a]of Ry(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);TW(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:GW(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:q(e.source,n.split(`.`))}))}xG(e,t,a,()=>!0)}const YW=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function XW(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=q(e.source,[`actions`,n,r]);if(!mS(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${mS(t.presets).join(`, `)})`,line:c});return}if(r===`reset`)return;let l=`removeSegment`in o,u=`insertSegment`in o,d=`insertSegmentFrom`in o;if(!l&&!u&&!d){e.issues.push({path:s,message:`actions.${n}: "${i}" is a "presets.<name>.root" target and can only be paired with "removeSegment", "insertSegment", or "insertSegmentFrom" (not "to"/"from"/"cycle"/bounded — those have no meaning as a tree op)`,line:c});return}let f=(r,i)=>{Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})${jz(i)}`,line:c})},p=new Set(My(_S(t,a).node)),m=(r,i)=>{!Az.has(i)||p.has(i)||Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" names no placement${jz(i)}`,line:c})};`removeSegment`in o&&m(`removeSegment`,o.removeSegment),`insertSegment`in o&&f(`insertSegment`,o.insertSegment),(`insertSegment`in o||`insertSegmentFrom`in o)&&m(`anchor`,o.anchor)}const ZW=`settings.`;function QW(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>ZW+e)])}}function $W(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:q(e.source,[`segments`,t,`settings`,n])})},a=nG(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of $y(n,tG(n)))i(e,`the defaults do not stand together: ${t}`)}function eG(e){return nG(e).length>0||$y(e,tG(e)).length>0}function tG(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function nG(e){let t=t=>Qy(rG(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||Qy(rG(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${iG(e,n).join(`, `)||`none`})`}];let i=[n];for(let e=r;e!==void 0;e=t(e)){if(e===n)return i.every(e=>n<=e)?[{setting:n,message:`atLeast closes a cycle (${[...i,n].join(` ≥ `)}) — every setting on it could only ever equal the rest`}]:[];if(i.includes(e))return[];i.push(e)}return[]})}function rG(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function iG(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&Qy(n)!==void 0).map(([e])=>e)}function aG(e,t,n,r,i){let a=Object.prototype.hasOwnProperty.call(t.segments,n.name)?t.segments[n.name]:void 0;if(a===void 0)return;let o=Zy(a),s=`${r}: placement "${jy(n)}" of segment "${n.name}"`;for(let[t,a]of Object.entries(n.settings??{})){let c=Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0,l=c===void 0?`sets "${t}", which segment "${n.name}" does not declare (it has: ${Object.keys(o).join(`, `)})`:eb(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Wv(a):``}, but it must be ${rb(c)}`;l!==void 0&&e.issues.push({path:r,message:`${s} ${l}`,line:i})}let c=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,n.settings?.[e]??t.default]));if(!(!Object.entries(c).every(([e,t])=>eb(o[e],t))||eG(o)))for(let{message:t}of $y(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function oG(e,t,n,r,i){for(let[a,o]of Wy(n))pG(e,`${t}.${a}`,o,r,{segCtx:i})}function sG(e,t,n,r,i){if(!(!Hy(n)||!(`depends_on`in n.cache)))for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:q(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const cG=`it reads the instant a frame is drawn at, which changes every frame, and a cache policy re-runs its source when a stored value changes — re-run it on a period instead: cache: { ttl: "<duration>" }`;function lG(e,t,n,r){if(!Hy(n))return;let i=n=>q(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=BW(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${cG}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=IW(r);n.cache.depends_on.forEach((n,r)=>{let o=a.get(n);o!==void 0&&e.issues.push({path:`${t}.cache.depends_on[${r}]`,message:`cache.depends_on names "${n}", which ${o}: ${cG}`,line:i(`depends_on`)})})}}function uG(e,t){let n=new Map(gC(t)),r=MW(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=Qv.find(e=>Rj[e]===n||Rj[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${Rj[e]}", the ${e}'s own name`;for(let e of r){let n=a(e,t);if(n!==null)return n}}return null},a=(e,t)=>{if(t.has(e))return null;t.add(e);let a=n.get(e),o=AW(e,a),s=o===void 0?void 0:zj(o);if(s!==void 0)return`reads "${e}", the ${s}'s own name`;for(let n of r.ofVariable(a)){let r=i([n],t);if(r!==null)return n.field===`template`?`reads "${e}", which ${r}`:`reads "${e}", whose ${n.field} ${r}`}return null};for(let{at:n,rule:a}of RW(t)){let t=i(r.ofTemplate(a),new Set);if(t===null)continue;let o=n.join(`.`);e.issues.push({path:o,message:`${o} ${t}: a rule decides that name, so it cannot read it — read the data the rule is about instead`,line:q(e.source,[...n])})}}function dG(e,t,n,r){try{eN.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function fG(e,t,n,r,i,a=t.helpers,o){let s=n.slice(n.lastIndexOf(`.`)+1);for(let{name:c,site:l,via:u}of aC(r,a)){if(Object.prototype.hasOwnProperty.call(t.actions,c))continue;let r=l===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(u!==null){hG(e,u,`Template references unknown action "${c}"${r}`,mG(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function pG(e,t,n,r,i){for(let[a,o]of tC(n,r.helpers)){if(vC(a,r))continue;if(a.startsWith(ZW)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??q(e.source,t.split(`.`))});continue}if(o!==null){hG(e,o,`Template references unknown variable ".${a}"${Hz(a)}`,mG(o,i?.segCtx===void 0?void 0:{name:i.segCtx,partials:i.partials}));continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&vC(n,r)?` (segment-local vars are namespaced — write ".${n}")`:Hz(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??q(e.source,t.split(`.`))})}}function mG(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function hG(e,t,n,r=[`helpers`,t]){let i=r.join(`.`);e.issues.some(e=>e.path===i&&e.message===n)||e.issues.push({path:i,message:n,line:q(e.source,r)})}function gG(e,t,n,r,i){let a=n.set,o=gM(Mx[r].configKey),s=`${a} takes ${$j(o,i)}`;if(`min`in n&&(o===`bool`||!(`min`in o))){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:q(e.source,[`actions`,t,`min`])});return}let c=yG(n,i);if(c===vG){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:q(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!Qj(o,e.value,i));if(l.length!==0){if(a===Mx.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>_y(e.value)))){let r=Mx.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:yW(`actions.${t}.to`,n.to,`set: "${r}", to`),line:q(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:q(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=_G?r.join(`, `):`${r.slice(0,_G).join(`, `)} and ${r.length-_G} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:q(e.source,[`actions`,t,n])})}}}const _G=3,vG=Symbol(`any integer`);function yG(e,t){return`to`in e?[{field:`to`,value:e.to}]:`cycle`in e?e.cycle.map(e=>({field:`cycle`,value:e})):`from`in e?ES(e.from,t).members.map(e=>({field:`from`,value:e})):`min`in e?[{field:`min`,value:String(e.min)},{field:`max`,value:String(e.max)}]:vG}function bG(e,t){return Object.entries(e).filter(([e])=>t(e))}function xG(e,t,n,r){let i=bR(t),a=TS(i);for(let[n,o]of bG(t.actions,r)){let[t,r]=`from`in o?[`from`,o.from]:`insertSegmentFrom`in o?[`insertSegmentFrom`,o.insertSegmentFrom]:[null,null];if(t!==null&&typeof r==`string`&&!a.includes(r)){e.issues.push({path:`actions.${n}.${t}`,message:`actions.${n} ${t}: references ${OS(r,i)}`,line:q(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;Ix.has(o.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${o.set}", which has no session pick — globals.${o.set} is set in the config file only, so a click would change nothing; write it with { persist: "${o.set}", … } instead`,line:q(e.source,[`actions`,n,`set`])});let s=Bx.get(o.set);s!==void 0&&gG(e,n,o,s,i)}for(let[n,i]of bG(t.actions,r))`do`in i&&i.do.forEach((r,a)=>{let o=Object.prototype.hasOwnProperty.call(t.actions,r)?t.actions[r]:void 0,s=o===void 0?`references unknown action "${r}"`:`do`in o?`"${r}" is itself a do action — list its members here instead`:i.do.indexOf(r)===a?a>0&&NS(o)?`"${r}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${r}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:q(e.source,[`actions`,n,`do`])})});for(let[n,i]of bG(t.actions,r))if(`run`in i)for(let r of i.refreshes){let i=Object.hasOwn(t.variables,r)?t.variables[r]:void 0;i?.kind!==`source`&&e.issues.push({path:`actions.${n}.refreshes`,message:`actions.${n} refreshes "${r}", which ${i===void 0?`is not declared`:`is a ${i.kind} variable`}: a run refreshes only a declared source (by its full name, <scope>.<plugin>.<source> where the scope is plugins or repo; a plugin names its own sources bare)`,line:q(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of bG(t.actions,r)){let r=`persist`in i?i.persist:`reset`in i?i.reset:null;if(r===null)continue;let a=`persist`in i?`persist`:`reset`,o=YM(r);if(o===null){let t=LM(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${RM().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, a "themeDefaults.<theme>.<shade|variation|style>" target, or a "presets.<name>.root" target`:`actions.${n}: the globals field "${r}" was removed: ${t}`,line:q(e.source,[`actions`,n,a])});continue}let s=YW.filter(e=>e in i);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:q(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){XW(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!mS(t.presets).includes(o.preset)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names preset "${o.preset}" which is not declared (have: ${mS(t.presets).join(`, `)})`,line:q(e.source,[`actions`,n,a])});continue}if(o.scope===`theme-default`&&!e.allowedPalettes.has(o.theme)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names theme "${o.theme}" which is not installed${Wv(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:q(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${jz(o.segment)}`,line:q(e.source,[`actions`,n,a])});continue}`min`in i&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:q(e.source,[`actions`,n,a])})}}for(let[i,a]of bG(t.variables,r)){oG(e,`variables.${i}`,a,n);let t=Vz(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:q(e.source,[`variables`,i])})}for(let[i,a]of bG(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))oG(e,`segments.${i}.vars.${t}`,r,n,i);let r=Zy(a);if($W(e,i,r),a.partials!==void 0)for(let t of Object.keys(a.partials))Object.hasOwn(n.helpers,t)&&e.issues.push({path:`segments.${i}.partials.${t}`,message:`segments.${i}.partials.${t} reuses the name of a global helper (helpers.${t}) — partials and helpers share one define chain, so pick a name no helper already uses`,line:q(e.source,[`segments`,i,`partials`,t])});let o=a.partials===void 0?n.helpers:{...n.helpers,...a.partials},s=QW({...n,helpers:o},r);for(let n of uH){let c=a[n];typeof c==`string`&&(pG(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),fG(e,t,`segments.${i}.${n}`,c,q(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of bG(t.variables,r))sG(e,`variables.${i}`,a,n),lG(e,`variables.${i}`,a,t);uG(e,t);for(let[i,a]of bG(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))sG(e,`segments.${i}.vars.${r}`,o,n,i),lG(e,`segments.${i}.vars.${r}`,o,t)}function SG(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=CG(t),a=new Map,o=[];for(let e of r.keys())a.set(e,0);for(let e of r.keys())if(!(!n(e)||a.get(e)!==0)&&s(e))return;function s(t){a.set(t,1),o.push(t);for(let c of r.get(t)??[]){if(!n(c))continue;let t=a.get(c);if(t===1){let t=o.indexOf(c),n=[...o.slice(t),c],r=n[0],a=i.get(r);return e.issues.push({path:a?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:q(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function CG(e){let t=new Map,n=new Map,r=MW(e),i=(e,i,a)=>{t.set(e,{declarationPath:a.join(`.`),linePathParts:a}),n.set(e,new Set(r.ofVariable(i).flatMap(({reaches:e})=>e)))};for(let[t,n]of Object.entries(e.variables))i(t,n,[`variables`,t]);for(let[t,n]of Object.entries(e.segments))for(let[e,r]of Object.entries(n.vars??{}))i(`${t}.${e}`,r,[`segments`,t,`vars`,e]);return{graph:n,nodeInfo:t}}function wG(e,t,n){let r=new Map([...hC(t)].map(([e,,t])=>[e,t]));for(let[t,i]of r){let a=t.split(`.`);for(let o=1;o<a.length;o++){let s=a.slice(0,o).join(`.`),c=r.get(s);if(c===void 0||!(n.checked(t)||n.checked(s)))continue;let[l,u,d]=n.authored(t)?[t,s,i]:[s,t,c],f=n.authored(t)===n.authored(s)?`Rename one so neither name starts with the other.`:`"${u}" is declared outside this file (the bundled default, a plugin, or a control the bar builds), so rename "${l}".`;e.issues.push({path:d.join(`.`),message:`variable "${t}" is declared under the variable "${s}" — a read of ".${t}" would name both, "${t}" and a field of "${s}". ${f}`,line:q(e.source,[...d])})}}}function TG(e){return{...PG,config:Ez(PG.raw,e)}}function EG(e,t,n,r,i){let a=VG(e,t,i,(t,a)=>{let o=QV(ZV(t,e,r.scope,r.home),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>MG(t,n,r,e,i)),s=nH(o,r.beneath.dropped);return{inherited:new Set([...IB(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=rH(Ez(a.raw,o.config),s,(a.raw.insert??[]).map(e=>e.seg));return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(HV)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const DG=new WeakMap;function OG(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e.path,e.scope,AG(e.path)])]),a=DG.get(n)??new Map;DG.set(n,a);let o=JSON.stringify([t.repo,t.checkout?.root??null]),s=a.get(o);if(s?.key===i)return s.layer;let c=QV(e,t,{config:n,rendering:new Map},(e,t,n)=>MG(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function kG(e,t,n,r){return QV(e,{repo:null,checkout:n,home:r},{config:t,rendering:new Map},(e,t,n)=>MG(e,t,n,`<plugin install>`,void 0)).dropped}function AG(e){try{let t=l.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function jG(e,t,n,r,i,a=e=>l.readFileSync(e,`utf-8`),o){let s={repo:i.repo,checkout:i.cwd===null?null:nc(i.cwd),home:e.home},c=OH(e,s.repo),u=OG(c.definitions,s,n,o),d={...u,dropped:[...u.dropped,...c.strays]};r.warned(c.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let f=d.config,p=[];for(let{path:e,scope:n}of t){let t=p.at(-1)?.plugins,i=EG(e,a(e),p.at(-1)?.config??f,{...s,scope:n,beneath:{dropped:[...d.dropped,...p.flatMap(e=>e.plugins.dropped)],rendering:t?.rendering??d.rendering}},o);r.warned(i.warnings),p.push({...i,path:e})}let m=new Set(p.flatMap(e=>[...e.plugins.reached])),h=e=>m.has(e.path),g=d.dropped.filter(h),_=d.dropped.filter(e=>!h(e));r.warned(g.map(HV));let v=p.at(-1)?.plugins.rendering??d.rendering,y={checkout:s.checkout,roots:c.roots,loaded:d.loaded,dropped:g,unreached:_,reached:m,rendering:v},b=p.at(-1),x=({warnings:e,...t})=>(r.warned(e),t);if(b===void 0)return{layers:p,base:f,installed:y,...x(FG(TG(f),v,`<default>`,o))};try{return{layers:p,base:f,installed:y,...x(FG(b,v,b.path,o,p.slice(0,-1).reverse()))}}catch(e){for(let[e,t]of p.slice(0,-1).entries())FG(t,t.plugins.rendering,t.path,o,p.slice(0,e).reverse());throw e}}function MG(e,t,n,r,i){if(n){FG(NG(e),new Map,r,i);return}let a=IS(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[],unplaced:[],inherited:[]};if(xG(s,e,yC(e),a),SG(s,e,a),wG(s,e,{checked:a,authored:a}),o.length>0)throw new ib(r,o)}function NG(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const PG={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function FG(e,t,n=`<config>`,r=new Set(qv()),i=[]){let a=wW(e.config.segments,t),o=LG({...e,path:n},i,a),s=(t,s)=>{let c=vS(e.config,t,o.authored);return IG(e,n,r,i,c.config,a,o.dropped,[...c.notices,...s])};try{return s(o.cells,[])}catch(e){if(!(e instanceof ib)||o.cells.length===0)throw e;let t=s([],[]),n=new Set(t.dropped.flatMap(e=>e.issues.map(e=>e.message))),{taken:r,refused:i}=o.cells.reduce((e,t)=>{try{return s([...e.taken,t],[]),{...e,taken:[...e.taken,t]}}catch(r){if(!(r instanceof ib))throw r;let i=r.issues.filter(e=>!n.has(e.message)).map(e=>e.message).join(`; `);return{...e,refused:[...e.refused,yS(t,`${t.relation} "${t.anchor}", but the bar refuses it there: ${i}`)]}}},{taken:[],refused:[]});return s(r,i)}}function IG({raw:e,source:t},n,r,i,a,o,s,c){let l=[],u={source:t,issues:l,allowedPalettes:r,groups:[],unplaced:[],inherited:[]},d=()=>{if(l.length>0)throw new ib(n,[...l,...u.unplaced,...u.inherited],c)};JW(u,a,e,o),SG(u,a),d();let f=zG(n,a.segments,u,o,i,s),p=vW(DW(a),l);d();let m=HR(iR(p)),h=new Set([...hC({variables:e.variables??{},segments:e.segments??{}})].map(([e])=>e));return wG(u,m,{checked:()=>!0,authored:e=>h.has(e)}),d(),{config:m,dropped:f,placed:a,warnings:c}}function LG(e,t,n){let r=[...t].reverse().concat(e),i=EW(e.config,r.flatMap(e=>e.raw.insert??[]),n),a=e=>!i(e.anchor),o=e=>n(e.seg).kind===`declared`,s=e=>TW(n(e.seg)),c=e=>(e.raw.insert??[]).filter(a);return{cells:r.flatMap(e=>c(e).filter(o)),authored:{root:r.some(e=>e.raw.root!==void 0),presets:new Set(r.flatMap(e=>Object.keys(e.raw.presets??{})))},dropped:r.flatMap(t=>{let r=ab(t.source);return(t.raw.insert??[]).filter(s).map(i=>({file:t.path,issue:{path:i.by.entry,message:GW(i.by.entry,i.seg,e.config.segments,n(i.seg)),line:r(i.by.entry.split(`.`))}}))})}}function RG(e){if(e.length>0)throw new kee(e)}function zG(e,t,n,r,i,a){let o=new Map,s=(e,t)=>{o.set(e,[...o.get(e)??[],t])};for(let{file:e,issue:t}of a)s(e,t);for(let t of n.unplaced)s(e,t);for(let{name:a,...o}of n.inherited){let n=i.flatMap(e=>{let t=WW(e.raw,a);return t===void 0?[]:[{layer:e,...t}]})[0];n===void 0?s(e,o):s(n.layer.path,{path:n.path,message:GW(n.layoutKey,a,t,r(a)),line:q(n.layer.source,n.path.split(`.`))})}return[...o].map(([e,t])=>new Oee(e,t))}function BG(e,t,n=new Set(qv()),r=HG){return VG(e,t,n,()=>({inherited:r,layer:null})).raw}function VG(e,t,n,r){let i=UG(e,t),a=Pee(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(qv()),groups:[],unplaced:[],inherited:[]};if(!db(i))throw new ib(e,[{path:``,message:`Config root must be an object, got ${fb(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:KG({...c,issues:[]},i.plugins)??[],db(i.segments)?Object.keys(i.segments):[]),d=WG(c,i,l,ZB(e),e);if(s.length>0)throw new ib(e,s,o);return{raw:d,warnings:o,layer:u}}const HG=new Set;function UG(e,t){try{return ua.default.parse(t)}catch(t){let n=t;throw new ib(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function WG(e,t,n,r,i){for(let n of Object.keys(t))GG.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...GG].join(`, `)}`,line:q(e.source,[n])});let a={};return t.globals!==void 0&&(a.globals=jM(e,`globals`,t.globals)),t.variables!==void 0&&(a.variables=qz(e,`variables`,t.variables)),t.segments!==void 0&&(a.segments=LB(e,t.segments,n)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
|
|
182
|
+
New: { h: ["seg1", "seg2"] }`,line:q(e.source,[`root`])}),NU;if(n.kind===`group`){let r=pb(e,eW,t,n);return r===null?NU:(e.groups.push({name:r.name,label:r.label,...r.open!==void 0&&{open:r.open},...r.direction!==void 0&&{direction:r.direction},...r.key!==void 0&&{key:r.key},...r.bg!==void 0&&{bg:r.bg},...r.fg!==void 0&&{fg:r.fg},...r.when!==void 0&&{when:r.when},path:t}),nW(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:q(e.source,[`root`])}),NU}if(a){let r=pb(e,HU,t,n);return r===null?NU:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when},...r.id!==void 0&&{id:r.id},...r.settings!==void 0&&{settings:r.settings}}}if(r){let r=pb(e,UU,t,n);return r===null?NU:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}if(i){let r=pb(e,WU,t,n);return r===null?NU:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:q(e.source,[`root`])}),NU};function KU(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Zx.source},additionalProperties:{$ref:MU}},parse:(e,t,n,r)=>{let i=r[n];if(!db(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${fb(i)}`,line:q(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!Zx.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:q(e.source,[...t.split(`.`),n,r])});continue}a[r]=GU(e,`${t}.${n}.${r}`,o)}return a}}}const qU={noun:`root key`,fields:{rows:KU(),when:wb(),distribution:zU()}};function JU(e,t,n){return db(n)&&`rows`in n?pb(e,qU,t,n)??{rows:{}}:GU(e,t,n)}const YU={noun:`insert key`,fields:{seg:VU(),id:NB(),before:wb(),after:wb()}};function XU(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=pb(e,YU,i,t);if(a===null)return[];let o=[`before`,`after`].filter(e=>a[e]!==void 0);if(o.length!==1)return e.issues.push({path:i,message:`an insert cell names exactly one of "before" or "after" (the placement id it sits beside), got ${o.length===0?`neither`:`both`}`,line:q(e.source,i.split(`.`))}),[];if(hi(a.seg))return e.issues.push({path:`${i}.seg`,message:`an insert cell places a segment, and "${a.seg}" is the bar's own chrome — name a segment instead`,line:q(e.source,[...i.split(`.`),`seg`])}),[];let s=o[0],c=a[s];return hi(c)?(e.issues.push({path:`${i}.${s}`,message:`an insert cell sits beside a placement, and "${c}" is the bar's own chrome — anchor on a placement id instead`,line:q(e.source,[...i.split(`.`),s])}),[]):[{seg:a.seg,...a.id!==void 0&&{id:a.id},anchor:c,relation:s,by:{file:n,entry:i}}]}):(e.issues.push({path:`insert`,message:`"insert" must be a list of cells like { seg: "name", after: "placement" }, got ${fb(t)}`,line:q(e.source,[`insert`])}),[])}function ZU(){return{required:!0,json:{type:`string`,pattern:Zx.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Zx.test(i)||i===`closed`){e.issues.push({path:`${t}.${n}`,message:`a group "name" must be an identifier (letters, digits, _; not starting with a digit) and not the reserved "${Yr}", got ${J(i)}`,line:q(e.source,[`root`])});return}return i}}}function QU(){return{required:!1,json:{type:`string`,minLength:1},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`string`||i===``||i.includes(`/`)){e.issues.push({path:`${t}.${n}`,message:`a group "key" must be a non-empty, slash-free SessionState key, got ${J(i)}`,line:q(e.source,[`root`])});return}return i}}}}function $U(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=sb(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:q(e.source,[...t.split(`.`),n])});return}return i}}}}const eW={noun:`layout-node key`,fields:{kind:PU(`group`),name:ZU(),label:$U(),open:Tb(),direction:Mb(ky),key:QU(),bg:wb(),fg:wb(),when:wb(),distribution:zU(),children:LU(Sb(()=>GU))}};function tW(e){return e.key??`groups.`+e.name}function nW(e){let t=li+e.name;return ti(t,{variable:t,key:tW(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function rW(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,[`root`])})}function iW(e,t){nN(e,t,li,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&rW(e,t.path,`duplicate group name "${t.name}" — group names must be unique (they name the synthesized state var, action, and toggle segment)`),r.add(t.name);for(let t of n)for(let r of n)t!==r&&t.path.startsWith(`${r.path}.`)&&tW(t)===tW(r)&&rW(e,t.path,`group "${t.name}" shares key "${tW(t)}" with its ancestor group "${r.name}" — a shared key holds ONE open group, so an ancestor and a descendant cannot share one. Sibling accordions share a key; nested groups use distinct keys.`);let i=new Map;for(let t of n){let n=tW(t);if(i.has(n)||i.set(n,Yr),t.open===!0){let r=i.get(n);r!==`closed`&&rW(e,t.path,`groups "${r}" and "${t.name}" share key "${n}" and both declare open: true — a shared key holds one open group; pick one`),i.set(n,t.name)}}let a={},o={},s={};for(let e of n){let t=li+e.name,r=tW(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=si(r,i.get(r)),o[t]=P(r,e.name),s[t]={template:ii(t,`${l}${e.label} ▸`,`${l}${e.label} ▾`),...e.bg!==void 0&&{bg:e.bg},...e.fg!==void 0&&{fg:e.fg}}}t.variables={...t.variables??{},...a},t.actions={...t.actions??{},...o},t.segments={...t.segments??{},...s}}const aW=`menu`,oW=`a menu binds its trigger text the way a cycle action binds a display — write {{ menu "applyTheme" "▸" "▾" }} (one per state) or {{ menu "insertHere" "+" }} (one static display for both), with the rare knobs in ONE trailing dict: {{ menu "applyTheme" "▸" "▾" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key). The renderer no longer appends ▸/▾ of its own (candybar-settings-ui-aok.4), and the older positional tail ("pageAction" closeOnPick paged "key") was removed — the page cursor is synthesized from the menu's identity`,sW=e=>e.kind===`call`&&e.name===`dict`,cW=e=>e.kind===`literal`&&typeof e.value!=`object`,lW=e=>Qr(``,e,2)===void 0;function uW(e){let t=e=>({kind:`issue`,message:e}),[n,...r]=e.argExprs;if(n===void 0)return t(`with no arguments — it takes an apply-action name and its trigger text (e.g. {{ menu "applyTheme" "▸" "▾" }})`);if(n.kind!==`literal`||typeof n.value!=`string`)return t(`whose apply action is not a string literal — a menu's identity is its apply-action name, which must be a literal so it can be gated at load (e.g. {{ menu "applyTheme" "▸" "▾" }})`);let i=r[r.length-1],a=i!==void 0&&sW(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(sW))return t(`whose options (dict …) is not its last argument — ${oW}`);if(i!==void 0&&a===void 0&&!cW(i)&&lW(o.length-1))return t(`whose last argument is neither a literal nor a literal (dict …) — the renderer tells a display from the options dict by the value it evaluates to, so this call could be read as ${o.length} displays or as ${o.length-1} plus options, and both are legal. Make the options explicit as a trailing (dict …) — {{ menu "${n.value}" (printf "…") (printf "…") (dict) }} binds dynamic displays unambiguously — or bind the trigger text as literals`);let s=Qr(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${oW}`);let c=a===void 0?{}:ED(a);if(c===null)return t(`whose options (dict …) is not fully literal — every option value must be a literal so the menu can be gated at load (a dynamic entry like (dict "key" .x) cannot)`);let l;try{l=Xj(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=tN(u);if(e!==void 0)return t(`whose accordion key "${u}" lands in the reserved "${e}" namespace — a key is collapsed to an identifier (${JSON.stringify(u)} becomes "${Gj(u)}"), so it would share one open-state key with the synthesized accordion that owns that namespace instead of grouping only your own menus. Name the group without the reserved prefix`)}return{kind:`ok`,apply:n.value,options:l}}function dW(e){let t=FT({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===aW).map(uW)}catch{return`parse-failed`}}function fW(e,t){let n=dW(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:Wj(t,e.apply,e.options.key),member:Uj(e.apply)}]:[])}function pW(e){let t=FT({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(aW)}catch{return!1}}function mW(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,[`root`])})}function hW(e,t){nN(e,t,ui,`{{ menu }} helpers`),nN(e,t,di,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))pW(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:q(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n)){for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&pW(i)&&mW(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}for(let[n,i]of Object.entries(r.partials??{}))pW(i)&&e.issues.push({path:`segments.${t}.partials.${n}`,message:`segments.${t}.partials.${n} uses {{ menu }}, but a menu must live directly in a segment's "template" string — the synthesis pass that wires its state never follows a {{ template }} call into a partial. Inline the {{ menu }} call into the template itself.`,line:q(e.source,[`segments`,t,`partials`,n])})}if(t.root!==void 0)for(let n of Fy(iS(t.root)))typeof n.when==`string`&&pW(n.when)&&mW(e,`root`,`a layout node's "when" predicate uses {{ menu }} — a menu is only valid in a segment's "template", not a node predicate. Move it into a segment.`);for(let[t,{template:r}]of Object.entries(n)){if(r===void 0||!pW(r))continue;let n=dW(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:gW(r.apply);n!==void 0&&mW(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function gW(e){if(e===``)return`with an empty apply-action name — an empty member aliases the absent-state sentinel ("") so the menu would render open before any click. Name the apply action`;if(Uj(e)===`closed`)return`whose apply action is named "${Yr}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function _W(e,t){let n={},r={},i=new Map,a=new Set,o=(e,n)=>{let r=`segments.${e}`;a.has(`${r}\0${n}`)||(a.add(`${r}\0${n}`),t.push({path:r,message:n}))};for(let t of mS(e.presets)){let a=new Map,s=new Map;for(let c of Fy(_S(e,t).node)){if(c.kind!==`segment`)continue;let t=e.segments[c.name];if(t===void 0)continue;i.has(c.name)||i.set(c.name,dW(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=jy(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||gW(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=Uj(i),f=Wj(u,i,l.key),p=qj(f),m=l.key===void 0?`ind ${u} ${i}`:`key ${l.key}`,h=[f,p].find(e=>{let t=a.get(e);return t!==void 0&&t!==m});if(h!==void 0){o(c.name,`two {{ menu }} disclosures normalize to the same state key ("${h}") but were declared differently — distinct names that differ only by non-alphanumeric characters (e.g. "a-b" vs "a_b") collapse to one key and would silently share open-state. Rename so they don't collide.`);continue}a.set(f,m),a.set(p,m);let g=Kj(f,d),_=`${c.name}\0${e}`,v=s.get(g);if(v!==void 0&&v!==_){o(c.name,`two {{ menu }} disclosures resolve to the same identity ("${g}") — ${l.key===void 0?`a segment cannot contain two menus over the same apply action "${i}"`:`menus sharing key "${l.key}" must have distinct apply actions`}.`);continue}s.set(g,_),r[g]=P(f,d),n[f]=si(f,Yr),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}function vW(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const yW={noun:`style key`,fields:{hueShift:Db(),chromaScale:Db({min:0}),lightnessScale:Db(),lightnessShift:Db()}};function bW(e,t){if(!db(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${fb(t)}`,line:q(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:q(e.source,[`styles`,r])});continue}if(_y(r)){e.issues.push({path:`styles.${r}`,message:vW(`styles.${r}`,r,`globals.endcaps`),line:q(e.source,[`styles`,r])});continue}let t=pb(e,yW,`styles.${r}`,i);t!==null&&(n[r]={...au,...t})}return n}const xW={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:JU(e,`${t}.${n}`,r[n])},globals:{required:!1,json:NM(),parse:(e,t,n,r)=>r[n]===void 0?void 0:MM(e,`${t}.${n}`,r[n])}}};function SW(e,t){if(!db(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${fb(t)}`,line:q(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:q(e.source,[`presets`,r])});continue}let t=pb(e,xW,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function CW(e,t){let n=[...t].map(([e,t])=>[IS(e),t]);return t=>{if(HL(t)||Object.hasOwn(e,t))return{kind:`declared`};let r=n.find(([e])=>e(t));if(r!==void 0)return{kind:`plugin`,definition:r[1]};let i=RS(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function wW(e){return e.kind===`plugin`||e.kind===`missing`}function TW(e,t,n){let r=new Map,i=(e,t)=>{r.set(e,[...r.get(e)??[],t])},a=e=>eS(e)?Object.values(e.rows):[e],o=[e.root,...Object.values(e.presets).flatMap(e=>e.root===void 0?[]:[e.root])];for(let e of o.flatMap(a))for(let t of Fy(e))t.kind===`segment`&&i(jy(t),{seg:t.name});for(let e of t)i(e.id??e.seg,{seg:e.seg,anchor:e.anchor});let s=new Set,c=e=>n(e.seg).kind===`absent`||e.anchor!==void 0&&s.has(e.anchor);for(let e=!0;e;){e=!1;for(let[t,n]of r)!s.has(t)&&n.every(c)&&(s.add(t),e=!0)}return e=>s.has(e)}function EW(e){let t=0,n=CW(e.segments,new Map),r=e=>{let r=n(e).kind===`declared`;return r||(t+=1),r},i=e=>({...e,children:e.children.flatMap(e=>a(e))}),a=e=>e.kind===`container`?[i(e)]:r(e.name)?[Py(e,i)]:[],o=e=>a(e)[0]??DW,s=e=>({...e,rows:Object.fromEntries(Object.entries(e.rows).map(([e,t])=>[e,o(t)]))}),c=e=>eS(e)?s(e):o(e),l=e=>e.root===void 0?e:{...e,root:c(e.root)},u={...e,root:s(e.root),presets:Object.fromEntries(Object.entries(e.presets).map(([e,t])=>[e,l(t)]))};return t===0?e:u}const DW={kind:`container`,direction:`horizontal`,children:[]};function OW({names:e,helpers:t,actions:n}){let r=(e,t)=>{let i=Object.hasOwn(n,e)?n[e]:void 0;return i===void 0||t.has(e)?[]:(t.add(e),[...[...jS(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=XS(e=>{let i=cC(e,t)?Object.keys(n):aC(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]}),a=XS(n=>i(n).flatMap(n=>[...tC(n,t).keys()].map(t=>({path:t,reaches:_C(t,e)}))));return{ofTemplate:a,calls:XS(e=>new Set(i(e).flatMap(e=>[...uC(e,t)]))),ofVariable:t=>[...Wy(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...Hy(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function kW(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}const AW=new WeakMap;function jW(e){let t=AW.get(e);return t===void 0&&(t=OW({names:new Set([...gC(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),AW.set(e,t)),t}function MW(e,t){for(let n of t.reads.calls(e))if(t.clock.has(n))return`calls "${n}"`;for(let{reaches:n}of t.reads.ofTemplate(e))for(let e of n){let n=t.projections.get(e);if(n!==void 0)return`reads "${e}", which ${n}`}return null}const NW=new WeakMap;function PW(e){let t=NW.get(e);return t===void 0&&(t=IW(e),NW.set(e,t)),t}function FW(e){return PW(e).projections}function IW(e){let t=new Map(gC(e)),n=new Map,r={reads:jW(e),projections:n,clock:YA};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=kW(e,r),i=t===void 0?null:Lj(t);i&&n.set(e,`reads the draw's "${i}" (${Ij[i]})`)}let i=RW(e),a=new Map;for(let e=!0;e;){e=!1;for(let[i,a]of t){if(a.kind!==`template`||n.has(i))continue;let t=MW(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of Qv)if(!a.has(t))for(let n of i[t]){let i=MW(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=kW(r,i);if(t===void 0||n.has(r))continue;let o=zj(t),s=o===void 0?void 0:a.get(o);s!==void 0&&(n.set(r,`reads the ${o} rule, which ${s}`),e=!0)}}return r}function LW(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>Qv.flatMap(n=>{let r=t[n];return $v(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function RW(e){let t=LW(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function zW(e,t){return MW(e,PW(t))}function BW(e){return t=>MW(t,e)!==null}const VW={nested:e=>`${e} sets "distribution" on a container inside a row — the row's own container places every cell along it, through any { h } or { v } nested in it, so this one would place nothing. Set it on the row (the outermost horizontal container), or, on the bar, on the root, which places the rows.`,bar:e=>`${e} sets "distribution" on a vertical container none of whose children is a segment or a horizontal container — a bar row's hue is placed by the innermost vertical container it stacks through, so it would place nothing. Set it on that container, or on the row whose children are the cells (the horizontal container).`,band:e=>`${e} sets "distribution" on a vertical container in a disclosure body — a body's items are placed along their rows, never by which row they sit on, so it would place nothing. Set it on the row whose children are the items (the horizontal container), or give a group \`direction: 'horizontal'\`.`};function HW(e,t){let n=new Map;for(let e of Object.keys(t)){let t=Hj(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:q(e.source,[`presets`])})}function UW(e,t){let n=[[`root`,e.root],...Object.entries(e.presets??{}).map(([e,t])=>[`presets.${e}.root`,t.root])];for(let[e,r]of n)if(r!==void 0){for(let[n,i]of aS(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const WW=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${FS(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${GW(FS(r.definition),n)}${KW(t,n)}`:`${e} entry "${t}" does not match any declared segment${KW(t,n)}`;function GW(e,t){let n=Object.keys(t).filter(IS(e)).sort();return n.length===0?`no segments`:n.map(e=>{let n=Object.keys(t[e].settings??{});return`${e} (${n.length===0?`no settings`:`settings: ${n.join(`, `)}`})`}).join(`, `)}function KW(e,t){return Az(e)+zS(e,e=>Object.hasOwn(t,e))}function qW(e,t,n,r){let i=[[[`globals`],t.globals.style,`globals.endcaps`],[[`editGlobals`],t.editGlobals.style,`editGlobals.endcaps`],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style,`presets.${e}.globals.endcaps`]),...Object.entries(t.themeDefaults).map(([e,t])=>[[`themeDefaults`,e],t.style,`globals.endcaps`])];for(let[n,r,a]of i){if(r===void 0||$v(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:_y(r)?vW(i,r,a):`${i} "${r}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:q(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:q(e.source,[`globals`,`preset`])}),HW(e,t.presets);let a=yC(t);for(let t of a.names)t!==`settings`&&!t.startsWith(XW)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:q(e.source,[`variables`,t])});let o=(t,n,i)=>{GL(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${gi}" ${GL(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:i}),KL(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${gi}" under a \`when\` or inside a disclosure body — the menu is visible under every condition, so its placement may not be gated. Move it to an ungated position, or remove it to put the menu at its default position.`,line:i});let a=s(t,`bar`);a!==void 0&&e.issues.push({path:n,message:VW[a](n),line:i});let o=new Map;for(let e of Fy(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=jy(e);o.set(t,[...o.get(t)??[],e])}for(let[t,r]of o){if(r.length<2)continue;let a=r[1].name,s=Ny(a,new Set(o.keys()));e.issues.push({path:n,message:`${n} has ${r.length} placements with the id "${t}" — an id names one placement (its settings, its menus' open state, and edit mode all address it), so give each its own: { seg: "${a}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:i})}};function s(e,t){if(e.kind===`segment`||e.distribution===void 0)return;if(t===`nested`)return`nested`;let n=t===`bar`&&e.children.some(e=>e.kind===`segment`||Ay[e.direction]===`cell`);return Ay[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:Ay[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,Iy(t,n)]):e.opens===void 0?[]:[[e.opens.body,Ly(t)]];function*u(e,t){for(let[n,r]of e){let e=s(n,t);e!==void 0&&(yield[e,r]),yield*u(l(n,r),c(n,t))}}let d=new Set,f=(n,i)=>{let o=iS(n),s=eS(n)?Object.entries(n.rows).map(([e,t])=>[t,`${i}.rows.${e}`]):l(o,i);for(let[t,n]of u(s,c(o,`bar`)))e.issues.push({path:n,message:VW[t](n),line:q(e.source,n.split(`.`))});for(let[o,s]of aS(n,i)){let n=q(e.source,s.split(`.`));if(o.when!==void 0&&(fG(e,`${s}.when`,o.when,a,{line:n}),uG(e,`${s}.when`,o.when,n),dG(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if(HL(o.name)){(o.id!==void 0||o.settings!==void 0)&&e.issues.push({path:s,message:`${i} gives the global settings menu anchor "${gi}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${gi}"`,line:n});continue}let c=r(o.name);wW(c)&&(d.add(o.name),e.unplaced.push({path:s,message:WW(i,o.name,t.segments,c),line:n})),iG(e,t,o,s,n)}};n.root!==void 0&&f(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&f(t.root,`presets.${e}.root`);let p=new Map([[`root`,rS(t.root)]]);for(let e of mS(t.presets)){let{node:n,path:r}=_S(t,e);p.set(r,n)}for(let[t,n]of p)o(n,t,q(e.source,t.split(`.`)));for(let[n,i]of p)for(let[a]of Ry(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);wW(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:WW(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:q(e.source,n.split(`.`))}))}bG(e,t,a,()=>!0)}const JW=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function YW(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=q(e.source,[`actions`,n,r]);if(!mS(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${mS(t.presets).join(`, `)})`,line:c});return}if(r===`reset`)return;let l=`removeSegment`in o,u=`insertSegment`in o,d=`insertSegmentFrom`in o;if(!l&&!u&&!d){e.issues.push({path:s,message:`actions.${n}: "${i}" is a "presets.<name>.root" target and can only be paired with "removeSegment", "insertSegment", or "insertSegmentFrom" (not "to"/"from"/"cycle"/bounded — those have no meaning as a tree op)`,line:c});return}let f=(r,i)=>{Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})${Az(i)}`,line:c})},p=new Set(My(_S(t,a).node)),m=(r,i)=>{!kz.has(i)||p.has(i)||Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" names no placement${Az(i)}`,line:c})};`removeSegment`in o&&m(`removeSegment`,o.removeSegment),`insertSegment`in o&&f(`insertSegment`,o.insertSegment),(`insertSegment`in o||`insertSegmentFrom`in o)&&m(`anchor`,o.anchor)}const XW=`settings.`;function ZW(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>XW+e)])}}function QW(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:q(e.source,[`segments`,t,`settings`,n])})},a=tG(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of $y(n,eG(n)))i(e,`the defaults do not stand together: ${t}`)}function $W(e){return tG(e).length>0||$y(e,eG(e)).length>0}function eG(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function tG(e){let t=t=>Qy(nG(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||Qy(nG(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${rG(e,n).join(`, `)||`none`})`}];let i=[n];for(let e=r;e!==void 0;e=t(e)){if(e===n)return i.every(e=>n<=e)?[{setting:n,message:`atLeast closes a cycle (${[...i,n].join(` ≥ `)}) — every setting on it could only ever equal the rest`}]:[];if(i.includes(e))return[];i.push(e)}return[]})}function nG(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function rG(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&Qy(n)!==void 0).map(([e])=>e)}function iG(e,t,n,r,i){let a=Object.prototype.hasOwnProperty.call(t.segments,n.name)?t.segments[n.name]:void 0;if(a===void 0)return;let o=Zy(a),s=`${r}: placement "${jy(n)}" of segment "${n.name}"`;for(let[t,a]of Object.entries(n.settings??{})){let c=Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0,l=c===void 0?`sets "${t}", which segment "${n.name}" does not declare (it has: ${Object.keys(o).join(`, `)})`:eb(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Wv(a):``}, but it must be ${rb(c)}`;l!==void 0&&e.issues.push({path:r,message:`${s} ${l}`,line:i})}let c=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,n.settings?.[e]??t.default]));if(!(!Object.entries(c).every(([e,t])=>eb(o[e],t))||$W(o)))for(let{message:t}of $y(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function aG(e,t,n,r,i){for(let[a,o]of Wy(n))fG(e,`${t}.${a}`,o,r,{segCtx:i})}function oG(e,t,n,r,i){if(!(!Hy(n)||!(`depends_on`in n.cache)))for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:q(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const sG=`it reads the instant a frame is drawn at, which changes every frame, and a cache policy re-runs its source when a stored value changes — re-run it on a period instead: cache: { ttl: "<duration>" }`;function cG(e,t,n,r){if(!Hy(n))return;let i=n=>q(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=zW(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${sG}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=FW(r);n.cache.depends_on.forEach((n,r)=>{let o=a.get(n);o!==void 0&&e.issues.push({path:`${t}.cache.depends_on[${r}]`,message:`cache.depends_on names "${n}", which ${o}: ${sG}`,line:i(`depends_on`)})})}}function lG(e,t){let n=new Map(gC(t)),r=jW(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=Qv.find(e=>Rj[e]===n||Rj[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${Rj[e]}", the ${e}'s own name`;for(let e of r){let n=a(e,t);if(n!==null)return n}}return null},a=(e,t)=>{if(t.has(e))return null;t.add(e);let a=n.get(e),o=kW(e,a),s=o===void 0?void 0:zj(o);if(s!==void 0)return`reads "${e}", the ${s}'s own name`;for(let n of r.ofVariable(a)){let r=i([n],t);if(r!==null)return n.field===`template`?`reads "${e}", which ${r}`:`reads "${e}", whose ${n.field} ${r}`}return null};for(let{at:n,rule:a}of LW(t)){let t=i(r.ofTemplate(a),new Set);if(t===null)continue;let o=n.join(`.`);e.issues.push({path:o,message:`${o} ${t}: a rule decides that name, so it cannot read it — read the data the rule is about instead`,line:q(e.source,[...n])})}}function uG(e,t,n,r){try{eN.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function dG(e,t,n,r,i,a=t.helpers,o){let s=n.slice(n.lastIndexOf(`.`)+1);for(let{name:c,site:l,via:u}of aC(r,a)){if(Object.prototype.hasOwnProperty.call(t.actions,c))continue;let r=l===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(u!==null){mG(e,u,`Template references unknown action "${c}"${r}`,pG(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function fG(e,t,n,r,i){for(let[a,o]of tC(n,r.helpers)){if(vC(a,r))continue;if(a.startsWith(XW)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??q(e.source,t.split(`.`))});continue}if(o!==null){mG(e,o,`Template references unknown variable ".${a}"${Vz(a)}`,pG(o,i?.segCtx===void 0?void 0:{name:i.segCtx,partials:i.partials}));continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&vC(n,r)?` (segment-local vars are namespaced — write ".${n}")`:Vz(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??q(e.source,t.split(`.`))})}}function pG(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function mG(e,t,n,r=[`helpers`,t]){let i=r.join(`.`);e.issues.some(e=>e.path===i&&e.message===n)||e.issues.push({path:i,message:n,line:q(e.source,r)})}function hG(e,t,n,r,i){let a=n.set,o=gM(Mx[r].configKey),s=`${a} takes ${$j(o,i)}`;if(`min`in n&&(o===`bool`||!(`min`in o))){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:q(e.source,[`actions`,t,`min`])});return}let c=vG(n,i);if(c===_G){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:q(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!Qj(o,e.value,i));if(l.length!==0){if(a===Mx.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>_y(e.value)))){let r=Mx.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:vW(`actions.${t}.to`,n.to,`set: "${r}", to`),line:q(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:q(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=gG?r.join(`, `):`${r.slice(0,gG).join(`, `)} and ${r.length-gG} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:q(e.source,[`actions`,t,n])})}}}const gG=3,_G=Symbol(`any integer`);function vG(e,t){return`to`in e?[{field:`to`,value:e.to}]:`cycle`in e?e.cycle.map(e=>({field:`cycle`,value:e})):`from`in e?ES(e.from,t).members.map(e=>({field:`from`,value:e})):`min`in e?[{field:`min`,value:String(e.min)},{field:`max`,value:String(e.max)}]:_G}function yG(e,t){return Object.entries(e).filter(([e])=>t(e))}function bG(e,t,n,r){let i=yR(t),a=TS(i);for(let[n,o]of yG(t.actions,r)){let[t,r]=`from`in o?[`from`,o.from]:`insertSegmentFrom`in o?[`insertSegmentFrom`,o.insertSegmentFrom]:[null,null];if(t!==null&&typeof r==`string`&&!a.includes(r)){e.issues.push({path:`actions.${n}.${t}`,message:`actions.${n} ${t}: references ${OS(r,i)}`,line:q(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;Ix.has(o.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${o.set}", which has no session pick — globals.${o.set} is set in the config file only, so a click would change nothing; write it with { persist: "${o.set}", … } instead`,line:q(e.source,[`actions`,n,`set`])});let s=Bx.get(o.set);s!==void 0&&hG(e,n,o,s,i)}for(let[n,i]of yG(t.actions,r))`do`in i&&i.do.forEach((r,a)=>{let o=Object.prototype.hasOwnProperty.call(t.actions,r)?t.actions[r]:void 0,s=o===void 0?`references unknown action "${r}"`:`do`in o?`"${r}" is itself a do action — list its members here instead`:i.do.indexOf(r)===a?a>0&&NS(o)?`"${r}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${r}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:q(e.source,[`actions`,n,`do`])})});for(let[n,i]of yG(t.actions,r))if(`run`in i)for(let r of i.refreshes){let i=Object.hasOwn(t.variables,r)?t.variables[r]:void 0;i?.kind!==`source`&&e.issues.push({path:`actions.${n}.refreshes`,message:`actions.${n} refreshes "${r}", which ${i===void 0?`is not declared`:`is a ${i.kind} variable`}: a run refreshes only a declared source (by its full name, <scope>.<plugin>.<source> where the scope is plugins or repo; a plugin names its own sources bare)`,line:q(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of yG(t.actions,r)){let r=`persist`in i?i.persist:`reset`in i?i.reset:null;if(r===null)continue;let a=`persist`in i?`persist`:`reset`,o=YM(r);if(o===null){let t=LM(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${RM().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, a "themeDefaults.<theme>.<shade|variation|style>" target, or a "presets.<name>.root" target`:`actions.${n}: the globals field "${r}" was removed: ${t}`,line:q(e.source,[`actions`,n,a])});continue}let s=JW.filter(e=>e in i);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:q(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){YW(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!mS(t.presets).includes(o.preset)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names preset "${o.preset}" which is not declared (have: ${mS(t.presets).join(`, `)})`,line:q(e.source,[`actions`,n,a])});continue}if(o.scope===`theme-default`&&!e.allowedPalettes.has(o.theme)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names theme "${o.theme}" which is not installed${Wv(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:q(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${Az(o.segment)}`,line:q(e.source,[`actions`,n,a])});continue}`min`in i&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:q(e.source,[`actions`,n,a])})}}for(let[i,a]of yG(t.variables,r)){aG(e,`variables.${i}`,a,n);let t=Bz(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:q(e.source,[`variables`,i])})}for(let[i,a]of yG(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))aG(e,`segments.${i}.vars.${t}`,r,n,i);let r=Zy(a);if(QW(e,i,r),a.partials!==void 0)for(let t of Object.keys(a.partials))Object.hasOwn(n.helpers,t)&&e.issues.push({path:`segments.${i}.partials.${t}`,message:`segments.${i}.partials.${t} reuses the name of a global helper (helpers.${t}) — partials and helpers share one define chain, so pick a name no helper already uses`,line:q(e.source,[`segments`,i,`partials`,t])});let o=a.partials===void 0?n.helpers:{...n.helpers,...a.partials},s=ZW({...n,helpers:o},r);for(let n of lH){let c=a[n];typeof c==`string`&&(fG(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),dG(e,t,`segments.${i}.${n}`,c,q(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of yG(t.variables,r))oG(e,`variables.${i}`,a,n),cG(e,`variables.${i}`,a,t);lG(e,t);for(let[i,a]of yG(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))oG(e,`segments.${i}.vars.${r}`,o,n,i),cG(e,`segments.${i}.vars.${r}`,o,t)}function xG(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=SG(t),a=new Map,o=[];for(let e of r.keys())a.set(e,0);for(let e of r.keys())if(!(!n(e)||a.get(e)!==0)&&s(e))return;function s(t){a.set(t,1),o.push(t);for(let c of r.get(t)??[]){if(!n(c))continue;let t=a.get(c);if(t===1){let t=o.indexOf(c),n=[...o.slice(t),c],r=n[0],a=i.get(r);return e.issues.push({path:a?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:q(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function SG(e){let t=new Map,n=new Map,r=jW(e),i=(e,i,a)=>{t.set(e,{declarationPath:a.join(`.`),linePathParts:a}),n.set(e,new Set(r.ofVariable(i).flatMap(({reaches:e})=>e)))};for(let[t,n]of Object.entries(e.variables))i(t,n,[`variables`,t]);for(let[t,n]of Object.entries(e.segments))for(let[e,r]of Object.entries(n.vars??{}))i(`${t}.${e}`,r,[`segments`,t,`vars`,e]);return{graph:n,nodeInfo:t}}function CG(e,t,n){let r=new Map([...hC(t)].map(([e,,t])=>[e,t]));for(let[t,i]of r){let a=t.split(`.`);for(let o=1;o<a.length;o++){let s=a.slice(0,o).join(`.`),c=r.get(s);if(c===void 0||!(n.checked(t)||n.checked(s)))continue;let[l,u,d]=n.authored(t)?[t,s,i]:[s,t,c],f=n.authored(t)===n.authored(s)?`Rename one so neither name starts with the other.`:`"${u}" is declared outside this file (the bundled default, a plugin, or a control the bar builds), so rename "${l}".`;e.issues.push({path:d.join(`.`),message:`variable "${t}" is declared under the variable "${s}" — a read of ".${t}" would name both, "${t}" and a field of "${s}". ${f}`,line:q(e.source,[...d])})}}}function wG(e){return{...NG,config:Tz(NG.raw,e)}}function TG(e,t,n,r,i){let a=BG(e,t,i,(t,a)=>{let o=ZV(XV(t,e,r.scope,r.home),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>jG(t,n,r,e,i)),s=tH(o,r.beneath.dropped);return{inherited:new Set([...FB(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=nH(Tz(a.raw,o.config),s,(a.raw.insert??[]).map(e=>e.seg));return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(VV)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const EG=new WeakMap;function DG(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e.path,e.scope,kG(e.path)])]),a=EG.get(n)??new Map;EG.set(n,a);let o=JSON.stringify([t.repo,t.checkout?.root??null]),s=a.get(o);if(s?.key===i)return s.layer;let c=ZV(e,t,{config:n,rendering:new Map},(e,t,n)=>jG(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function OG(e,t,n,r){return ZV(e,{repo:null,checkout:n,home:r},{config:t,rendering:new Map},(e,t,n)=>jG(e,t,n,`<plugin install>`,void 0)).dropped}function kG(e){try{let t=l.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function AG(e,t,n,r,i,a=e=>l.readFileSync(e,`utf-8`),o){let s={repo:i.repo,checkout:i.cwd===null?null:nc(i.cwd),home:e.home},c=DH(e,s.repo),u=DG(c.definitions,s,n,o),d={...u,dropped:[...u.dropped,...c.strays]};r.warned(c.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let f=d.config,p=[];for(let{path:e,scope:n}of t){let t=p.at(-1)?.plugins,i=TG(e,a(e),p.at(-1)?.config??f,{...s,scope:n,beneath:{dropped:[...d.dropped,...p.flatMap(e=>e.plugins.dropped)],rendering:t?.rendering??d.rendering}},o);r.warned(i.warnings),p.push({...i,path:e})}let m=new Set(p.flatMap(e=>[...e.plugins.reached])),h=e=>m.has(e.path),g=d.dropped.filter(h),_=d.dropped.filter(e=>!h(e));r.warned(g.map(VV));let v=p.at(-1)?.plugins.rendering??d.rendering,y={checkout:s.checkout,roots:c.roots,loaded:d.loaded,dropped:g,unreached:_,reached:m,rendering:v},b=p.at(-1),x=({warnings:e,...t})=>(r.warned(e),t);if(b===void 0)return{layers:p,base:f,installed:y,...x(PG(wG(f),v,`<default>`,o))};try{return{layers:p,base:f,installed:y,...x(PG(b,v,b.path,o,p.slice(0,-1).reverse()))}}catch(e){for(let[e,t]of p.slice(0,-1).entries())PG(t,t.plugins.rendering,t.path,o,p.slice(0,e).reverse());throw e}}function jG(e,t,n,r,i){if(n){PG(MG(e),new Map,r,i);return}let a=IS(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[],unplaced:[],inherited:[]};if(bG(s,e,yC(e),a),xG(s,e,a),CG(s,e,{checked:a,authored:a}),o.length>0)throw new ib(r,o)}function MG(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const NG={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function PG(e,t,n=`<config>`,r=new Set(qv()),i=[]){let a=CW(e.config.segments,t),o=IG({...e,path:n},i,a),s=(t,s)=>{let c=vS(e.config,t,o.authored);return FG(e,n,r,i,c.config,a,o.dropped,[...c.notices,...s])};try{return s(o.cells,[])}catch(e){if(!(e instanceof ib)||o.cells.length===0)throw e;let t=s([],[]),n=new Set(t.dropped.flatMap(e=>e.issues.map(e=>e.message))),{taken:r,refused:i}=o.cells.reduce((e,t)=>{try{return s([...e.taken,t],[]),{...e,taken:[...e.taken,t]}}catch(r){if(!(r instanceof ib))throw r;let i=r.issues.filter(e=>!n.has(e.message)).map(e=>e.message).join(`; `);return{...e,refused:[...e.refused,yS(t,`${t.relation} "${t.anchor}", but the bar refuses it there: ${i}`)]}}},{taken:[],refused:[]});return s(r,i)}}function FG({raw:e,source:t},n,r,i,a,o,s,c){let l=[],u={source:t,issues:l,allowedPalettes:r,groups:[],unplaced:[],inherited:[]},d=()=>{if(l.length>0)throw new ib(n,[...l,...u.unplaced,...u.inherited],c)};qW(u,a,e,o),xG(u,a),d();let f=RG(n,a.segments,u,o,i,s),p=_W(EW(a),l);d();let m=VR(rR(p)),h=new Set([...hC({variables:e.variables??{},segments:e.segments??{}})].map(([e])=>e));return CG(u,m,{checked:()=>!0,authored:e=>h.has(e)}),d(),{config:m,dropped:f,placed:a,warnings:c}}function IG(e,t,n){let r=[...t].reverse().concat(e),i=TW(e.config,r.flatMap(e=>e.raw.insert??[]),n),a=e=>!i(e.anchor),o=e=>n(e.seg).kind===`declared`,s=e=>wW(n(e.seg)),c=e=>(e.raw.insert??[]).filter(a);return{cells:r.flatMap(e=>c(e).filter(o)),authored:{root:r.some(e=>e.raw.root!==void 0),presets:new Set(r.flatMap(e=>Object.keys(e.raw.presets??{})))},dropped:r.flatMap(t=>{let r=ab(t.source);return(t.raw.insert??[]).filter(s).map(i=>({file:t.path,issue:{path:i.by.entry,message:WW(i.by.entry,i.seg,e.config.segments,n(i.seg)),line:r(i.by.entry.split(`.`))}}))})}}function LG(e){if(e.length>0)throw new kee(e)}function RG(e,t,n,r,i,a){let o=new Map,s=(e,t)=>{o.set(e,[...o.get(e)??[],t])};for(let{file:e,issue:t}of a)s(e,t);for(let t of n.unplaced)s(e,t);for(let{name:a,...o}of n.inherited){let n=i.flatMap(e=>{let t=UW(e.raw,a);return t===void 0?[]:[{layer:e,...t}]})[0];n===void 0?s(e,o):s(n.layer.path,{path:n.path,message:WW(n.layoutKey,a,t,r(a)),line:q(n.layer.source,n.path.split(`.`))})}return[...o].map(([e,t])=>new Oee(e,t))}function zG(e,t,n=new Set(qv()),r=VG){return BG(e,t,n,()=>({inherited:r,layer:null})).raw}function BG(e,t,n,r){let i=HG(e,t),a=Pee(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(qv()),groups:[],unplaced:[],inherited:[]};if(!db(i))throw new ib(e,[{path:``,message:`Config root must be an object, got ${fb(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:GG({...c,issues:[]},i.plugins)??[],db(i.segments)?Object.keys(i.segments):[]),d=UG(c,i,l,XB(e),e);if(s.length>0)throw new ib(e,s,o);return{raw:d,warnings:o,layer:u}}const VG=new Set;function HG(e,t){try{return ua.default.parse(t)}catch(t){let n=t;throw new ib(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function UG(e,t,n,r,i){for(let n of Object.keys(t))WG.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...WG].join(`, `)}`,line:q(e.source,[n])});let a={};return t.globals!==void 0&&(a.globals=jM(e,`globals`,t.globals)),t.variables!==void 0&&(a.variables=Kz(e,`variables`,t.variables)),t.segments!==void 0&&(a.segments=IB(e,t.segments,n)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
|
|
183
183
|
Replace: layout: [["seg1", "seg2"], ["seg3"]]
|
|
184
184
|
With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
|
|
185
|
-
Single-row example: root: { h: ["seg1", "seg2"] }`,line:q(e.source,[`layout`])}),t.root!==void 0&&(a.root=YU(e,`root`,t.root)),t.insert!==void 0&&(a.insert=ZU(e,t.insert,i)),t.actions!==void 0&&(a.actions=YB(e,t.actions,r)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:q(e.source,[`looks`])}),t.styles!==void 0&&(a.styles=xW(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=AM(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=CW(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=PM(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=JB(e,t.helpers)),t.plugins!==void 0&&(a.plugins=KG(e,t.plugins)),aW(e,a),gW(e,a),mN(e,a),nN(e,a,pi,`the global settings menu`),rN(e,a,n),a}const GG=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function KG(e,t){if(Array.isArray(t)&&t.every(e=>typeof e==`string`&&e!==``))return t;e.issues.push({path:`plugins`,message:`"plugins" must be a list of plugin definition paths, got ${fb(t)}`,line:q(e.source,[`plugins`])})}const qG={},JG=gI(`commands.`),YG=SI(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),XG=uI(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),ZG=`{{ ${jN} }}`,QG={min:0,max:100,step:5},$G={warnAt:{label:`warning at %`,domain:QG,default:50},errorAt:{label:`error at %`,domain:{...QG,atLeast:`warnAt`},default:80}};function eK(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:QG,default:80}}}const tK={globals:{palette:`tokyo-night`},variables:{...JG.variables,...Fj,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"effort.level":{kind:`input`,path:`effort.level`,default:``},"effort.glyphs":{kind:`literal`,value:`? `},"glyph.worktree":{kind:`literal`,value:`⊫`},...XG.variables,version:{kind:`input`,path:`version`,default:``},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.tracking":{kind:`input`,path:`git.tracking`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.committedAt":{kind:`input`,path:`git.committedAt`,type:`number`,default:0},"git.timeSinceCommit":{kind:`template`,type:`number`,template:`{{ if gt .git.committedAt 0 }}{{ sub (int (unixEpoch now)) .git.committedAt }}{{ else }}0{{ end }}`},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`template`,type:`number`,template:`{{ etaMinutes .block.nativeUtilization .block.resetsAt 300 }}`},"weekly.etaMinutes":{kind:`template`,type:`number`,template:`{{ etaMinutes .weekly.percentage .weekly.resetsAt 10080 }}`},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``}},segments:{directory:{group:`location`,description:"The main checkout's path, shortened fish-style — `~` under home — plus the subpath and, in a linked worktree, the worktree's name. Click to copy the full path.",template:`{{ $dir := ternary .location.main .current_dir (ne .location.main "") }}{{ if and (ne .home "") (or (eq .home $dir) (hasPrefix (printf "%s/" .home) $dir)) }}{{ $dir = printf "~%s" (trimPrefix .home $dir) }}{{ end }}{{ $text := printf "%s%s" (abbreviatePath $dir) .location.subpath }}{{ if ne .location.worktree "" }}{{ $text = printf "%s (%s %s)" $text .glyph.worktree .location.worktree }}{{ end }}{{ action "copyDir" $text }}`,fg:ZG},model:{group:`model-context`,description:`The active model's display name, followed by the effort gauge (a chevron ladder, climbing on a bubble at max) when an effort level is set.`,template:`✱ {{ formatModelName .model.display_name }}{{ if ne .effort.level "" }} {{ template "effortGauge" . }}{{ end }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{group:`session-tools`,description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{group:`model-context`,description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{group:`location`,description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{group:`location`,description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{group:`git`,description:`The git state: a summary (branch, ahead/behind, S/U/? flags) that the arrow at its right edge expands to every fact — repo, in-progress operation, sha, upstream ±, stash count, time since the last commit.`,template:`{{ if ne .git.branch "" }}{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}{{ end }}{{ if or .location.noRepo ${XG.armed} }}{{ if ne .git.branch "" }} {{ end }}${XG.template}{{ end }}`,fg:ZG,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if eq .git.prState "open" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (eq .git.prState "open") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:iI(``).template},commands:{group:`session-tools`,description:`Type /compact, /model or /clear into this session; /clear asks for a second click. Hidden when not inside tmux.`,template:JG.template,when:JG.when},session:{group:`cost-limits`,description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:eK(0)},today:{group:`cost-limits`,description:`Today's cost and tokens across every session, with a budget warning once a budget is configured.`,template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:eK(50)},block:{group:`cost-limits`,description:`The 5-hour rate-limit block: percent used and time to reset, heating to warning then error.`,template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:$G,when:`{{ gt .block.resetsAt 0 }}`},weekly:{group:`cost-limits`,description:`The weekly rate-limit quota: percent used and time to reset, heating to warning then error.`,template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:$G,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{group:`cost-limits`,description:`Spend per hour, with the projected time to the 5-hour and weekly limits.`,template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 (tint) 0 "error" .settings.errorWithin "warning" .settings.warnWithin (tint) }}`,settings:{errorWithin:{label:`error within (min)`,domain:{min:0,max:300,step:5},default:30},warnWithin:{label:`warning within (min)`,domain:{min:0,max:300,step:5,atLeast:`errorWithin`},default:60}},when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{group:`activity`,description:`Token throughput for the latest exchange: output, input, and total.`,template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{group:`activity`,description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,when:`{{ ne .speed.history "" }}`},cacheTimer:{group:`activity`,description:"Minutes until the prompt cache expires, or `cold` once it has.",template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ readableOn (color (cascade (minutesUntilReset .cache.expiresAt) "0:error" "9:warning" "21:foreground")) (bgOf) ${yv} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:YG.template,bg:YG.bg,when:YG.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...iI(``).actions,...JG.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...XG.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...YG.actions},styles:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},themeDefaults:qG,presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{effortGauge:`{{ \$ord := default 0 (get (dict "low" 1 "medium" 2 "high" 3 "xhigh" 4 "max" 5) .effort.level) }}{{ \$glyphs := compact (splitList " " .effort.glyphs) }}{{ $bubble := readableOn (mix (bgOf) (color "accent") 40) (bgOf) 1.08 }}{{ if eq \$ord 5 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${yv} }}{{ \$climb := frames 1 (index \$glyphs 1) 1 (index \$glyphs 3) 1 (index \$glyphs 4) }}{{ fg \$bubble "" }}{{ bg \$bubble (fg \$climbing \$climb) }}{{ fg \$bubble "" }}{{ else }}{{ fg (ramp $ord "step" 0 (${jN}) 2 (readableOn (color "accent") (bgOf) ${yv})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${yv}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ $age := .git.timeSinceCommit }}{{ if and .settings.age (gt $age 0) }} ◷ {{ template "formatTimeSince" $age }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:CI(`.`),formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatToolTally:`{{ $names := splitList "," . }}{{ range $i, $pair := $names }}{{ if lt $i 2 }}{{ if $i }} {{ end }}{{ $kv := splitList ":" $pair }}{{ index $kv 0 }}{{ if ne (index $kv 1) "1" }}×{{ index $kv 1 }}{{ end }}{{ end }}{{ end }}{{ if gt (len $names) 2 }} +{{ sub (len $names) 2 }}{{ end }}`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},nK=new Set([tK.globals.palette,...Object.keys(tK.themeDefaults),...Object.values(tK.segments).map(e=>e.palette)].filter(e=>e!==void 0)),rK=Ez(BG(`<default>`,JSON.stringify(tK),nK),tK),iK=mS(rK.presets);function aK(e){return iK.includes(e)}const oK=Object.freeze({});function sK(e,t){return e.kind===`decided`?t[e.name]??oK:oK}function cK(e,t){return{...e,...Object.fromEntries(Tx.map(n=>[n,e[n]??t[n]]))}}const lK=(e,t)=>qb(n=>{let{setting:r,on:i,inTmux:a}=Bb[n].switch;return e[r]===i&&(t||!a)});function uK(e,t,n,r){let i=Dx(e);return Kv(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function dK(e,t){return hS(t(`preset`),e.globals.preset,e.presets)}function fK(e,t,n){let r=dK(e,t),i=bS(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Yx(a.palette,t(`theme`),i.palette),s=cK(i,sK(o,e.themeDefaults));return{...Object.fromEntries(Cx.map(e=>[e,uK(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:iy(a.style,t(`style`),s.style,e.styles),effect:my(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function pK(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?Cy:wy;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const mK=Object.entries(Mx),hK=new Set(Px.map(e=>e.sessionKey)),gK=()=>!1;function _K(e,t){return fK(e,e=>hK.has(e)?t(e):null,gK)}const vK=[`preset`,`theme`];function yK(e,t,n){let r=new Set(vK.slice(0,n).map(e=>Mx[e].sessionKey));return fK(e,e=>r.has(e)?t(e):null,gK)}function bK(e,t){let n=Array.from({length:vK.length+1},(n,r)=>yK(e,t,r));return e=>{let t=vK.indexOf(e);return n[t===-1?vK.length:t]}}function xK(e,t,n,r){return e.flatMap(([e,i])=>{let a=pK(t,e);return a===null||a===pK(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function SK(e,t,n){return pK(_K(e,t),n)}function CK(e,t){let n=_K(e,t);return xK(mK,n,bK(e,t),t=>wK(e,n.preset,t.configKey))}function wK(e,t,n){return n in(gS(e.presets,t).globals??{})?JM(t,n):n}function TK(e,t,n){let r=hS(t(Mx.preset.sessionKey),e.globals.preset,e.presets),i=YM(n);return{key:i?.scope===`globals`?wK(e,r,i.field):n,globals:bS(e,r)}}function EK(e,t){let{preset:n}=_K(e,t);return kK(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:nb(a,s);return c===void 0||tb(c)===tb(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function DK(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return mS(e.presets).flatMap(n=>{let i=kK(e,n);return[...new Set(i.filter(e=>r.has(e.key)).map(e=>e.id))].flatMap(e=>{let n=i.filter(t=>t.id===e);return $y(Object.fromEntries(n.map(e=>[e.setting,e.decl])),Object.fromEntries(n.map(e=>{let n=r.get(e.key)??t(e.key),i=n===null?void 0:nb(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const OK=new WeakMap;function kK(e,t){let n=OK.get(e)??new Map;OK.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...Fy(_S(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Zy(e.segments[t.name])[n];return{id:r,setting:n,key:i,decl:a,saved:t.settings?.[n]??a.default}})),a=[...new Map(i.map(e=>[e.key,e])).values()];return n.set(t,a),a}function AK(e,t){let n=_K(e,t);return{from:n.preset,globals:gS(e.presets,n.preset).globals??{},picks:xK(mK.filter(([e])=>e!==`preset`),n,bK(e,t),e=>e.configKey),placements:EK(e,t)}}function jK(e,t){return fK({...e,globals:{palette:t},presets:{}},()=>null,gK)}function MK(e,t){let n=_K(e,t),r=pK(n,`theme`);if(r===null)return{kind:`rule`};let i=jK(e,r),a=bS(e,n.preset),o=Object.fromEntries(Tx.map(e=>[e,pK(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:Tx.some(e=>o[e]!==pK(i,e))}}function NK(e){return{sessionKeys:Px.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...EM(e)?iK.map(t=>JM(t,e)):[],...qM(e)?qv().map(t=>KM(t,e)):[]]}}function PK(e){return new Set(Px.map(e=>e.configKey).filter(t=>NK(t).fileKeys.some(t=>LK(e,IK(t)))))}function FK(e,t,n){let r=CK(e,n),i=new Set(r.map(e=>e.configKey)),a=zx(e=>i.has(Mx[e].configKey)||t.has(Mx[e].configKey)),o=MK(e,n);return{unsaved:r.length+EK(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function IK(e){let t=YM(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return XM(t)}function LK(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&LK(e[n],r)}function RK(e,t,n){let r=Bx.get(n);if(r!==void 0)return SK(e,t,r);for(let[,t]of qy(e))if(t.key===n)return t.default??null;return null}function zK(e,t){let n=BM(e).get(t);return n===void 0?null:String(n)}const BK={inside:()=>[],defaultOf:()=>Yr,menus:[]},VK=e=>`${e.key}\0${e.member}`;function HK(e){let t=new Map,n=n=>{let r=`${n.name}\0${jy(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:pW(a,jy(n));return t.set(r,o),o},r=e=>[...e.opens===void 0?[]:[e.opens.ref],...n(e)],i=new Map,a=new Map;for(let t of Object.values(e.variables))t.kind===`state`&&(t.default!==void 0&&i.set(t.key,t.default),t.within!==void 0&&a.set(t.key,t.within));let o=new Map,s=new Map,c=new Map,l=e=>{s.set(e.key,(s.get(e.key)??new Set).add(e.member))},u=(e,t)=>{let n=o.get(VK(e))??new Map;n.set(VK(t),t),o.set(VK(e),n)},d=(e,t)=>{if(e.kind===`container`){for(let n of e.children)d(n,t);return}for(let n of r(e)){l(n),c.set(VK(n),n);for(let e of t)u(e,n)}e.opens!==void 0&&d(e.opens.body,[...t,e.opens.ref])};for(let t of mS(e.presets))d(_S(e,t).node,[]);for(let t of Object.values(e.actions)){let e=ci(t);e!==void 0&&l(e)}for(let[e,t]of a)for(let n of s.get(e)??[])for(let r of t)u(r,{key:e,member:n});let f=new Map;return{inside:e=>{let t=f.get(VK(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(VK(e))??[])n.has(t)||(n.set(t,i),r(i))};r(e);let i=new Map;for(let{key:e,member:t}of n.values())i.set(e,(i.get(e)??new Set).add(t));let a=[...i].map(([e,t])=>({key:e,outside:new Set([...s.get(e)].filter(e=>!t.has(e)))}));return f.set(VK(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const UK=new WeakMap;function WK(e){let t=UK.get(e);if(t!==void 0)return t;let n=HK(e);return UK.set(e,n),n}function GK(e,t,n){let r=new Set(n.map(e=>e.key)),i=n=>t(n)??e.defaultOf(n),a=new Set;for(let{key:t,value:o}of n){let n=i(t);if(n!==o)for(let o of e.inside({key:t,member:n})){let t=i(o.key);t!==e.defaultOf(o.key)&&!o.outside.has(t)&&!r.has(o.key)&&a.add(o.key)}}return[...a]}function KK(e,t){let n=({key:n,member:r})=>(t(n)??e.defaultOf(n))===r,r=(t,n)=>e.inside(n).some(({key:e,outside:n})=>e===t.key&&!n.has(t.member));return e.menus.filter(n).filter(t=>{let i=e.menus.filter(e=>e!==t&&r(t,e)),a=i.length>0&&e.defaultOf(t.key)===t.member;return!i.some(n)&&!a})}function qK(e,t,n){let r=(r,i,a)=>{let o=GK(t(r),t=>e.get(r,t),i);(0,Y.runInAction)(()=>{a();for(let t of o)e.clear(r,t)}),o.length>0&&n(`close-nested: folded=${o.join(`,`)} (session=${r})`)},i=(t,n)=>r(t,n,()=>e.setBatch(t,n));return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(e,t,n)=>i(e,[{key:t,value:n}]),setBatch:i,clear:(n,i)=>r(n,[{key:i,value:t(n).defaultOf(i)}],()=>e.clear(n,i))}}const JK=`render-origin`,YK=`client-hints`,XK=`config-override`;var Z=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}},ZK=class extends Error{constructor(e){super(`the daemon closed: ${e} refused`),this.name=`DaemonClosing`}},QK=class extends Error{constructor(e){super(`the client left: ${e} not run`),this.name=`ClickAbandoned`}};function $K(e){try{return e()}catch(e){throw e instanceof URIError?new Z(`malformed wire encoding: ${e.message}`):e}}const eq=new Set([`1`,`true`]),tq=new Set([`0`,`false`,``]);function nq(e,t){let n=Dq(e),r=n.scope===`segment-palette`?`string`:kx(n.field);if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if(eq.has(t))return`true`;if(tq.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function rq(e){try{return l.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function iq(e,t,n){try{if(t===null){l.rmSync(cn(e),{force:!0});return}sn(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function aq(e){return/^\s*$/.test(e)?null:_a(e)}function oq(e,t){return e!==null&&ya(e,t)!==void 0}function sq(e){if(e.kind===`segment`)return e.when===void 0?e.name:{seg:e.name,when:e.when};if(e.kind===`container`){let{kind:t,direction:n,children:r,...i}=e;return{[n===`horizontal`?`h`:`v`]:r.map(sq),...i}}return e}function cq(e){if(!eS(e))return sq(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,sq(t)])),...n}}const lq=tK,uq=lq.segments,dq=lq.presets,fq=lq.root;function pq(e,t,n,r){if(!oq(e,t)&&n===void 0)throw new Z(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function mq(e,t){let n=XM(t);return t.scope===`segment-palette`&&pq(e,[`segments`,t.segment],uq[t.segment],n.join(`.`)),n}function hq(e){return _a(Da(e))}function gq(){return Object.entries(fq.rows).map(([e,t])=>{let n=sq(t);return{path:[`root`],fragment:hq({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function _q(e,t){let n=e===null?void 0:ya(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function vq(e,t){if(t===void 0)return null;let n=cq(t);return{path:e,fragment:hq(n),unit:{path:e,value:n}}}function yq(e,t){let n=[`presets`,t],r=[...n,`root`],i=dq[t];pq(e,n,i,r.join(`.`));let a=_q(e,r)??vq(r,i?.root);return a!==null&&Ja(a.fragment)?a:null}function bq(e,t){let n=qa(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function xq(e,t){return[...gq(),_q(e,[`root`]),yq(e,t)].filter(e=>e!==null).reduce(bq,new Map)}function Sq(e,t,n){for(let{node:r,...i}of xq(e,t).values())if(Xa(r,n))return i;throw new Z(`${Cq(e,t).join(`.`)} holds no placement "${n}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`)}function Cq(e,t){return yq(e,t)?.path??[`root`]}function wq(e,t){return t.scope===`preset-root`?Cq(e,t.preset):XM(t)}function Tq(e,{unit:t}){return t===null?e:Va(e,t.path,Da(t.value),Ta)}function Eq(e){let t=YM(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function Dq(e){let t=Eq(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function Oq(e,t,n,r,i){let a=zq(t,r),o,s=()=>(o??={chain:Nq(t,n)}).chain;Bq(t,s,a),i(t,s,a),iq(t.path,r,e.logger),e.record(t.path,n,r)}function kq(e,t,n){let r=Mq(e,t(),n);if(r.length>0)throw new Z(`refused: ${e.above.map(e=>e.path).join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const Aq=()=>{};function jq(e,t){try{return t()}catch(t){throw!(t instanceof Z)||e.above.length===0?t:new Z(`${t.message} — or it is declared by ${e.above.map(e=>e.path).join(`, `)}, which the bar does not edit`)}}function Mq(e,t,n){if(t===null)return[];let r=new Set(Lq(Iq(t),Iq(n)));return Lq(Fq(e,t),Fq(e,n)).filter(e=>!r.has(e))}function Nq(e,t){try{return Pq(e,t)}catch(e){if(e instanceof ib)return null;throw e}}function Pq(e,t){return jG(e.locs,t===null?e.above:[WH(e.path),...e.above],rK,{warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:l.readFileSync(n,`utf8`))}function Fq(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function Iq(e){return e.layers.at(-1)?.config??e.base}function Lq(e,t,n=``){return!Rq(e)||!Rq(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>Lq(e[r],t[r],n===``?r:`${n}.${r}`))}function Rq(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zq(e,t){try{return Pq(e,t)}catch(e){throw e instanceof ib?new Z(`refused: the config file would not load after this click — ${e.message}`):e}}function Bq(e,t,n){if(n.dropped.length===0)return;let r=t();if(r===null)return;let i=e=>e.dropped.flatMap(e=>e.issues.map(t=>({file:e.file,issue:t}))),a=new Set(i(r).map(({file:e,issue:t})=>`${e}\0${t.message}`)),o=i(n).filter(({file:e,issue:t})=>!a.has(`${e}\0${t.message}`));if(o.length>0)throw new Z(`refused: this click would leave a placement of a segment nothing declares — ${o.map(({file:e,issue:t})=>new ib(e,[t]).message).join(`
|
|
186
|
-
`)}`)}function Vq(e,t){let n=Dq(t),r=aq(rq(e)??``),i=r===null?void 0:ya(r,XM(n));return i!==void 0&&`value`in i?i.value:void 0}function Hq(e,t,n){Uq(e,t,n,[])}function Uq(e,t,n,r){let i=rq(t.path),a=n.reduce((e,[t,n])=>Va(e,mq(aq(e),Dq(t)),nq(t,n),Ta),i??``);Oq(e,t,i,jq(t,()=>Wq(a,t.path,r,e=>e)),kq)}function Wq(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=Sq(aq(s),n,i),l=eo(Tq(s,c),c.path,i,a,Da(o));if(l===null)throw new Z(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function Gq(e,t,n){let r=aq(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of xq(r,t)){if(!Xa(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?xa(e,c):Da(s.value);if(a!==`#`)return Va(e,[...i,`rows`,a],l,Ta);if(yq(r,t)!==null)throw new Z(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return Va(e,i,l,Ta)}return e}function Kq(e,t){return Ua(e,t,t[0]===`presets`&&t.length>2&&!aK(t[1])?2:0)}function qq(e,t,n){let r=n.map(Eq),i=rq(t.path);if(i===null)return;let a=r.reduce((e,t)=>Kq(e,wq(aq(e),t)),i);a!==i&&Oq(e,t,i,a,Aq)}function Jq(e){let t=e===null?void 0:ya(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function Yq(e,t){let n=new Set([...iK,...Jq(e),...t.above.flatMap(e=>Object.keys(ua.default.parse(l.readFileSync(e.path,`utf8`)).presets??{}))].map(Hj));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(Hj(e)))}function Xq(e,t,n,r,i,a){let o=rq(t.path),s=aq(o??``),c=Yq(s,t),l=[`presets`,c],u=jq(t,()=>yq(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?xa(o??``,u.fragment):Da(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Da(r)]]],f=i.map(([e,t])=>{let n=JM(c,e);return[mq(s,Dq(n)),nq(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Va(e,t,n,Ta),Va(o??``,l,`{}`,Ta));return Oq(e,t,o,jq(t,()=>Wq(p,t.path,a.map(e=>({...e,preset:c})),Gq)),kq),c}function Zq(e,t,n,r){let i=rq(t.path);Oq(e,t,i,Va(i??``,[`themeDefaults`,n],Da(r),Ta),kq)}function Qq(e,t,n){if(aK(n))throw new Z(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=rq(t.path),a=aq(i??``);if(i===null||a===null||ya(a,r)===void 0)throw new Z(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=ya(a,[`globals`,`preset`]);Oq(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>Kq(e,t),i),Aq)}function $q(e,t,n,r){let i=Eq(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=rq(t.path),o=r.op===`remove`?r.target:r.anchor,s=jq(t,()=>Sq(aq(a??``),i.preset,o)),c=Tq(a??``,s),{after:l,placed:u}=eJ(c,s.path,r,()=>{let e=zq(t,c).config;return mS(e.presets).map(t=>_S(e,t).node)});if(l===null)throw new Z(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return Oq(e,t,a,l,kq),u}function eJ(e,t,n,r){switch(n.op){case`remove`:return{after:Qa(e,t,n.target),placed:null};case`insert`:{let i=GR(n.segment,n.anchor,r());return{after:$a(e,t,i,n.anchor,n.relation),placed:i}}}}function tJ(e,t,n){let r=(r,i,a)=>{let o=i.filter(t).map(t=>({key:t,before:e.get(r,t)}));a();for(let{key:t,before:i}of o)n(r,t,i,e.get(r,t))};return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(t,n,i)=>r(t,[n],()=>e.set(t,n,i)),setBatch:(t,n)=>r(t,n.map(e=>e.key),()=>e.setBatch(t,n)),clear:(t,n)=>r(t,[n],()=>e.clear(t,n))}}const nJ={load:()=>({}),save:()=>{},flush:()=>{}};var rJ=class{sessions;storage;head=0;atom=(0,Y.createAtom)(`SessionState`);constructor(e=nJ,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}observers(){return this.atom.observers_?.size??0}latestRevision(){return this.head}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,Y.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t.some(({key:e,value:t})=>n.values.get(e)!==t)&&(n.revision=++this.head);for(let{key:e,value:r}of t)n.values.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,Y.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.values.delete(t)&&(n.revision=++this.head),n.values.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,Y.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}close(){this.flush(),this.storage=nJ}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};const iJ={load:()=>({}),save:()=>{}},aJ=new Set(Px.map(e=>e.sessionKey)),oJ=e=>aJ.has(e)||e.startsWith(cN),sJ=8*1024*1024,cJ={past:[],future:[]},lJ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var uJ=class{held=Y.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,Y.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=iJ){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??cJ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??cJ}begin(){let e=new Map,t=!1,n=(n,r)=>{t=!0;let i=e.get(n)??new Map,a=i.get(lJ(r));i.set(lJ(r),a===void 0?r:{...r,before:a.before}),e.set(n,i)},r=new Map;return{sessionState:tJ(this.sessionState,()=>!0,(e,i,a,o)=>{if(t=!0,!(!oJ(i)&&i!==`edit.mode`)){if(i===`edit.mode`){let t=r.get(e);r.set(e,{before:t===void 0?a:t.before,after:o});return}n(e,{kind:`session`,key:i,before:a,after:o})}}),file:(e,t,r,i)=>n(e,{kind:`file`,file:t,before:r,after:i}),wrote:()=>{t=!0},written:()=>t,commit:()=>{let t=new Map(e),n=new Map(r);e.clear(),r.clear();for(let e of new Set([...t.keys(),...n.keys()])){let r=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=r.length===0?i:vJ(i,r),o=n.get(e),s=o===void 0?a:SJ(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new Z(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,bJ(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new Z(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(lJ)),a=n.net.filter(e=>!i.has(lJ(e))),o=pJ(CJ(xJ(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new Z(`rewind: ${r.map(TJ).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new Z(`redo: nothing to redo`);let a=[...n,i],o=pJ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...hJ(t.savepoint,a.length-o.length,i)}),i}apply(e,t,n,r,i){let a=n===`before`?`after`:`before`,o=t.filter(t=>this.read(e,t)!==t[a]);if(o.length>0){let t=new Set(o.map(lJ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:CJ(n,t),future:CJ(i,t),...a!==void 0&&{savepoint:{at:CJ([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(lJ(e))),below:CJ(a.below,t)}}}),new Z(`${r}: ${o.map(TJ).join(`, `)} changed since that edit — refusing to overwrite it; this session's undo history no longer steps it`)}let s=[];try{for(let r of t)this.write(e,r,r[n]),s.push(r);this.put(e,i)}catch(t){try{for(let t of s.reverse())this.write(e,t,t[a])}catch(e){throw Error(`${t.message}; and putting the step back failed, so it is half-applied: ${e.message}`)}throw t}}read(e,t){return t.kind===`session`?this.sessionState.get(e,t.key):rq(t.file)}write(e,t,n){t.kind===`file`?iq(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||dJ(n)>sJ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,fJ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${sJ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function dJ(e){let t=0;for(let{past:n,future:r,savepoint:i}of e.values())for(let e of[...n,...r,...i===void 0?[]:[i.net,...i.below]])for(let n of e)t+=(n.before?.length??0)+(n.after?.length??0);return t}function fJ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...hJ(n,1,[])}:{past:e,future:t.slice(1),...hJ(n,0,[])}}function pJ(e){return e.slice(-50)}const mJ=e=>e===uN.member;function hJ(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:gJ(e.net,n),below:e.below}}}function gJ(e,t){let n=new Map(e.map(e=>[lJ(e),e]));for(let e of t){let t=n.get(lJ(e));n.set(lJ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const _J=e=>e.map(e=>({...e,before:e.after,after:e.before}));function vJ(e,t){let n=[...e.past,t],r=pJ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...hJ(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...yJ(e.future,a),...i.below]},n.length-r.length,t)}}function yJ(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function bJ(e,t){return{past:e.past.slice(0,-1),future:pJ([...e.future,t]),...hJ(e.savepoint,0,_J(t))}}function xJ(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...yJ(r,t.at-i.length),...t.below]}function SJ(e,t){if(mJ(t.after)&&!mJ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!mJ(t.after)&&mJ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function CJ(e,t){return e.map(e=>e.filter(e=>!t.has(lJ(e)))).filter(e=>e.length>0)}function wJ(e){return e.map(TJ).join(`, `)}function TJ(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function EJ(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function DJ(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(EJ))}function OJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(EJ)&&DJ(t.below)}function kJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return DJ(t.past)&&DJ(t.future)&&(t.savepoint===void 0||OJ(t.savepoint))}function AJ(e,t){let n=e=>e.kind===`file`||oJ(e.key)?!0:(t.add(e.key),!1),r=e=>e.map(e=>e.filter(n)).filter(e=>e.length>0),{savepoint:i}=e,a=r(e.past),o=r(e.future);return i===void 0?{past:a,future:o}:{past:a,future:o,savepoint:{at:r(e.past.slice(0,i.at)).length,net:i.net.filter(n),below:r(i.below)}}}function jJ(e,t){return{load:()=>{let n;try{n=l.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(kJ)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,AJ(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{l.mkdirSync(E.dirname(e),{recursive:!0}),sn(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const MJ=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function NJ(e){return{...Object.fromEntries(MJ.map(e=>[e,void 0])),CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir,...e.claudeConfigDir!==void 0&&{CLAUDE_CONFIG_DIR:e.claudeConfigDir}}}const PJ=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function FJ(e){let t=e=>({kind:`failed`,reason:e});if(!PJ(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!PJ(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!cF.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${cF.join(` or `)}`)}return{kind:`ok`,value:e}}function IJ(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const LJ=e=>$H(e,`doctor-marks.json`,{},FJ),RJ=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},zJ=(e,t)=>e.includes(t)?e:[...e,t],BJ=e=>$H(e,`doctor-clicked-terminals.json`,[],RJ);var VJ=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const HJ=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},UJ=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),WJ=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=UJ(e,t);return r===void 0?n:r.projectDir},GJ=(e,t)=>UJ(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function KJ(e){let t=new Map;for(let n of e.split(`
|
|
187
|
-
`)){let e=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(n);if(e===null)continue;let r=Number(e[1]);t.set(r,{pid:r,ppid:Number(e[2]),command:e[3].trim()})}return t}function*
|
|
188
|
-
`,1)[0]??``}function
|
|
189
|
-
`)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function
|
|
190
|
-
`)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?I:F(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=F(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=F({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function
|
|
191
|
-
`).length:0)}async getRemotesAsync(e){let t=DY(E.join(this.resolveCommonGitDir(this.resolveGitDir(e)),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){return pY(await this.execGitAsync(fY,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=_Y(e);return(n===null?null:yY(n))??E.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=vY(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return this.launcher.launch({bin:e,args:[...t],cwd:n.cwd,timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=dY(t);return n===`github`?SY(`gh pr view`,await this.execForgeAsync(oY.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,TY):n===`gitlab`?SY(`glab mr view`,await this.execForgeAsync(oY.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,EY):I}isWorktree(e){try{let t=E.join(e,`.git`);return!!(l.existsSync(t)&&l.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){k(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=tY(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F(wY(t.value)):t}};function kY(e){return Math.max(1,e-2)}function AY(){return Y.observable.box(jY(`unread`),{deep:!1})}function jY(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function MY(e,t){let n=e.reading.get();n.kind===`read`&&(0,Y.compareStructural)(n.outcome,t)||((0,Y.runInAction)(()=>e.reading.set({kind:`read`,outcome:t})),n.kind===`pending`&&n.land())}function NY(e,t){let n=e.reading.get();n.kind===`read`?(0,Y.runInAction)(()=>e.reading.set(jY(t))):n.why!==t&&t===`unread`&&(0,Y.runInAction)(()=>e.reading.set({...n,why:t}))}function PY(e,t){e.reading.get().kind===`pending`&&MY(e,t)}function FY(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function IY(e){let t=e.reading.get();return t.kind===`read`?t.outcome:t}async function LY(e){for(;;){let t=e();if(!FY(t))return t;await t.landed}}function RY(e,t,n,r){let i=new AbortController,a=r(Math.max(0,t),()=>i.abort());return new Promise((t,r)=>{i.signal.addEventListener(`abort`,()=>t(`deadline`)),e(i.signal).then(()=>t(`answered`),e=>i.signal.aborted?n(e):r(e))}).finally(()=>{a(),i.abort()})}function zY(e){return{current:()=>e}}function BY(e){return LY(()=>e.current())}function VY(e,t,n){return xt({dir:e.project_dir,env:n===void 0?[]:[[So,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function HY(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function UY(e){return{...Object.fromEntries(Cx.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:aK(e.preset)}}}const WY={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function GY(e,t){if(!t)return`-`;if(ro(e))return`pending`;let{prState:n,prError:r,prEarlier:i}=e??{};return ro(n)?`pending`:n===void 0?r===void 0?i===void 0?`-`:`earlier-${String(i)}`:`failed`:n}const KY=10*1e3;function qY(e,t){if(!(t<60))return e*3600/t}function JY(e,t,n,r){let i=r-t;if(i<50||i>KY)return;let a=n-e;if(!(a<=0))return a*1e3/i}function YY(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=JY(t.input,t.atMs,n.input,n.atMs),i=JY(t.output,t.atMs,n.output,n.atMs),a=JY(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function XY(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>KY)continue;let o=JY(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function ZY(e,t){let n=bS(e,t),r=[...Qv.flatMap(e=>{let t=n[e];return $v(t)?[t]:[]})];for(let n of Fy(_S(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...QY(e,n.name));return eX(e,r)}function QY(e,t){let n=e.segments[t];return n?[...[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]),...Object.values(n.partials??{})]:[]}function $Y(e,t,n){return eX(e,[...QY(e,t),...n])}function eX(e,t){let n=MW(e),r=new Map(gC(e)),i=t.flatMap(e=>n.ofTemplate(e).flatMap(({reaches:e})=>e)),a=new Set,o=new Set;for(;i.length>0;){let e=i.pop();if(a.has(e))continue;a.add(e);let t=r.get(e),s=AW(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function tX(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=ZY(e,n);return t.set(n,i),i}}function nX(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function rX(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.committedAt`)&&{showCommittedAt:!0},...Object.keys(WY).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const iX=new WeakMap;function aX(e){let t=iX.get(e);return t===void 0&&(t=oX(e),iX.set(e,t)),t}function oX(e){let t=t=>nX(e,t);return{git:t(`git`),session:t(`session.cost`)||t(`session.tokens`)||t(`burn`),today:t(`today`),context:t(`context`)||t(`autocompact`),metrics:t(`metrics`)||t(`burn`),burn:t(`burn`),activity:t(`activity`),tmux:t(`tmux.session`),hostName:t(`host.name`),hostUser:t(`host.user`),cache:t(`cache`),speed:t(`speed`),autocompact:t(`autocompact`),block:t(`block`)}}function sX(e){return kY(e.termCols??120)}function cX(e,t){return To(wo(e.claudeConfigDir,t))}function lX(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function uX(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=aX(e.neededInputPaths),s=r.session_id,c=i.usageStore.request(s,r.transcript_path),l=async(e,t,r)=>{if(!t)return;let a=i.clock.monotonic();n.set(e,null);let o=null;try{await r()}catch(t){i.log(`error`,`${e} lane threw: ${C(t)}`),o=`${e}: ${String(t)}`}n.set(e,Math.round(i.clock.monotonic()-a)),i.faults.refreshed(s,e,o)};await Promise.all([l(`session`,o.session,()=>c.usage(r)),l(`today`,o.today,()=>c.today(i.lanes().today)),l(`context`,o.context,()=>i.contextProvider.getContextInfo(r)),l(`metrics`,o.metrics,()=>i.metricsProvider.getMetricsInfo(s,r)),l(`activity`,o.activity,()=>i.activityProvider.getActivityInfo(s,r)),l(`cache`,o.cache,()=>i.cacheExpiry.refresh(s,r.transcript_path)),l(`speed`,o.speed,()=>c.speed(RA(t).getTime())),l(`autocompact`,o.autocompact,async()=>i.autoCompact.window(cX(a,i.home)))])}function dX(e,t){return[...t.keys()].filter(t=>e.has(t))}function fX(e,t){let n=zY(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function pX({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,rX(n),t.workspace?.project_dir]}function mX(e,t,n,r,i){let a=aX(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return zY(I);try{return n()}catch(t){return s.push(`${e}: ${C(t)}`),zY(L(`${e}: ${String(t)}`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...pX(n,r))),tmux:c(`tmux`,a.tmux&&o!==null,()=>e.tmuxService.declare(t,o)),hostName:c(`host.name`,a.hostName,()=>e.hostService.declareName(t)),hostUser:c(`host.user`,a.hostUser,()=>e.hostService.declareUser(t)),today:c(`today`,a.today,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map(dX(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function hX(e){let{hookData:t,deps:n}=e,r=aX(e.neededInputPaths),i=t.session_id,a=n.lanes(),o=(e,t,r)=>{if(!t)return I;let a=n.faults.of(i,e);if(a!==void 0)return a;try{return r()}catch(t){return n.log(`error`,`${e} read threw: ${C(t)}`),L(`${e}: ${String(t)}`)}};return{git:a.git.current(),usage:o(`session`,r.session,()=>n.usageStore.usageOf(i,t)),context:o(`context`,r.context,()=>n.contextProvider.contextOf(t)),metrics:o(`metrics`,r.metrics,()=>n.metricsProvider.metricsOf(i,t)),activity:o(`activity`,r.activity,()=>n.activityProvider.activityOf(i)),tmuxSession:a.tmux.current(),hostName:a.hostName.current(),hostUser:a.hostUser.current(),cache:o(`cache`,r.cache,()=>n.cacheExpiry.expiryOf(i)),speed:o(`speed`,r.speed,()=>n.usageStore.speedOf(i)),autoCompact:o(`autocompact`,r.autocompact,()=>n.autoCompact.stored(cX(e.hints,n.home))),sources:new Map([...a.sources].map(([e,t])=>[e,t.current()]))}}function gX(e){let t=e.git.current(),n=t.kind===`ok`?t.value.pullRequest:void 0;return[t,e.tmux.current(),e.hostName.current(),e.hostUser.current(),e.today.current(),...[...e.sources.values()].map(e=>e.current()),...n===void 0?[]:[n]].flatMap(e=>e.kind===`pending`&&e.why===`unread`?[e.landed]:[])}function _X(e,t,n){let{hookData:r,hints:i}=e,{effective:a,configFacts:o}=t,{configPath:s,...c}=o,l=aX(e.neededInputPaths),u=(e,t)=>{switch(e.kind){case`pending`:return no;case`failed`:case`absent`:return;case`ok`:return t(e.value)}},d=e=>e.kind===`ok`?e.value:void 0,f=i.tmux??null,p=n.git.kind===`pending`?no:AX(n.git,()=>no),m=n.tmuxSession.kind===`pending`?no:d(n.tmuxSession),h=n.hostName.kind===`pending`?no:d(n.hostName),g=n.hostUser.kind===`pending`?no:d(n.hostUser),_=n.autoCompact.kind===`pending`||l.autocompact&&n.context.kind===`pending`?no:TX(n.autoCompact,d(n.context)?.maxTokens),v=r.rate_limits?.five_hour,y=r.rate_limits?.seven_day,b=l.burn?n.usage.kind===`pending`||n.metrics.kind===`pending`?no:bX(d(n.usage)?.session.cost,d(n.metrics)?.sessionDuration):void 0,x=u(n.speed,xX),S=u(n.usage,e=>OX({cost:e.session.cost,tokens:e.session.tokens})),C=u(n.metrics,e=>OX({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),w=u(n.activity,EX),ee=u(n.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),T=u(n.cache,e=>({expiresAt:e})),te=kX(e.deps.home),E=r.workspace?{...r.workspace,current_dir:kX(r.workspace.current_dir)??``,project_dir:kX(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>kX(e)??e)}:r.workspace,ne=r.session_id;return{...r,...E!==void 0&&{workspace:E},...te!==void 0&&{home:te},...p!==void 0&&{git:p},...r.location!==void 0&&{location:{...r.location,main:kX(r.location.main)??``}},...f!==null&&{tmux:{pane:f.pane,...m!==void 0&&{session:m}}},host:{...h!==void 0&&{name:h},...g!==void 0&&{user:g},...i.ssh!==void 0&&{ssh:i.ssh}},...UY(a),history:t.history,navigation:{back:t.back},term:{cols:sX(i)},...c,...s!==null&&{configPath:s},resumeCommand:VY(E,ne,i.claudeConfigDir),...S!==void 0&&{session:S},...b!==void 0&&{burn:b},...x!==void 0&&{speed:x},...l.block&&v!==void 0&&{block:{nativeUtilization:v.used_percentage,resetsAt:v.resets_at}},...y!==void 0&&{weekly:{percentage:y.used_percentage,resetsAt:y.resets_at}},...T!==void 0&&{cache:T},...ee!==void 0&&{context:ee},...C!==void 0&&{metrics:C},...w!==void 0&&{activity:w},..._!==void 0&&{autocompact:_},...yX(n.sources.keys(),e=>{let t=n.sources.get(e);return t.kind===`pending`?no:t})}}function vX(e){return{sources:String(e.size),sourcesPending:[...e].flatMap(([e,t])=>{let n=t.current();return n.kind===`pending`?[`${e}:${n.why}`]:[]}).join(`,`)||`-`}}function yX(e,t){let n=Object.fromEntries(PS.map(e=>[e,{}]));for(let r of e){let e=r.split(`.`),i=e.pop(),a=e.reduce((e,t)=>e[t]??={},n);a[i]=t(r)}return n}function bX(e,t){let n=e!=null&&t!=null?qY(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function xX(e){let t=YY(e),n=XY(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function SX(e,t){return _X(e,t,hX(e))}function CX({usageStore:e,faults:t,log:n},r,i,a){if(t.of(i.session_id,`today`)!==void 0)return;let o=r.current();if(o.kind===`pending`)return no;if(o.kind!==`ok`)return;let s=(()=>{try{return e.todayAt(o.value,i,a)}catch(e){return n(`error`,`today read threw: ${C(e)}`),I}})();return s.kind===`pending`?no:s.kind===`ok`?{cost:s.value.cost,tokens:s.value.tokens}:void 0}async function wX(e,t,n){await uX(e,t,n),await LY(()=>{let t=gX(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function TX(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return xI(e.value,t)}}function EX(e){let t=e.todos.findIndex(e=>e.active),n=e.todos.length===0?void 0:{total:e.todos.length,completed:e.todos.filter(e=>e.done).length,...t>=0&&{position:t+1,active:e.todos[t].text}},r=DX(e.running),i=DX(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}};if(!(e.command===null&&n===void 0&&a===void 0))return{...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function DX(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function OX(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function kX(e){return e===void 0||e.length===0||E.sep!==`\\`?e:e.replace(/\\/g,`/`)}function AX(e,t){if(e.kind!==`ok`)return;let n=e.value,r=e=>e?.kind===`ok`?e.value:void 0,i=r(n.aheadBehind),a=r(n.sha),o=r(n.operation),s=r(n.committedAt),c=r(n.stashCount),l=r(n.upstream),u=n.upstream===void 0?void 0:r(JJ(n.upstream,n.aheadBehind)),d=r(n.repoName),f=r(n.repoUrl),p=n.pullRequest===void 0?void 0:n.pullRequest.kind===`pending`?n.pullRequest:YJ(n.pullRequest,n.head),m={};switch(p?.kind){case`pending`:{let e=t(`git.pr`);m={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:m={prNumber:p.value.number,prState:p.value.state,prUrl:p.value.url};break;case`failed`:m={prError:p.reason};break;case`earlier`:m={prEarlier:p.value.state};break;case`absent`:case void 0:break}return{branch:n.branch,status:n.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{committedAt:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{tracking:u},...d!==void 0&&{repoName:d},...f!==void 0&&{repoUrl:f},...m}}const jX={pullRequests:e=>rX(e).showPullRequest===!0,rateLimits:e=>nX(e,`block`)||nX(e,`weekly`)};function MX(e,t){let n=new Map;for(let r of Fy(_S(e,t).node)){if(r.kind!==`segment`)continue;let e=n.get(r.name)??[];r.when&&e.push(r.when),n.set(r.name,e)}let r=[...n.keys()].filter(t=>Ky(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,$Y(e,t,n.get(t))])),a=e=>r.filter(t=>jX[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}const NX=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function PX(e){if(typeof e==`string`)return NX.exec(e)?.[1]}function FX(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function IX(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function LX(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=FX(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?PX(IX(n)):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&o===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...o!==void 0&&{command:o}}}function RX(e,t){return e===void 0?[ie(t,`.config`,`claude`),ie(t,`.claude`)].filter(e=>f(e)):[e]}async function zX(e){let t=[];for(let n of e){let e=ie(n,`projects`),r=await BX(lo(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(ie(e,n.name))}return t}async function BX(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function VX(e,t,n){let r=[],i=[],a=ie(t,e,`subagents`);try{let t=(await lo(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=ie(a,o);if(n?.has(t)){r.push(t);continue}let s=await go(t,void 0,void 0);if(s.kind!==`ok`){k(`Failed to check agent file ${t}`);continue}i=YX(i,t,s.value);let c=KX(_o(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){k(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function HX(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(WX(t)===`tool_result`)return`tool-result`;let n=typeof e.origin==`object`&&e.origin!==null?e.origin.kind:void 0;if(n!==void 0&&n!==`human`)return`turn`;let r=IX(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||UX.test(r)?`claude-code`:`prompt`}const UX=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function WX(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function GX(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=HX(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:LX(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function KX(e){let t=e.trim();if(!t)return{kind:`blank`};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{kind:`object`,value:e}:{kind:`unparsed`,reason:`not a JSON object`}}catch(e){return{kind:`unparsed`,reason:String(e)}}}function qX(e){let t=KX(e);if(t.kind===`unparsed`)return k(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return GX(t.value)}catch(e){return k(`Failed to project JSONL line: ${e}`),null}}function JX(e){let t=[];for(let n of e.split(`
|
|
192
|
-
`)){let e=
|
|
185
|
+
Single-row example: root: { h: ["seg1", "seg2"] }`,line:q(e.source,[`layout`])}),t.root!==void 0&&(a.root=JU(e,`root`,t.root)),t.insert!==void 0&&(a.insert=XU(e,t.insert,i)),t.actions!==void 0&&(a.actions=JB(e,t.actions,r)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:q(e.source,[`looks`])}),t.styles!==void 0&&(a.styles=bW(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=AM(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=SW(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=PM(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=qB(e,t.helpers)),t.plugins!==void 0&&(a.plugins=GG(e,t.plugins)),iW(e,a),hW(e,a),mN(e,a),nN(e,a,pi,`the global settings menu`),rN(e,a,n),a}const WG=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function GG(e,t){if(Array.isArray(t)&&t.every(e=>typeof e==`string`&&e!==``))return t;e.issues.push({path:`plugins`,message:`"plugins" must be a list of plugin definition paths, got ${fb(t)}`,line:q(e.source,[`plugins`])})}const KG={},qG=hI(`commands.`),JG=xI(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),YG=lI(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),XG=`{{ ${jN} }}`,ZG={min:0,max:100,step:5},QG={warnAt:{label:`warning at %`,domain:ZG,default:50},errorAt:{label:`error at %`,domain:{...ZG,atLeast:`warnAt`},default:80}};function $G(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:ZG,default:80}}}const eK={globals:{palette:`tokyo-night`},variables:{...qG.variables,...Fj,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"effort.level":{kind:`input`,path:`effort.level`,default:``},"effort.glyphs":{kind:`literal`,value:`? `},"glyph.worktree":{kind:`literal`,value:`⊫`},...YG.variables,version:{kind:`input`,path:`version`,default:``},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.tracking":{kind:`input`,path:`git.tracking`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.committedAt":{kind:`input`,path:`git.committedAt`,type:`number`,default:0},"git.timeSinceCommit":{kind:`template`,type:`number`,template:`{{ if gt .git.committedAt 0 }}{{ sub (int (unixEpoch now)) .git.committedAt }}{{ else }}0{{ end }}`},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`template`,type:`number`,template:`{{ etaMinutes .block.nativeUtilization .block.resetsAt 300 }}`},"weekly.etaMinutes":{kind:`template`,type:`number`,template:`{{ etaMinutes .weekly.percentage .weekly.resetsAt 10080 }}`},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``}},segments:{directory:{group:`location`,description:"The main checkout's path, shortened fish-style — `~` under home — plus the subpath and, in a linked worktree, the worktree's name. Click to copy the full path.",template:`{{ $dir := ternary .location.main .current_dir (ne .location.main "") }}{{ if and (ne .home "") (or (eq .home $dir) (hasPrefix (printf "%s/" .home) $dir)) }}{{ $dir = printf "~%s" (trimPrefix .home $dir) }}{{ end }}{{ $text := printf "%s%s" (abbreviatePath $dir) .location.subpath }}{{ if ne .location.worktree "" }}{{ $text = printf "%s (%s %s)" $text .glyph.worktree .location.worktree }}{{ end }}{{ action "copyDir" $text }}`,fg:XG},model:{group:`model-context`,description:`The active model's display name, followed by the effort gauge (a chevron ladder, climbing on a bubble at max) when an effort level is set.`,template:`✱ {{ formatModelName .model.display_name }}{{ if ne .effort.level "" }} {{ template "effortGauge" . }}{{ end }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{group:`session-tools`,description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{group:`model-context`,description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{group:`location`,description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{group:`location`,description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{group:`git`,description:`The git state: a summary (branch, ahead/behind, S/U/? flags) that the arrow at its right edge expands to every fact — repo, in-progress operation, sha, upstream ±, stash count, time since the last commit.`,template:`{{ if ne .git.branch "" }}{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}{{ end }}{{ if or .location.noRepo ${YG.armed} }}{{ if ne .git.branch "" }} {{ end }}${YG.template}{{ end }}`,fg:XG,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if eq .git.prState "open" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (eq .git.prState "open") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:rI(``).template},commands:{group:`session-tools`,description:`Type /compact, /model or /clear into this session; /clear asks for a second click. Hidden when not inside tmux.`,template:qG.template,when:qG.when},session:{group:`cost-limits`,description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:$G(0)},today:{group:`cost-limits`,description:`Today's cost and tokens across every session, with a budget warning once a budget is configured.`,template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:$G(50)},block:{group:`cost-limits`,description:`The 5-hour rate-limit block: percent used and time to reset, heating to warning then error.`,template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:QG,when:`{{ gt .block.resetsAt 0 }}`},weekly:{group:`cost-limits`,description:`The weekly rate-limit quota: percent used and time to reset, heating to warning then error.`,template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:QG,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{group:`cost-limits`,description:`Spend per hour, with the projected time to the 5-hour and weekly limits.`,template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 (tint) 0 "error" .settings.errorWithin "warning" .settings.warnWithin (tint) }}`,settings:{errorWithin:{label:`error within (min)`,domain:{min:0,max:300,step:5},default:30},warnWithin:{label:`warning within (min)`,domain:{min:0,max:300,step:5,atLeast:`errorWithin`},default:60}},when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{group:`activity`,description:`Token throughput for the latest exchange: output, input, and total.`,template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{group:`activity`,description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,when:`{{ ne .speed.history "" }}`},cacheTimer:{group:`activity`,description:"Minutes until the prompt cache expires, or `cold` once it has.",template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ readableOn (color (cascade (minutesUntilReset .cache.expiresAt) "0:error" "9:warning" "21:foreground")) (bgOf) ${yv} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:JG.template,bg:JG.bg,when:JG.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...rI(``).actions,...qG.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...YG.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...JG.actions},styles:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},themeDefaults:KG,presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{effortGauge:`{{ \$ord := default 0 (get (dict "low" 1 "medium" 2 "high" 3 "xhigh" 4 "max" 5) .effort.level) }}{{ \$glyphs := compact (splitList " " .effort.glyphs) }}{{ $bubble := readableOn (mix (bgOf) (color "accent") 40) (bgOf) 1.08 }}{{ if eq \$ord 5 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${yv} }}{{ \$climb := frames 1 (index \$glyphs 1) 1 (index \$glyphs 3) 1 (index \$glyphs 4) }}{{ fg \$bubble "" }}{{ bg \$bubble (fg \$climbing \$climb) }}{{ fg \$bubble "" }}{{ else }}{{ fg (ramp $ord "step" 0 (${jN}) 2 (readableOn (color "accent") (bgOf) ${yv})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${yv}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ $age := .git.timeSinceCommit }}{{ if and .settings.age (gt $age 0) }} ◷ {{ template "formatTimeSince" $age }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:SI(`.`),formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatToolTally:`{{ $names := splitList "," . }}{{ range $i, $pair := $names }}{{ if lt $i 2 }}{{ if $i }} {{ end }}{{ $kv := splitList ":" $pair }}{{ index $kv 0 }}{{ if ne (index $kv 1) "1" }}×{{ index $kv 1 }}{{ end }}{{ end }}{{ end }}{{ if gt (len $names) 2 }} +{{ sub (len $names) 2 }}{{ end }}`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},tK=new Set([eK.globals.palette,...Object.keys(eK.themeDefaults),...Object.values(eK.segments).map(e=>e.palette)].filter(e=>e!==void 0)),nK=Tz(zG(`<default>`,JSON.stringify(eK),tK),eK),rK=mS(nK.presets);function iK(e){return rK.includes(e)}const aK=Object.freeze({});function oK(e,t){return e.kind===`decided`?t[e.name]??aK:aK}function sK(e,t){return{...e,...Object.fromEntries(Tx.map(n=>[n,e[n]??t[n]]))}}const cK=(e,t)=>qb(n=>{let{setting:r,on:i,inTmux:a}=Bb[n].switch;return e[r]===i&&(t||!a)});function lK(e,t,n,r){let i=Dx(e);return Kv(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function uK(e,t){return hS(t(`preset`),e.globals.preset,e.presets)}function dK(e,t,n){let r=uK(e,t),i=bS(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Yx(a.palette,t(`theme`),i.palette),s=sK(i,oK(o,e.themeDefaults));return{...Object.fromEntries(Cx.map(e=>[e,lK(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:iy(a.style,t(`style`),s.style,e.styles),effect:my(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function fK(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?Cy:wy;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const pK=Object.entries(Mx),mK=new Set(Px.map(e=>e.sessionKey)),hK=()=>!1;function gK(e,t){return dK(e,e=>mK.has(e)?t(e):null,hK)}const _K=[`preset`,`theme`];function vK(e,t,n){let r=new Set(_K.slice(0,n).map(e=>Mx[e].sessionKey));return dK(e,e=>r.has(e)?t(e):null,hK)}function yK(e,t){let n=Array.from({length:_K.length+1},(n,r)=>vK(e,t,r));return e=>{let t=_K.indexOf(e);return n[t===-1?_K.length:t]}}function bK(e,t,n,r){return e.flatMap(([e,i])=>{let a=fK(t,e);return a===null||a===fK(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function xK(e,t,n){return fK(gK(e,t),n)}function SK(e,t){let n=gK(e,t);return bK(pK,n,yK(e,t),t=>CK(e,n.preset,t.configKey))}function CK(e,t,n){return n in(gS(e.presets,t).globals??{})?JM(t,n):n}function wK(e,t,n){let r=hS(t(Mx.preset.sessionKey),e.globals.preset,e.presets),i=YM(n);return{key:i?.scope===`globals`?CK(e,r,i.field):n,globals:bS(e,r)}}function TK(e,t){let{preset:n}=gK(e,t);return OK(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:nb(a,s);return c===void 0||tb(c)===tb(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function EK(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return mS(e.presets).flatMap(n=>{let i=OK(e,n);return[...new Set(i.filter(e=>r.has(e.key)).map(e=>e.id))].flatMap(e=>{let n=i.filter(t=>t.id===e);return $y(Object.fromEntries(n.map(e=>[e.setting,e.decl])),Object.fromEntries(n.map(e=>{let n=r.get(e.key)??t(e.key),i=n===null?void 0:nb(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const DK=new WeakMap;function OK(e,t){let n=DK.get(e)??new Map;DK.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...Fy(_S(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Zy(e.segments[t.name])[n];return{id:r,setting:n,key:i,decl:a,saved:t.settings?.[n]??a.default}})),a=[...new Map(i.map(e=>[e.key,e])).values()];return n.set(t,a),a}function kK(e,t){let n=gK(e,t);return{from:n.preset,globals:gS(e.presets,n.preset).globals??{},picks:bK(pK.filter(([e])=>e!==`preset`),n,yK(e,t),e=>e.configKey),placements:TK(e,t)}}function AK(e,t){return dK({...e,globals:{palette:t},presets:{}},()=>null,hK)}function jK(e,t){let n=gK(e,t),r=fK(n,`theme`);if(r===null)return{kind:`rule`};let i=AK(e,r),a=bS(e,n.preset),o=Object.fromEntries(Tx.map(e=>[e,fK(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:Tx.some(e=>o[e]!==fK(i,e))}}function MK(e){return{sessionKeys:Px.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...EM(e)?rK.map(t=>JM(t,e)):[],...qM(e)?qv().map(t=>KM(t,e)):[]]}}function NK(e){return new Set(Px.map(e=>e.configKey).filter(t=>MK(t).fileKeys.some(t=>IK(e,FK(t)))))}function PK(e,t,n){let r=SK(e,n),i=new Set(r.map(e=>e.configKey)),a=zx(e=>i.has(Mx[e].configKey)||t.has(Mx[e].configKey)),o=jK(e,n);return{unsaved:r.length+TK(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function FK(e){let t=YM(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return XM(t)}function IK(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&IK(e[n],r)}function LK(e,t,n){let r=Bx.get(n);if(r!==void 0)return xK(e,t,r);for(let[,t]of qy(e))if(t.key===n)return t.default??null;return null}function RK(e,t){let n=BM(e).get(t);return n===void 0?null:String(n)}const zK={inside:()=>[],defaultOf:()=>Yr,menus:[]},BK=e=>`${e.key}\0${e.member}`;function VK(e){let t=new Map,n=n=>{let r=`${n.name}\0${jy(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:fW(a,jy(n));return t.set(r,o),o},r=e=>[...e.opens===void 0?[]:[e.opens.ref],...n(e)],i=new Map,a=new Map;for(let t of Object.values(e.variables))t.kind===`state`&&(t.default!==void 0&&i.set(t.key,t.default),t.within!==void 0&&a.set(t.key,t.within));let o=new Map,s=new Map,c=new Map,l=e=>{s.set(e.key,(s.get(e.key)??new Set).add(e.member))},u=(e,t)=>{let n=o.get(BK(e))??new Map;n.set(BK(t),t),o.set(BK(e),n)},d=(e,t)=>{if(e.kind===`container`){for(let n of e.children)d(n,t);return}for(let n of r(e)){l(n),c.set(BK(n),n);for(let e of t)u(e,n)}e.opens!==void 0&&d(e.opens.body,[...t,e.opens.ref])};for(let t of mS(e.presets))d(_S(e,t).node,[]);for(let t of Object.values(e.actions)){let e=ci(t);e!==void 0&&l(e)}for(let[e,t]of a)for(let n of s.get(e)??[])for(let r of t)u(r,{key:e,member:n});let f=new Map;return{inside:e=>{let t=f.get(BK(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(BK(e))??[])n.has(t)||(n.set(t,i),r(i))};r(e);let i=new Map;for(let{key:e,member:t}of n.values())i.set(e,(i.get(e)??new Set).add(t));let a=[...i].map(([e,t])=>({key:e,outside:new Set([...s.get(e)].filter(e=>!t.has(e)))}));return f.set(BK(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const HK=new WeakMap;function UK(e){let t=HK.get(e);if(t!==void 0)return t;let n=VK(e);return HK.set(e,n),n}function WK(e,t,n){let r=new Set(n.map(e=>e.key)),i=n=>t(n)??e.defaultOf(n),a=new Set;for(let{key:t,value:o}of n){let n=i(t);if(n!==o)for(let o of e.inside({key:t,member:n})){let t=i(o.key);t!==e.defaultOf(o.key)&&!o.outside.has(t)&&!r.has(o.key)&&a.add(o.key)}}return[...a]}function GK(e,t){let n=({key:n,member:r})=>(t(n)??e.defaultOf(n))===r,r=(t,n)=>e.inside(n).some(({key:e,outside:n})=>e===t.key&&!n.has(t.member));return e.menus.filter(n).filter(t=>{let i=e.menus.filter(e=>e!==t&&r(t,e)),a=i.length>0&&e.defaultOf(t.key)===t.member;return!i.some(n)&&!a})}function KK(e,t,n){let r=(r,i,a)=>{let o=WK(t(r),t=>e.get(r,t),i);(0,Y.runInAction)(()=>{a();for(let t of o)e.clear(r,t)}),o.length>0&&n(`close-nested: folded=${o.join(`,`)} (session=${r})`)},i=(t,n)=>r(t,n,()=>e.setBatch(t,n));return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(e,t,n)=>i(e,[{key:t,value:n}]),setBatch:i,clear:(n,i)=>r(n,[{key:i,value:t(n).defaultOf(i)}],()=>e.clear(n,i))}}const qK=`render-origin`,JK=`client-hints`,YK=`config-override`;var Z=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}},XK=class extends Error{constructor(e){super(`the daemon closed: ${e} refused`),this.name=`DaemonClosing`}},ZK=class extends Error{constructor(e){super(`the client left: ${e} not run`),this.name=`ClickAbandoned`}};function QK(e){try{return e()}catch(e){throw e instanceof URIError?new Z(`malformed wire encoding: ${e.message}`):e}}const $K=new Set([`1`,`true`]),eq=new Set([`0`,`false`,``]);function tq(e,t){let n=Eq(e),r=n.scope===`segment-palette`?`string`:kx(n.field);if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if($K.has(t))return`true`;if(eq.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function nq(e){try{return l.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function rq(e,t,n){try{if(t===null){l.rmSync(cn(e),{force:!0});return}sn(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function iq(e){return/^\s*$/.test(e)?null:_a(e)}function aq(e,t){return e!==null&&ya(e,t)!==void 0}function oq(e){if(e.kind===`segment`)return e.when===void 0?e.name:{seg:e.name,when:e.when};if(e.kind===`container`){let{kind:t,direction:n,children:r,...i}=e;return{[n===`horizontal`?`h`:`v`]:r.map(oq),...i}}return e}function sq(e){if(!eS(e))return oq(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,oq(t)])),...n}}const cq=eK,lq=cq.segments,uq=cq.presets,dq=cq.root;function fq(e,t,n,r){if(!aq(e,t)&&n===void 0)throw new Z(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function pq(e,t){let n=XM(t);return t.scope===`segment-palette`&&fq(e,[`segments`,t.segment],lq[t.segment],n.join(`.`)),n}function mq(e){return _a(Da(e))}function hq(){return Object.entries(dq.rows).map(([e,t])=>{let n=oq(t);return{path:[`root`],fragment:mq({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function gq(e,t){let n=e===null?void 0:ya(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function _q(e,t){if(t===void 0)return null;let n=sq(t);return{path:e,fragment:mq(n),unit:{path:e,value:n}}}function vq(e,t){let n=[`presets`,t],r=[...n,`root`],i=uq[t];fq(e,n,i,r.join(`.`));let a=gq(e,r)??_q(r,i?.root);return a!==null&&Ja(a.fragment)?a:null}function yq(e,t){let n=qa(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function bq(e,t){return[...hq(),gq(e,[`root`]),vq(e,t)].filter(e=>e!==null).reduce(yq,new Map)}function xq(e,t,n){for(let{node:r,...i}of bq(e,t).values())if(Xa(r,n))return i;throw new Z(`${Sq(e,t).join(`.`)} holds no placement "${n}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`)}function Sq(e,t){return vq(e,t)?.path??[`root`]}function Cq(e,t){return t.scope===`preset-root`?Sq(e,t.preset):XM(t)}function wq(e,{unit:t}){return t===null?e:Va(e,t.path,Da(t.value),Ta)}function Tq(e){let t=YM(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function Eq(e){let t=Tq(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function Dq(e,t,n,r,i){let a=Rq(t,r),o,s=()=>(o??={chain:Mq(t,n)}).chain;zq(t,s,a),i(t,s,a),rq(t.path,r,e.logger),e.record(t.path,n,r)}function Oq(e,t,n){let r=jq(e,t(),n);if(r.length>0)throw new Z(`refused: ${e.above.map(e=>e.path).join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const kq=()=>{};function Aq(e,t){try{return t()}catch(t){throw!(t instanceof Z)||e.above.length===0?t:new Z(`${t.message} — or it is declared by ${e.above.map(e=>e.path).join(`, `)}, which the bar does not edit`)}}function jq(e,t,n){if(t===null)return[];let r=new Set(Iq(Fq(t),Fq(n)));return Iq(Pq(e,t),Pq(e,n)).filter(e=>!r.has(e))}function Mq(e,t){try{return Nq(e,t)}catch(e){if(e instanceof ib)return null;throw e}}function Nq(e,t){return AG(e.locs,t===null?e.above:[UH(e.path),...e.above],nK,{warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:l.readFileSync(n,`utf8`))}function Pq(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function Fq(e){return e.layers.at(-1)?.config??e.base}function Iq(e,t,n=``){return!Lq(e)||!Lq(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>Iq(e[r],t[r],n===``?r:`${n}.${r}`))}function Lq(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rq(e,t){try{return Nq(e,t)}catch(e){throw e instanceof ib?new Z(`refused: the config file would not load after this click — ${e.message}`):e}}function zq(e,t,n){if(n.dropped.length===0)return;let r=t();if(r===null)return;let i=e=>e.dropped.flatMap(e=>e.issues.map(t=>({file:e.file,issue:t}))),a=new Set(i(r).map(({file:e,issue:t})=>`${e}\0${t.message}`)),o=i(n).filter(({file:e,issue:t})=>!a.has(`${e}\0${t.message}`));if(o.length>0)throw new Z(`refused: this click would leave a placement of a segment nothing declares — ${o.map(({file:e,issue:t})=>new ib(e,[t]).message).join(`
|
|
186
|
+
`)}`)}function Bq(e,t){let n=Eq(t),r=iq(nq(e)??``),i=r===null?void 0:ya(r,XM(n));return i!==void 0&&`value`in i?i.value:void 0}function Vq(e,t,n){Hq(e,t,n,[])}function Hq(e,t,n,r){let i=nq(t.path),a=n.reduce((e,[t,n])=>Va(e,pq(iq(e),Eq(t)),tq(t,n),Ta),i??``);Dq(e,t,i,Aq(t,()=>Uq(a,t.path,r,e=>e)),Oq)}function Uq(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=xq(iq(s),n,i),l=eo(wq(s,c),c.path,i,a,Da(o));if(l===null)throw new Z(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function Wq(e,t,n){let r=iq(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of bq(r,t)){if(!Xa(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?xa(e,c):Da(s.value);if(a!==`#`)return Va(e,[...i,`rows`,a],l,Ta);if(vq(r,t)!==null)throw new Z(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return Va(e,i,l,Ta)}return e}function Gq(e,t){return Ua(e,t,t[0]===`presets`&&t.length>2&&!iK(t[1])?2:0)}function Kq(e,t,n){let r=n.map(Tq),i=nq(t.path);if(i===null)return;let a=r.reduce((e,t)=>Gq(e,Cq(iq(e),t)),i);a!==i&&Dq(e,t,i,a,kq)}function qq(e){let t=e===null?void 0:ya(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function Jq(e,t){let n=new Set([...rK,...qq(e),...t.above.flatMap(e=>Object.keys(ua.default.parse(l.readFileSync(e.path,`utf8`)).presets??{}))].map(Hj));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(Hj(e)))}function Yq(e,t,n,r,i,a){let o=nq(t.path),s=iq(o??``),c=Jq(s,t),l=[`presets`,c],u=Aq(t,()=>vq(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?xa(o??``,u.fragment):Da(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Da(r)]]],f=i.map(([e,t])=>{let n=JM(c,e);return[pq(s,Eq(n)),tq(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Va(e,t,n,Ta),Va(o??``,l,`{}`,Ta));return Dq(e,t,o,Aq(t,()=>Uq(p,t.path,a.map(e=>({...e,preset:c})),Wq)),Oq),c}function Xq(e,t,n,r){let i=nq(t.path);Dq(e,t,i,Va(i??``,[`themeDefaults`,n],Da(r),Ta),Oq)}function Zq(e,t,n){if(iK(n))throw new Z(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=nq(t.path),a=iq(i??``);if(i===null||a===null||ya(a,r)===void 0)throw new Z(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=ya(a,[`globals`,`preset`]);Dq(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>Gq(e,t),i),kq)}function Qq(e,t,n,r){let i=Tq(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=nq(t.path),o=r.op===`remove`?r.target:r.anchor,s=Aq(t,()=>xq(iq(a??``),i.preset,o)),c=wq(a??``,s),{after:l,placed:u}=$q(c,s.path,r,()=>{let e=Rq(t,c).config;return mS(e.presets).map(t=>_S(e,t).node)});if(l===null)throw new Z(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return Dq(e,t,a,l,Oq),u}function $q(e,t,n,r){switch(n.op){case`remove`:return{after:Qa(e,t,n.target),placed:null};case`insert`:{let i=WR(n.segment,n.anchor,r());return{after:$a(e,t,i,n.anchor,n.relation),placed:i}}}}function eJ(e,t,n){let r=(r,i,a)=>{let o=i.filter(t).map(t=>({key:t,before:e.get(r,t)}));a();for(let{key:t,before:i}of o)n(r,t,i,e.get(r,t))};return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(t,n,i)=>r(t,[n],()=>e.set(t,n,i)),setBatch:(t,n)=>r(t,n.map(e=>e.key),()=>e.setBatch(t,n)),clear:(t,n)=>r(t,[n],()=>e.clear(t,n))}}const tJ={load:()=>({}),save:()=>{},flush:()=>{}};var nJ=class{sessions;storage;head=0;atom=(0,Y.createAtom)(`SessionState`);constructor(e=tJ,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}observers(){return this.atom.observers_?.size??0}latestRevision(){return this.head}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,Y.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t.some(({key:e,value:t})=>n.values.get(e)!==t)&&(n.revision=++this.head);for(let{key:e,value:r}of t)n.values.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,Y.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.values.delete(t)&&(n.revision=++this.head),n.values.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,Y.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}close(){this.flush(),this.storage=tJ}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};const rJ={load:()=>({}),save:()=>{}},iJ=new Set(Px.map(e=>e.sessionKey)),aJ=e=>iJ.has(e)||e.startsWith(cN),oJ=8*1024*1024,sJ={past:[],future:[]},cJ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var lJ=class{held=Y.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,Y.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=rJ){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??sJ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??sJ}begin(){let e=new Map,t=!1,n=(n,r)=>{t=!0;let i=e.get(n)??new Map,a=i.get(cJ(r));i.set(cJ(r),a===void 0?r:{...r,before:a.before}),e.set(n,i)},r=new Map;return{sessionState:eJ(this.sessionState,()=>!0,(e,i,a,o)=>{if(t=!0,!(!aJ(i)&&i!==`edit.mode`)){if(i===`edit.mode`){let t=r.get(e);r.set(e,{before:t===void 0?a:t.before,after:o});return}n(e,{kind:`session`,key:i,before:a,after:o})}}),file:(e,t,r,i)=>n(e,{kind:`file`,file:t,before:r,after:i}),wrote:()=>{t=!0},written:()=>t,commit:()=>{let t=new Map(e),n=new Map(r);e.clear(),r.clear();for(let e of new Set([...t.keys(),...n.keys()])){let r=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=r.length===0?i:_J(i,r),o=n.get(e),s=o===void 0?a:xJ(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new Z(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,yJ(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new Z(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(cJ)),a=n.net.filter(e=>!i.has(cJ(e))),o=fJ(SJ(bJ(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new Z(`rewind: ${r.map(wJ).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new Z(`redo: nothing to redo`);let a=[...n,i],o=fJ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...mJ(t.savepoint,a.length-o.length,i)}),i}apply(e,t,n,r,i){let a=n===`before`?`after`:`before`,o=t.filter(t=>this.read(e,t)!==t[a]);if(o.length>0){let t=new Set(o.map(cJ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:SJ(n,t),future:SJ(i,t),...a!==void 0&&{savepoint:{at:SJ([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(cJ(e))),below:SJ(a.below,t)}}}),new Z(`${r}: ${o.map(wJ).join(`, `)} changed since that edit — refusing to overwrite it; this session's undo history no longer steps it`)}let s=[];try{for(let r of t)this.write(e,r,r[n]),s.push(r);this.put(e,i)}catch(t){try{for(let t of s.reverse())this.write(e,t,t[a])}catch(e){throw Error(`${t.message}; and putting the step back failed, so it is half-applied: ${e.message}`)}throw t}}read(e,t){return t.kind===`session`?this.sessionState.get(e,t.key):nq(t.file)}write(e,t,n){t.kind===`file`?rq(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||uJ(n)>oJ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,dJ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${oJ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function uJ(e){let t=0;for(let{past:n,future:r,savepoint:i}of e.values())for(let e of[...n,...r,...i===void 0?[]:[i.net,...i.below]])for(let n of e)t+=(n.before?.length??0)+(n.after?.length??0);return t}function dJ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...mJ(n,1,[])}:{past:e,future:t.slice(1),...mJ(n,0,[])}}function fJ(e){return e.slice(-50)}const pJ=e=>e===uN.member;function mJ(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:hJ(e.net,n),below:e.below}}}function hJ(e,t){let n=new Map(e.map(e=>[cJ(e),e]));for(let e of t){let t=n.get(cJ(e));n.set(cJ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const gJ=e=>e.map(e=>({...e,before:e.after,after:e.before}));function _J(e,t){let n=[...e.past,t],r=fJ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...mJ(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...vJ(e.future,a),...i.below]},n.length-r.length,t)}}function vJ(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function yJ(e,t){return{past:e.past.slice(0,-1),future:fJ([...e.future,t]),...mJ(e.savepoint,0,gJ(t))}}function bJ(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...vJ(r,t.at-i.length),...t.below]}function xJ(e,t){if(pJ(t.after)&&!pJ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!pJ(t.after)&&pJ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function SJ(e,t){return e.map(e=>e.filter(e=>!t.has(cJ(e)))).filter(e=>e.length>0)}function CJ(e){return e.map(wJ).join(`, `)}function wJ(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function TJ(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function EJ(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(TJ))}function DJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(TJ)&&EJ(t.below)}function OJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return EJ(t.past)&&EJ(t.future)&&(t.savepoint===void 0||DJ(t.savepoint))}function kJ(e,t){let n=e=>e.kind===`file`||aJ(e.key)?!0:(t.add(e.key),!1),r=e=>e.map(e=>e.filter(n)).filter(e=>e.length>0),{savepoint:i}=e,a=r(e.past),o=r(e.future);return i===void 0?{past:a,future:o}:{past:a,future:o,savepoint:{at:r(e.past.slice(0,i.at)).length,net:i.net.filter(n),below:r(i.below)}}}function AJ(e,t){return{load:()=>{let n;try{n=l.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(OJ)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,kJ(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{l.mkdirSync(E.dirname(e),{recursive:!0}),sn(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const jJ=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function MJ(e){return{...Object.fromEntries(jJ.map(e=>[e,void 0])),CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir,...e.claudeConfigDir!==void 0&&{CLAUDE_CONFIG_DIR:e.claudeConfigDir}}}const NJ=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function PJ(e){let t=e=>({kind:`failed`,reason:e});if(!NJ(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!NJ(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!sF.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${sF.join(` or `)}`)}return{kind:`ok`,value:e}}function FJ(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const IJ=e=>QH(e,`doctor-marks.json`,{},PJ),LJ=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},RJ=(e,t)=>e.includes(t)?e:[...e,t],zJ=e=>QH(e,`doctor-clicked-terminals.json`,[],LJ);var BJ=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const VJ=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},HJ=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),UJ=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=HJ(e,t);return r===void 0?n:r.projectDir},WJ=(e,t)=>HJ(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function GJ(e){let t=new Map;for(let n of e.split(`
|
|
187
|
+
`)){let e=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(n);if(e===null)continue;let r=Number(e[1]);t.set(r,{pid:r,ppid:Number(e[2]),command:e[3].trim()})}return t}function*KJ(e,t){let n=new Set;for(let r=e.get(t);r!==void 0&&!n.has(r.pid);)n.add(r.pid),yield r,r=e.get(r.ppid)}function qJ(e,t){return e.kind===`absent`?F(`none`):e.kind===`failed`?e:t.kind===`failed`?t:F(t.kind===`ok`?`tracked`:`gone`)}function JJ(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?L(`HEAD: ${t.reason}`):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const YJ={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},XJ={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function ZJ(e,t,n){return Object.hasOwn(t,n)?F(t[n]):L(`${e}: unknown state ${JSON.stringify(n)}`)}const QJ={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,tag:`tag`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function $J(e){return Object.keys(QJ).flatMap(t=>{let n=e[t];return n?.kind===`failed`?[`git.${QJ[t]}: ${n.reason}`]:[]})}function eY(e,t,n){return t.ok?F(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?I:L(tY(e,t))}function tY(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??nY(t.stderr)].filter(Boolean).join(`, `)}`}function nY(e){return e.trim().split(`
|
|
188
|
+
`,1)[0]??``}function rY(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?I:F(n)}function iY(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?F(t):I}const aY={github:`gh`,gitlab:`glab`};function oY(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const sY=/^[A-Za-z]:[\\/]/;function cY(e){let t=e.trim();if(sY.test(t))return null;let n=t.match(/^(?:[^@/]+@)?(\[[^\]]+\]):(.*)$/)??t.match(/^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.*)$/),r=n?`ssh://${n[1]}/${n[2].replace(/^\/+/,``)}`:t,i;try{i=new URL(r)}catch{return null}return{scheme:i.protocol.replace(/:$/,``),host:i.hostname.toLowerCase(),port:i.port,path:i.pathname.replace(/^\/+/,``).replace(/\/+$/,``)}}function lY(e){return cY(e)?.host||null}function uY(e){let t=lY(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const dY=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function fY(e){let t=eY(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?pY(t.value):[]}}function pY(e){let t=new Map;for(let n of e.split(`
|
|
189
|
+
`)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function mY(e){return e.urls.find(e=>yY(e)!==null)??e.urls[0]??null}function hY(e){return e.find(e=>e.name===`origin`)??e[0]??null}function gY(e){let t=hY(e);return t?mY(t):null}function _Y(e){let t=hY(e);return t?t.urls.find(e=>uY(e)!==null)??mY(t):null}function vY(e){let t=(cY(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function yY(e){let t=cY(e);if(!t)return null;let n=t.scheme===`https`?{scheme:`https`,port:t.port}:t.scheme===`http`?{scheme:`http`,port:t.port}:t.scheme===`ssh`||t.scheme===`git`?{scheme:`https`,port:``}:null;if(!n||!t.host)return null;let r=t.path.replace(/\.git$/,``);if(!r)return null;let i=n.port?`${t.host}:${n.port}`:t.host;return`${n.scheme}://${i}/${r}`}function bY(e){let t=gY(e);return t===null?null:yY(t)}function xY(e,t,n,r){return t.ok?r(t.stdout):oY(t)||t.reason===`non-zero`&&n.test(t.stderr)?I:L(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??nY(t.stderr)].filter(Boolean).join(`, `)}`)}function SY(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function CY(e){let t=`detached`,n=I,r=I,i=I,a=0,o=0,s=0,c=0;for(let l of e.split(`
|
|
190
|
+
`)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?I:F(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=F(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=F({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function wY(e){let t;try{t=JSON.parse(e)}catch(e){return L(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!SY(t))return L(`gh pr view: JSON is not an object`);let{number:n,state:r,url:i,headRefOid:a}=t;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return L(`gh pr view: missing number/state/url/headRefOid`);let o=ZJ(`gh pr view`,YJ,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function TY(e){let t;try{t=JSON.parse(e)}catch(e){return L(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!SY(t))return L(`glab mr view: JSON is not an object`);let n=t.iid,r=t.state,i=t.web_url,a=t.sha;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return L(`glab mr view: missing iid/state/web_url/sha`);let o=ZJ(`glab mr view`,XJ,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function EY(e){try{let t=l.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var DY=class{constructor(e){this.launcher=e}isGitRepo(e){return ec(e)}async execGitAsync(e,t){return this.launcher.launch({bin:`git`,args:[...e],cwd:t.cwd,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}resolveEffectiveGitDir(e,t){return this.isWorktree(e)?F(e):t&&this.isGitRepo(t)?F(t):this.isGitRepo(e)?F(e):this.findGitRoot(e)}findGitRoot(e){let t=tc(e);return t===void 0?I:F(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return L(`git: ${e instanceof Error?e.message:String(e)}`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=this.findGitRoot(e);if(t.kind!==`ok`)return t;r=t.value}let a=await this.getCoreAsync(r);if(a.kind!==`ok`)return a;let o={branch:a.value.branch,status:a.value.status,aheadBehind:a.value.aheadBehind,head:a.value.oid};t.showWorkingTree&&(o.workingTree=a.value.workingTree),t.showSha&&(o.sha=rY(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showCommittedAt&&(o.committedAt=await this.committedAt(r,a.value.oid)),t.showStashCount&&(o.stashCount=this.getStashCount(r));let s=t.showRepoName||t.showRepoUrl?await this.getRemotesAsync(r):void 0;return s!==void 0&&t.showRepoName&&(o.repoName=rY(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=rY(s,bY)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),F(o)}resolveGitDir(e){return to(oc(e),E.join(e,`.git`))}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return l.existsSync(E.join(t,`MERGE_HEAD`))?F(`MERGE`):l.existsSync(E.join(t,`CHERRY_PICK_HEAD`))?F(`CHERRY-PICK`):l.existsSync(E.join(t,`REVERT_HEAD`))?F(`REVERT`):l.existsSync(E.join(t,`BISECT_LOG`))?F(`BISECT`):l.existsSync(E.join(t,`rebase-merge`))||l.existsSync(E.join(t,`rebase-apply`))?F(`REBASE`):I}catch(e){return L(`git operation probe: ${e instanceof Error?e.message:String(e)}`)}}async getNearestTagAsync(e){return iY(eY(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestamp(e,t.value):t}commitTimes=new Map;async commitTimestamp(e,t){let n=this.commitTimes.get(t);if(n!==void 0)return this.commitTimes.delete(t),this.commitTimes.set(t,n),n;let r=this.readCommitTimestamp(e,t);for(this.commitTimes.set(t,r),r.then(e=>{e.kind!==`ok`&&this.commitTimes.get(t)===r&&this.commitTimes.delete(t)},()=>{this.commitTimes.get(t)===r&&this.commitTimes.delete(t)});this.commitTimes.size>256;){let e=this.commitTimes.keys().next().value;if(e===void 0)break;this.commitTimes.delete(e)}return r}async readCommitTimestamp(e,t){let n=iY(eY(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10);return Number.isNaN(r)?L(`git log -1: unparseable timestamp "${n.value}"`):F(r)}resolveCommonGitDir(e){return to(sc(e),e)}getStashCount(e){let t=E.join(this.resolveCommonGitDir(this.resolveGitDir(e)),`logs`,`refs`,`stash`),n;try{n=l.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?F(0):L(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`)}let r=n.trim();return F(r?r.split(`
|
|
191
|
+
`).length:0)}async getRemotesAsync(e){let t=EY(E.join(this.resolveCommonGitDir(this.resolveGitDir(e)),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){return fY(await this.execGitAsync(dY,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=gY(e);return(n===null?null:vY(n))??E.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=_Y(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return this.launcher.launch({bin:e,args:[...t],cwd:n.cwd,timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=uY(t);return n===`github`?xY(`gh pr view`,await this.execForgeAsync(aY.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,wY):n===`gitlab`?xY(`glab mr view`,await this.execForgeAsync(aY.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,TY):I}isWorktree(e){try{let t=E.join(e,`.git`);return!!(l.existsSync(t)&&l.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){k(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=eY(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F(CY(t.value)):t}};function OY(e){return Math.max(1,e-2)}function kY(){return Y.observable.box(AY(`unread`),{deep:!1})}function AY(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function jY(e,t){let n=e.reading.get();n.kind===`read`&&(0,Y.compareStructural)(n.outcome,t)||((0,Y.runInAction)(()=>e.reading.set({kind:`read`,outcome:t})),n.kind===`pending`&&n.land())}function MY(e,t){let n=e.reading.get();n.kind===`read`?(0,Y.runInAction)(()=>e.reading.set(AY(t))):n.why!==t&&t===`unread`&&(0,Y.runInAction)(()=>e.reading.set({...n,why:t}))}function NY(e,t){e.reading.get().kind===`pending`&&jY(e,t)}function PY(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function FY(e){let t=e.reading.get();return t.kind===`read`?t.outcome:t}async function IY(e){for(;;){let t=e();if(!PY(t))return t;await t.landed}}function LY(e,t,n,r){let i=new AbortController,a=r(Math.max(0,t),()=>i.abort());return new Promise((t,r)=>{i.signal.addEventListener(`abort`,()=>t(`deadline`)),e(i.signal).then(()=>t(`answered`),e=>i.signal.aborted?n(e):r(e))}).finally(()=>{a(),i.abort()})}function RY(e){return{current:()=>e}}function zY(e){return IY(()=>e.current())}function BY(e,t,n){return xt({dir:e.project_dir,env:n===void 0?[]:[[So,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function VY(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function HY(e){return{...Object.fromEntries(Cx.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:iK(e.preset)}}}const UY={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function WY(e,t){if(!t)return`-`;if(ro(e))return`pending`;let{prState:n,prError:r,prEarlier:i}=e??{};return ro(n)?`pending`:n===void 0?r===void 0?i===void 0?`-`:`earlier-${String(i)}`:`failed`:n}const GY=10*1e3;function KY(e,t){if(!(t<60))return e*3600/t}function qY(e,t,n,r){let i=r-t;if(i<50||i>GY)return;let a=n-e;if(!(a<=0))return a*1e3/i}function JY(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=qY(t.input,t.atMs,n.input,n.atMs),i=qY(t.output,t.atMs,n.output,n.atMs),a=qY(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function YY(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>GY)continue;let o=qY(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function XY(e,t){let n=bS(e,t),r=[...Qv.flatMap(e=>{let t=n[e];return $v(t)?[t]:[]})];for(let n of Fy(_S(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...ZY(e,n.name));return $Y(e,r)}function ZY(e,t){let n=e.segments[t];return n?[...[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]),...Object.values(n.partials??{})]:[]}function QY(e,t,n){return $Y(e,[...ZY(e,t),...n])}function $Y(e,t){let n=jW(e),r=new Map(gC(e)),i=t.flatMap(e=>n.ofTemplate(e).flatMap(({reaches:e})=>e)),a=new Set,o=new Set;for(;i.length>0;){let e=i.pop();if(a.has(e))continue;a.add(e);let t=r.get(e),s=kW(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function eX(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=XY(e,n);return t.set(n,i),i}}function tX(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function nX(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.committedAt`)&&{showCommittedAt:!0},...Object.keys(UY).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const rX=new WeakMap;function iX(e){let t=rX.get(e);return t===void 0&&(t=aX(e),rX.set(e,t)),t}function aX(e){let t=t=>tX(e,t);return{git:t(`git`),session:t(`session.cost`)||t(`session.tokens`)||t(`burn`),today:t(`today`),context:t(`context`)||t(`autocompact`),metrics:t(`metrics`)||t(`burn`),burn:t(`burn`),activity:t(`activity`),tmux:t(`tmux.session`),hostName:t(`host.name`),hostUser:t(`host.user`),cache:t(`cache`),speed:t(`speed`),autocompact:t(`autocompact`),block:t(`block`)}}function oX(e){return OY(e.termCols??120)}function sX(e,t){return To(wo(e.claudeConfigDir,t))}function cX(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function lX(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=iX(e.neededInputPaths),s=r.session_id,c=i.usageStore.request(s,r.transcript_path),l=async(e,t,r)=>{if(!t)return;let a=i.clock.monotonic();n.set(e,null);let o=null;try{await r()}catch(t){i.log(`error`,`${e} lane threw: ${C(t)}`),o=`${e}: ${String(t)}`}n.set(e,Math.round(i.clock.monotonic()-a)),i.faults.refreshed(s,e,o)};await Promise.all([l(`session`,o.session,()=>c.usage(r)),l(`today`,o.today,()=>c.today(i.lanes().today)),l(`context`,o.context,()=>i.contextProvider.getContextInfo(r)),l(`metrics`,o.metrics,()=>i.metricsProvider.getMetricsInfo(s,r)),l(`activity`,o.activity,()=>i.activityProvider.getActivityInfo(s,r)),l(`cache`,o.cache,()=>i.cacheExpiry.refresh(s,r.transcript_path)),l(`speed`,o.speed,()=>c.speed(RA(t).getTime())),l(`autocompact`,o.autocompact,async()=>i.autoCompact.window(sX(a,i.home)))])}function uX(e,t){return[...t.keys()].filter(t=>e.has(t))}function dX(e,t){let n=RY(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function fX({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,nX(n),t.workspace?.project_dir]}function pX(e,t,n,r,i){let a=iX(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return RY(I);try{return n()}catch(t){return s.push(`${e}: ${C(t)}`),RY(L(`${e}: ${String(t)}`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...fX(n,r))),tmux:c(`tmux`,a.tmux&&o!==null,()=>e.tmuxService.declare(t,o)),hostName:c(`host.name`,a.hostName,()=>e.hostService.declareName(t)),hostUser:c(`host.user`,a.hostUser,()=>e.hostService.declareUser(t)),today:c(`today`,a.today,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map(uX(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function mX(e){let{hookData:t,deps:n}=e,r=iX(e.neededInputPaths),i=t.session_id,a=n.lanes(),o=(e,t,r)=>{if(!t)return I;let a=n.faults.of(i,e);if(a!==void 0)return a;try{return r()}catch(t){return n.log(`error`,`${e} read threw: ${C(t)}`),L(`${e}: ${String(t)}`)}};return{git:a.git.current(),usage:o(`session`,r.session,()=>n.usageStore.usageOf(i,t)),context:o(`context`,r.context,()=>n.contextProvider.contextOf(t)),metrics:o(`metrics`,r.metrics,()=>n.metricsProvider.metricsOf(i,t)),activity:o(`activity`,r.activity,()=>n.activityProvider.activityOf(i)),tmuxSession:a.tmux.current(),hostName:a.hostName.current(),hostUser:a.hostUser.current(),cache:o(`cache`,r.cache,()=>n.cacheExpiry.expiryOf(i)),speed:o(`speed`,r.speed,()=>n.usageStore.speedOf(i)),autoCompact:o(`autocompact`,r.autocompact,()=>n.autoCompact.stored(sX(e.hints,n.home))),sources:new Map([...a.sources].map(([e,t])=>[e,t.current()]))}}function hX(e){let t=e.git.current(),n=t.kind===`ok`?t.value.pullRequest:void 0;return[t,e.tmux.current(),e.hostName.current(),e.hostUser.current(),e.today.current(),...[...e.sources.values()].map(e=>e.current()),...n===void 0?[]:[n]].flatMap(e=>e.kind===`pending`&&e.why===`unread`?[e.landed]:[])}function gX(e,t,n){let{hookData:r,hints:i}=e,{effective:a,configFacts:o}=t,{configPath:s,...c}=o,l=iX(e.neededInputPaths),u=(e,t)=>{switch(e.kind){case`pending`:return no;case`failed`:case`absent`:return;case`ok`:return t(e.value)}},d=e=>e.kind===`ok`?e.value:void 0,f=i.tmux??null,p=n.git.kind===`pending`?no:kX(n.git,()=>no),m=n.tmuxSession.kind===`pending`?no:d(n.tmuxSession),h=n.hostName.kind===`pending`?no:d(n.hostName),g=n.hostUser.kind===`pending`?no:d(n.hostUser),_=n.autoCompact.kind===`pending`||l.autocompact&&n.context.kind===`pending`?no:wX(n.autoCompact,d(n.context)?.maxTokens),v=r.rate_limits?.five_hour,y=r.rate_limits?.seven_day,b=l.burn?n.usage.kind===`pending`||n.metrics.kind===`pending`?no:yX(d(n.usage)?.session.cost,d(n.metrics)?.sessionDuration):void 0,x=u(n.speed,bX),S=u(n.usage,e=>DX({cost:e.session.cost,tokens:e.session.tokens})),C=u(n.metrics,e=>DX({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),w=u(n.activity,TX),ee=u(n.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),T=u(n.cache,e=>({expiresAt:e})),te=OX(e.deps.home),E=r.workspace?{...r.workspace,current_dir:OX(r.workspace.current_dir)??``,project_dir:OX(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>OX(e)??e)}:r.workspace,ne=r.session_id;return{...r,...E!==void 0&&{workspace:E},...te!==void 0&&{home:te},...p!==void 0&&{git:p},...r.location!==void 0&&{location:{...r.location,main:OX(r.location.main)??``}},...f!==null&&{tmux:{pane:f.pane,...m!==void 0&&{session:m}}},host:{...h!==void 0&&{name:h},...g!==void 0&&{user:g},...i.ssh!==void 0&&{ssh:i.ssh}},...HY(a),history:t.history,navigation:{back:t.back},term:{cols:oX(i)},...c,...s!==null&&{configPath:s},resumeCommand:BY(E,ne,i.claudeConfigDir),...S!==void 0&&{session:S},...b!==void 0&&{burn:b},...x!==void 0&&{speed:x},...l.block&&v!==void 0&&{block:{nativeUtilization:v.used_percentage,resetsAt:v.resets_at}},...y!==void 0&&{weekly:{percentage:y.used_percentage,resetsAt:y.resets_at}},...T!==void 0&&{cache:T},...ee!==void 0&&{context:ee},...C!==void 0&&{metrics:C},...w!==void 0&&{activity:w},..._!==void 0&&{autocompact:_},...vX(n.sources.keys(),e=>{let t=n.sources.get(e);return t.kind===`pending`?no:t})}}function _X(e){return{sources:String(e.size),sourcesPending:[...e].flatMap(([e,t])=>{let n=t.current();return n.kind===`pending`?[`${e}:${n.why}`]:[]}).join(`,`)||`-`}}function vX(e,t){let n=Object.fromEntries(PS.map(e=>[e,{}]));for(let r of e){let e=r.split(`.`),i=e.pop(),a=e.reduce((e,t)=>e[t]??={},n);a[i]=t(r)}return n}function yX(e,t){let n=e!=null&&t!=null?KY(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function bX(e){let t=JY(e),n=YY(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function xX(e,t){return gX(e,t,mX(e))}function SX({usageStore:e,faults:t,log:n},r,i,a){if(t.of(i.session_id,`today`)!==void 0)return;let o=r.current();if(o.kind===`pending`)return no;if(o.kind!==`ok`)return;let s=(()=>{try{return e.todayAt(o.value,i,a)}catch(e){return n(`error`,`today read threw: ${C(e)}`),I}})();return s.kind===`pending`?no:s.kind===`ok`?{cost:s.value.cost,tokens:s.value.tokens}:void 0}async function CX(e,t,n){await lX(e,t,n),await IY(()=>{let t=hX(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function wX(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return bI(e.value,t)}}function TX(e){let t=e.todos.findIndex(e=>e.active),n=e.todos.length===0?void 0:{total:e.todos.length,completed:e.todos.filter(e=>e.done).length,...t>=0&&{position:t+1,active:e.todos[t].text}},r=EX(e.running),i=EX(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}};if(!(e.command===null&&n===void 0&&a===void 0))return{...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function EX(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function DX(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function OX(e){return e===void 0||e.length===0||E.sep!==`\\`?e:e.replace(/\\/g,`/`)}function kX(e,t){if(e.kind!==`ok`)return;let n=e.value,r=e=>e?.kind===`ok`?e.value:void 0,i=r(n.aheadBehind),a=r(n.sha),o=r(n.operation),s=r(n.committedAt),c=r(n.stashCount),l=r(n.upstream),u=n.upstream===void 0?void 0:r(qJ(n.upstream,n.aheadBehind)),d=r(n.repoName),f=r(n.repoUrl),p=n.pullRequest===void 0?void 0:n.pullRequest.kind===`pending`?n.pullRequest:JJ(n.pullRequest,n.head),m={};switch(p?.kind){case`pending`:{let e=t(`git.pr`);m={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:m={prNumber:p.value.number,prState:p.value.state,prUrl:p.value.url};break;case`failed`:m={prError:p.reason};break;case`earlier`:m={prEarlier:p.value.state};break;case`absent`:case void 0:break}return{branch:n.branch,status:n.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{committedAt:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{tracking:u},...d!==void 0&&{repoName:d},...f!==void 0&&{repoUrl:f},...m}}const AX={pullRequests:e=>nX(e).showPullRequest===!0,rateLimits:e=>tX(e,`block`)||tX(e,`weekly`)};function jX(e,t){let n=new Map;for(let r of Fy(_S(e,t).node)){if(r.kind!==`segment`)continue;let e=n.get(r.name)??[];r.when&&e.push(r.when),n.set(r.name,e)}let r=[...n.keys()].filter(t=>Ky(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,QY(e,t,n.get(t))])),a=e=>r.filter(t=>AX[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}const MX=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function NX(e){if(typeof e==`string`)return MX.exec(e)?.[1]}function PX(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function FX(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function IX(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=PX(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?NX(FX(n)):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&o===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...o!==void 0&&{command:o}}}function LX(e,t){return e===void 0?[ie(t,`.config`,`claude`),ie(t,`.claude`)].filter(e=>f(e)):[e]}async function RX(e){let t=[];for(let n of e){let e=ie(n,`projects`),r=await zX(lo(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(ie(e,n.name))}return t}async function zX(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function BX(e,t,n){let r=[],i=[],a=ie(t,e,`subagents`);try{let t=(await lo(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=ie(a,o);if(n?.has(t)){r.push(t);continue}let s=await go(t,void 0,void 0);if(s.kind!==`ok`){k(`Failed to check agent file ${t}`);continue}i=JX(i,t,s.value);let c=GX(_o(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){k(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function VX(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(UX(t)===`tool_result`)return`tool-result`;let n=typeof e.origin==`object`&&e.origin!==null?e.origin.kind:void 0;if(n!==void 0&&n!==`human`)return`turn`;let r=FX(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||HX.test(r)?`claude-code`:`prompt`}const HX=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function UX(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function WX(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=VX(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:IX(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function GX(e){let t=e.trim();if(!t)return{kind:`blank`};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{kind:`object`,value:e}:{kind:`unparsed`,reason:`not a JSON object`}}catch(e){return{kind:`unparsed`,reason:String(e)}}}function KX(e){let t=GX(e);if(t.kind===`unparsed`)return k(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return WX(t.value)}catch(e){return k(`Failed to project JSONL line: ${e}`),null}}function qX(e){let t=[];for(let n of e.split(`
|
|
192
|
+
`)){let e=KX(n);e&&t.push(e)}return t}function JX(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function YX(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function XX(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await go(e,a===void 0?void 0:{offset:a.offset,ino:a.ino},s?.size);if(t.kind!==`ok`)return t;let c=t.value;c.reset&&(o=n),i=JX(c.reset?[]:i,e,c),(s===void 0||c.reset)&&(s={size:c.size,stamp:c.stamp});let l=c.start+c.lines.length;if(o=await r(o,_o(c,e=>qX(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return F({folded:{cursor:a,value:o},longLines:i})}}
|
|
193
193
|
/*!
|
|
194
194
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
195
195
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -217,9 +217,9 @@ Config tooling:
|
|
|
217
217
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
218
218
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
219
219
|
*/
|
|
220
|
-
function
|
|
220
|
+
function ZX(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function QX(e,t,n){let r=e.split(/\r?\n/),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
|
|
221
221
|
`,e===t&&(i+=` `.repeat(a+n+2),i+=`^
|
|
222
|
-
`))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=
|
|
222
|
+
`))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=ZX(t.toml,t.ptr),i=QX(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}static x(t,n,r){throw new e(t,{toml:n.s,ptr:r??n.p})}};
|
|
223
223
|
/*!
|
|
224
224
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
225
225
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -247,7 +247,7 @@ function QX(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().lengt
|
|
|
247
247
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
248
248
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
249
249
|
*/
|
|
250
|
-
function
|
|
250
|
+
function $X(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);a&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o=``,s=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),a&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c&&=3;else if(n<32&&n!==9||n===127)Q.x(`control characters are not allowed in strings`,e);else if((!c||c===3)&&n===r&&(!a||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(a&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),!c){let t=e.s.slice(s,e.p);o=o?o+t:t}return e.p+=a?3:1,o}else if(!c)!i&&n===92&&(o+=e.s.slice(s,s=e.p),c=1);else if(c===1)if(n===120||n===117||n===85){let t=e.p++-1,r=0,i=n===120?2:n===117?4:8;for(let t=0;t<i;t++,e.p++){let t=e.s.charCodeAt(e.p),n=t>=48&&t<=57?t-48:t>=65&&t<=70?t-65+10:t>=97&&t<=102?t-97+10:-1;n<0&&Q.x(`invalid non-hex character in unicode escape`,e),r=r<<4|n}(r<0||r>1114111||r>=55296&&r<=57343)&&Q.x(`invalid unicode escape`,e,t),o+=String.fromCodePoint(r),s=e.p--,c=0}else a&&(n===32||n===9)?c=2:(n===98?o+=`\b`:n===116?o+=` `:n===110?o+=`
|
|
251
251
|
`:n===102?o+=`\f`:n===114?o+=`\r`:n===101?o+=`\x1B`:n===34?o+=`"`:n===92?o+=`\\`:Q.x(`unrecognised escape sequence`,e),s=e.p+1,c=0);else n!==32&&n!==9&&(c===2&&Q.x(`invalid escape: only line-ending whitespace may be escaped`,e,s),c=+(!i&&n===92),s=e.p);Q.x(`unfinished string`,e,t)}
|
|
252
252
|
/*!
|
|
253
253
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
@@ -276,7 +276,7 @@ function eZ(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCode
|
|
|
276
276
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
277
277
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
278
278
|
*/
|
|
279
|
-
let
|
|
279
|
+
let eZ=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var tZ=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e,t,n){let r=!0,i=!0,a=`Z`,o;if(typeof e==`string`)if(t)prep:{if(t<3){if(+e.slice(11,13)>23){e=``;break prep}t===2?(a=null,e+=`Z`):(o=e.charCodeAt(e.length-1))!==90&&o!==122&&(a=e.slice(e.length-6)),n&&(e=e.slice(0,10)+`T`+e.slice(11))}else t===4&&(e=+e.slice(0,2)>23?``:`0000-01-01T${e}Z`);r=t!==4,i=t!==3}else{let t=e.match(eZ);t?(t[1]||(r=!1,e=`0000-01-01T${e}`),i=!!t[2],i&&e[10]===` `&&(e=e.replace(` `,`T`)),t[2]&&+t[2]>23?e=``:(a=t[3]||null,!a&&i&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=r,this.#t=i,this.#n=a)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`||this.#n===`z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
|
|
280
280
|
/*!
|
|
281
281
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
282
282
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -304,7 +304,7 @@ let tZ=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[
|
|
|
304
304
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
305
305
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
306
306
|
*/
|
|
307
|
-
function
|
|
307
|
+
function nZ(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function rZ(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function iZ(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||Q.x(`document contains excessively nested structures. aborting.`,e);let t=r===91?hZ(e):mZ(e);return e.d++,t}return r===34||r===39?$X(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&Q.x(`invalid value`,e,n),e.p++,!0):r===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&Q.x(`invalid value`,e,n),e.p++,!1):r===43||r===45?aZ(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?cZ(e,r,t):e.s.charCodeAt(e.p+2)===58?lZ(e,r,t):aZ(e,e.p,r,0,t)}function aZ(e,t,n,r,i){let a=n,o=0,s=!1;if(a===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&Q.x(`invalid value`,e,t),e.p++,(r||1)/0;if(a===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&Q.x(`invalid value`,e,t),e.p++,NaN;if(a===48){if(++e.p>=e.s.length||rZ(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return oZ(e,t,16,i);if(a===98)return oZ(e,t,2,i);if(a===111)return oZ(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:Q.x(`illegal leading zero`,e,t)}else nZ(a)||Q.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!rZ(a,i));)o||=1,a===95?(o&1||Q.x(`illegal underscore`,e),o+=11,s=!0):o===1&&a===46?o=2:(o===1||o===3)&&(a===101||a===69)?o=4:o===4&&(a===43||a===45)?o=6:nZ(a)?o>9?o-=11:o&1||o++:Q.x(`illegal character in numeric literal`,e);if(!o){let t=(n-48)*(r||1);return e.bi===!0?BigInt(t):t}o&1||Q.x(`unfinished numeric value`,e,t);let c=e.s.slice(t,e.p);return s&&(c=c.replaceAll(`_`,``)),o>1?parseFloat(c):sZ(e,c,10,t)}function oZ(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!rZ(i,r));)i===95?(a&1&&Q.x(`illegal underscore`,e),a=3):nZ(i,n)?a&1&&a--:Q.x(`illegal character in numeric literal`,e);a&1&&Q.x(`unfinished numeric value`,e);let o=e.s.slice(t+2,e.p);return a&&(o=o.replaceAll(`_`,``)),sZ(e,o,n,t)}function sZ(e,t,n,r){if(e.bi!==!0)int:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break int;Q.x(`integer value cannot be represented losslessly`,e,r)}return i}return BigInt(n===10?t:(n===2?`0b`:n===8?`0o`:`0x`)+t)}function cZ(e,t,n){let r=e.p++,i;if(!nZ(t)||!nZ(e.s.charCodeAt(e.p++))||!nZ(e.s.charCodeAt(e.p++))||!nZ(e.s.charCodeAt(e.p++)))return aZ(e,e.p=r,t,0,n);if(e.p+=5,nZ(e.s.charCodeAt(e.p++))||Q.x(`invalid date-time: date part is malformed`,e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!nZ(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return uZ(e,e.s.slice(r,e.p),3,!1,r);if(e.s.charCodeAt(e.p+=3)!==58&&Q.x(`invalid date-time: time part is malformed`,e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;nZ(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return uZ(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return uZ(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return uZ(e,e.s.slice(r,e.p),2,i,r)}function lZ(e,t,n){let r=e.p;if(!nZ(t)||!nZ(e.s.charCodeAt(++e.p)))return aZ(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;nZ(e.s.charCodeAt(++e.p)););return uZ(e,e.s.slice(r,e.p),4,!1,r)}function uZ(e,t,n,r,i,a){if(e.ld){let a=new tZ(t,n,r);return a.isValid()||Q.x(`invalid date`,e,i),a}try{switch(a&&(t+=a),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(t){Q.x(t instanceof Error?t.message:``+t,e,i)}}
|
|
308
308
|
/*!
|
|
309
309
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
310
310
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -332,7 +332,7 @@ function rZ(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48
|
|
|
332
332
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
333
333
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
334
334
|
*/
|
|
335
|
-
function
|
|
335
|
+
function dZ(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}(t<32&&t!==9||t===127)&&Q.x(`control characters are not allowed in comments`,e)}}function fZ(e,t,n){let r;for(;e.p<e.s.length;){for(;e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10));)e.p++;if(n||r!==35)break;dZ(e)}}
|
|
336
336
|
/*!
|
|
337
337
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
338
338
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -360,7 +360,7 @@ function fZ(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)br
|
|
|
360
360
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
361
361
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
362
362
|
*/
|
|
363
|
-
function
|
|
363
|
+
function pZ(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return r||Q.x(`unexpected end of key`,e),r===1&&i.push(e.s.slice(a,e.p)),e.p++,i;else o===46?(r||Q.x(`illegal empty bare key`,e),r===1&&i.push(e.s.slice(a,e.p)),r=0):!r&&(o===34||o===39)?(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2)&&Q.x(`illegal quoted key: multiline strings are not allowed`,e),i.push($X(e)),r=2,e.p--):o===32||o===9?r===1&&(i.push(e.s.slice(a,e.p)),r=2):r===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122?Q.x(`illegal character in key`,e):r||(r=1,a=e.p);while(o=e.s.charCodeAt(++e.p));Q.x(`incomplete key-value: cannot find end of key`,e,n)}function mZ(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(fZ(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=pZ(e);for(let n=0;n<c.length;n++){n&&(a=o?a[t]:a[t]=Object.create(null)),t=c[n],(o=Object.hasOwn(a,t))&&(typeof a[t]!=`object`||r.has(a[t]))&&Q.x(`trying to redefine an already defined value`,e,s);let i=t===`__proto__`;if(e.uk&&(i||t===`constructor`)){a=e.uk!==1&&Q.x(`document contains an unsafe property`,e,s);break}!o&&i&&Object.defineProperty(a,t,{enumerable:!0,configurable:!0,writable:!0})}o&&Q.x(`trying to redefine an already defined value`,e,s),fZ(e,!0,!0);let l=iZ(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),fZ(e),(i=e.s.charCodeAt(e.p++))===125)return n;i!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished table`,e,t)}function hZ(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(fZ(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(iZ(e,93)),fZ(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished array`,e,t)}
|
|
364
364
|
/*!
|
|
365
365
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
366
366
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -388,7 +388,7 @@ function mZ(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return
|
|
|
388
388
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
389
389
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
390
390
|
*/
|
|
391
|
-
function
|
|
391
|
+
function gZ(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if(a=c?a[s]:a[s]=Object.create(null),o=(l=o[s]).c,i===0&&(l.t===1||l.t===2))return null;if(l.t===2){let e=a.length-1;a=a[e],o=o[e].c}}if(s=t[n],(c=Object.hasOwn(a,s))&&o[s]?.t===0&&o[s]?.d)return null;if(!c){let r=s===`__proto__`;if(e.uk&&(r||s===`constructor`))return!1;r&&(Object.defineProperty(a,s,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})),o[s]={t:n<t.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(l=o[s],l.t!==i&&!(i===1&&l.t===3)||(i===2&&(l.d||(l.d=!0,a[s]=[]),a[s].push(a=Object.create(null)),l.c[l.i++]=l={t:1,d:!1,i:0,c:Object.create(null)}),l.d))return null;if(l.d=!0,i===1)a=c?a[s]:a[s]=Object.create(null);else if(i===0&&c)return null;return[s,a,l.c]}function _Z(e,t,n){(t===null||e.uk===2)&&Q.x(t===null?`trying to redefine an already defined table or value`:`document contains an unsafe property`,e,n)}function vZ(e,t={}){let n={s:e,p:0,d:t.maxDepth??1e3,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour===`throw`?2:+(t.unsafeKeyBehaviour===`drop`)},r=Object.create(null),i=Object.create(null),a,o=!1,s=r,c=i;for(e.charCodeAt(0)===65279&&n.p++,fZ(n);n.p<e.length;){if(e.charCodeAt(n.p)===91){let t=e.charCodeAt(++n.p)===91;a=n.p+=+t,o=!1;let l=pZ(n,93);t&&(e.charCodeAt(n.p)!==93&&Q.x(`expected end of table array declaration`,n),n.p++);let u=gZ(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(_Z(n,u,a),o=!0)}else{a=n.p;let e=gZ(n,pZ(n),s,c,0);!e&&!o&&_Z(n,e,a),fZ(n,!0,!0);let t=iZ(n,void 0);e&&!o&&(e[1][e[0]]=t)}fZ(n,!0),n.p<e.length&&(a=e.charCodeAt(n.p))!==10&&(a!==13||e.charCodeAt(n.p+1)!==10)&&Q.x(`each key-value declaration must be followed by an end-of-line`,n),fZ(n)}return r}``.isWellFormed;
|
|
392
392
|
/*!
|
|
393
393
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
394
394
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -416,7 +416,7 @@ function _Z(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if
|
|
|
416
416
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
417
417
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
418
418
|
*/
|
|
419
|
-
const
|
|
419
|
+
const yZ=e=>e.codePointAt(0).toString(16).toUpperCase(),bZ=String.raw`
|
|
420
420
|
ObjC.import("AppKit");
|
|
421
421
|
ObjC.import("CoreText");
|
|
422
422
|
function lacksOf(font, points) {
|
|
@@ -463,55 +463,55 @@ function run(argv) {
|
|
|
463
463
|
: iterm(argv[1], points),
|
|
464
464
|
);
|
|
465
465
|
}
|
|
466
|
-
`;async function
|
|
467
|
-
`).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const
|
|
468
|
-
`,`:family=${
|
|
469
|
-
`)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function
|
|
466
|
+
`;async function xZ(e,t){let n=await e.launch({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,bZ,...t],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new BJ(`the font`);return{kind:`failed`,reason:`osascript failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}let r;try{r=JSON.parse(n.stdout)}catch{return{kind:`failed`,reason:`osascript answered ${JSON.stringify(n.stdout.trim())}, not JSON`}}return typeof r==`object`&&r&&`error`in r?{kind:`failed`,reason:r.error}:{kind:`ok`,value:r}}const SZ=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),CZ=e=>[...e].map(yZ).join(`,`);async function wZ(e,t,n){let r=await xZ(e,[`font`,t.kind,t.name,CZ(n)]);if(r.kind===`failed`)return r;let{lacks:i}=r.value;return{kind:`ok`,value:{font:t.name,lacks:i===null?null:SZ(i)}}}function TZ(e,t){if(e.font===null)return{kind:`failed`,reason:`iTerm2 profile ${JSON.stringify(e.name)} names no font`};let n=`iTerm2 profile ${JSON.stringify(e.name)}`+(e.nonAscii?`, its non-ASCII font`:``)+(e.powerline?`, built-in Powerline glyphs on`:``),r=e.lacks===null||!e.powerline?e.lacks:e.lacks.filter(e=>!ite(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const EZ=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function DZ(e,t,n){if(e.length===0)return{kind:`failed`,reason:t===null?`iTerm2 has no profiles in its preferences`:`iTerm2 has no profile named ${JSON.stringify(t)}`};let r=e.map(e=>TZ(e,n));if(t!==null)return r[0];let i=r.find(e=>!EZ(e));return i===void 0?{kind:`ok`,value:{font:[...new Set(r.flatMap(e=>e.kind===`ok`?[e.value.font]:[]))].join(`, `),from:`every iTerm2 profile, since the session does not say which draws the bar`,lacks:[]}}:i.kind===`failed`?i:{kind:`ok`,value:{...i.value,from:`${i.value.from}, one of its profiles, and the session does not say which draws the bar`}}}async function OZ(e,t,n,r){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let i=n.ITERM_PROFILE??null,a=await xZ(e,[`iterm`,i??``,CZ(r)]);return a.kind===`failed`?a:DZ(a.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:SZ(e.lacks)})),i,t)}function kZ(e,t){let n=e.split(`
|
|
467
|
+
`).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const AZ=e=>e.replace(/[\\:,=-]/g,`\\$&`);async function jZ(e,t,n){let r=await e.launch({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
|
|
468
|
+
`,`:family=${AZ(t)}`],timeoutMs:3e3,category:`doctor.font`});if(!r.ok){if(r.reason===`rate-limited`)throw new BJ(`the font`);return{kind:`failed`,reason:`fc-match failed (${r.error??`${r.reason}: ${r.stderr.trim()}`})`}}return kZ(r.stdout,n)}function MZ(e,t,n){return process.platform===`darwin`?wZ(e,t,n):jZ(e,t.name,n)}function NZ(e,t){let n=t||E.join(e,`.config`);return[E.join(n,`alacritty`,`alacritty.toml`),E.join(n,`alacritty.toml`),E.join(e,`.config`,`alacritty`,`alacritty.toml`),E.join(e,`.alacritty.toml`)]}function PZ(e){return e===`darwin`?`Menlo`:`monospace`}const FZ=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function IZ(e){let t=FZ(e.font)?e.font:{},n=FZ(t.normal)?t.normal:{},r=(FZ(e.general)?e.general:{}).import??e.import??[];return{family:typeof n.family==`string`?n.family:null,imports:Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}}function LZ(e,t,n){let r;try{r=l.readFileSync(e,`utf8`)}catch(t){return{kind:`failed`,reason:`cannot read ${e}: ${t.message}`}}let i;try{i=vZ(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=IZ(i);if(a.family!==null)return{kind:`ok`,value:{family:a.family,from:e}};if(n===5)return{kind:`ok`,value:null};let o=null;for(let r of a.imports){let i=r.startsWith(`~/`)?E.join(t,r.slice(2)):E.resolve(E.dirname(e),r);if(!l.existsSync(i))continue;let a=LZ(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}async function RZ(e,t,n,r){let i=NZ(r,t.XDG_CONFIG_HOME).find(e=>l.existsSync(e)),a=i===void 0?{kind:`ok`,value:null}:LZ(i,r,0);if(a.kind===`failed`)return a;let o=a.value?.family??PZ(process.platform),s=a.value?.from??(i===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${i} sets none`),c=await MZ(e,{kind:`family`,name:o},n);if(c.kind===`failed`)return c;let{font:u,lacks:d}=c.value;return{kind:`ok`,value:{font:u,from:u===o?s:`${s}; ${o} as fontconfig matches it`,lacks:d}}}const zZ={iterm2:OZ,alacritty:(e,t,n,r,i)=>RZ(e,n,r,i)};function BZ(e,t,n,r,i){return zZ[t.name](e,t.version,n,r,i)}function VZ(e){let t=e?.through;return typeof t==`string`||t===null?{kind:`ok`,value:{through:t}}:{kind:`failed`,reason:`names no post-mortem read`}}const HZ=e=>QH(e,`doctor-post-mortems-read.json`,{through:null},VZ);function UZ(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const WZ={realpath:e=>UZ(()=>l.realpathSync(e)),checkoutOf:Lt,digest:e=>UZ(()=>Pt(e)),nativeShipped:Bo(process.platform,process.arch)};function GZ(e,t,n){let r=e.realpath(t);if(r.kind===`failed`)return{kind:`failed`,reason:`the daemon's bundle ${t} cannot be resolved: ${r.reason}`};let i=e.checkoutOf(r.value);return{kind:`ok`,value:{daemon:{bundle:r.value,checkout:i===null?null:{root:i,rustSource:e.digest(E.join(i,`rust-client`))}},nativeShipped:e.nativeShipped,clients:n.map(t=>t===null?{kind:`unreported`}:{kind:`reported`,client:t.kind,bundle:e.realpath(t.bundle),source:t.source})}}}const KZ=e=>({marks:IJ(e),clicked:zJ(e),postMortemsRead:HZ(e)}),qZ=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function JZ(e){let t=new Map,n=(e,n)=>{let r=JSON.stringify(e),i=t.get(r)??n();return t.set(r,i),i};return{...e,probeTmux:t=>n([`tmux`,t],()=>e.probeTmux(t)),remoteLogin:t=>n([`remote`,t],()=>e.remoteLogin(t)),fontInUse:(t,r,i)=>n([`font`,t,r,i],()=>e.fontInUse(t,r,i))}}function YZ(e){let t=e.replace(/\n$/,``);if(t===` `)return{kind:`ok`,value:null};let n=t.split(` `),[r,i,a,o,s]=n;return n.length!==5||!/^[1-9]\d*$/.test(o)||!/^[01]$/.test(s)?{kind:`failed`,reason:`tmux answered ${JSON.stringify(e)}, not the five fields asked for`}:{kind:`ok`,value:{features:r.split(`,`).filter(e=>e!==``),termtype:i,termname:a,pid:Number(o),utf8:s===`1`}}}const XZ=/^(sshd|mosh-server)\b/;function ZZ(e,t){let n=GJ(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of KJ(n,t))if(XZ.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}async function QZ(e,t){let n=await e.launch({bin:`ps`,args:[`-A`,`-o`,`pid=,ppid=,comm=`],timeoutMs:2e3,category:`doctor.process`});if(!n.ok){if(n.reason===`rate-limited`)throw new BJ(`the processes`);return{kind:`failed`,reason:`ps failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}return ZZ(n.stdout,t)}const $Z=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function eQ(e,t){let n=[];for(let r of e.split(`
|
|
469
|
+
`)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function tQ(e){let t;try{t=l.realpathSync(e)}catch{return!1}let n=$Z.exec(t)?.[1];return n!==void 0&&l.existsSync(E.join(n,`bin`,`cc-candybar`))}async function nQ(e){let t=await e.launch({bin:`ps`,args:[`-U`,String(o.userInfo().uid),`-ww`,`-o`,`pid=,ppid=,rss=,lstart=,args=`],timeoutMs:2e3,category:`doctor.daemons`,envOverlay:{LC_ALL:`C`,TZ:`UTC`}});return t.ok?{kind:`ok`,value:eQ(t.stdout,tQ)}:{kind:`failed`,reason:`ps failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}async function rQ(e,t){let n=await Ws(e,t,`doctor.tmux`,[`display`,`-p`,`-t`,t.pane,`#{client_termfeatures} #{client_termtype} #{client_termname} #{client_pid} #{client_utf8}`]);if(n.kind===`rate-limited`)throw new BJ(`tmux`);return n.kind===`failed`?{kind:`failed`,reason:n.reason}:YZ(n.stdout)}function iQ(e,t,n){return{probeTmux:t=>rQ(e,t),remoteLogin:t=>QZ(e,t),fontInUse:(t,r,i)=>BZ(e,t,r,i,n.home),loadConfig:t,home:n.home,managedSettingsDir:n.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??iee(process.platform),install:WZ,daemons:()=>nQ(e),forge:t=>lQ(e,t),transcript:oQ}}function aQ(e,t){let n=e.toString(`utf-8`),r=t?0:n.indexOf(`
|
|
470
470
|
`)+1,i=n.lastIndexOf(`
|
|
471
471
|
`)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
|
|
472
|
-
`)){let t=
|
|
473
|
-
`)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const
|
|
474
|
-
`:null,r=
|
|
472
|
+
`)){let t=GX(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function oQ(e){let t=xo(e,cF+1);return t.kind===`ok`?F(aQ(t.value.buf,t.value.fromStart)):t}function sQ(e,t){if(t.kind===`failed`)return t;let n=new Map;for(let{path:e,answered:r}of t.value)n.set(e,r||(n.get(e)??!1));return{kind:`ok`,value:[...n].map(([t,n])=>({path:t,answered:n,read:e.transcript(t)}))}}const cQ={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};async function lQ(e,t){if(tc(t)===void 0)return{kind:`ok`,value:null};let n=fY(await e.launch({bin:`git`,args:[...dY],cwd:t,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(n.kind===`failed`)return n;let r=_Y(n.value);if(r===null)return{kind:`ok`,value:null};let i=uY(r);if(i===null)return{kind:`ok`,value:null};let a=aY[i],o=cQ[i],s=o.loginHost(lY(r)),c=await e.launch({bin:a,args:[...o.args(s)],cwd:t,timeoutMs:2e3,category:`doctor.forge`});return uQ(a,s,o.nonZero,c)}function uQ(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):oY(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:nY(r.stderr)}):{kind:`failed`,reason:tY(e,r)}}function dQ(e,t){let n={layers:e.layers,target:t,warnings:e.warning===null?[]:e.warning.split(`
|
|
473
|
+
`)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const fQ=e=>UZ(()=>aee(e));function pQ(e,t){let n=e=>JSON.stringify([e.managedDir,e.projectDir,e.userFile]),r=n(e),i=[],a=new Map;for(let o of t){let t={managedDir:e.managedDir,projectDir:o.projectDir,userFile:To(o.claudeConfigDir)},s=n(t);if(s===r)i.push(o);else{let e=a.get(s)??{at:t,bars:[]};e.bars.push(o),a.set(s,e)}}let o=(e,t)=>({at:e,sources:fQ(e),bars:t.map(({role:e,frame:t})=>({role:e,frame:t}))});return{origin:o(e,i),elsewhere:[...a.values()].map(({at:e,bars:t})=>o(e,t))}}async function mQ(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:await e.probeTmux(t)}}function hQ(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:ste(t),tmuxClient:null};case`inside`:{if(e.client.kind===`failed`)return{kind:`unasked`,reason:e.client.reason};let t=e.client.value;return t===null?{kind:`unasked`,reason:`tmux has no client attached to the pane's session`}:{kind:`seen`,identified:ote(t),tmuxClient:t}}}}async function gQ(e,t,n,r){if(t.kind!==`seen`)return t;let{identified:i,tmuxClient:a}=t,o=n.terminalEnv;if(i.kind!==`known`)return i;let{name:s,version:c}=i.terminal;if(tte(s))return{kind:`bundling`,name:s,version:c};if(!nte(s))return{kind:`unread`,name:s,version:c};let{ITERM_PROFILE:l,...u}=o??{},d=a===null?{kind:`ok`,value:n.ssh===!0}:await e.remoteLogin(a.pid);return{kind:`configured`,name:s,version:c,font:d.kind===`failed`?{kind:`failed`,reason:`whether the terminal is remote could not be asked: ${d.reason}`}:d.value?{kind:`failed`,reason:`the terminal is on the far side of a remote login, so its font is on the machine it runs on`}:await e.fontInUse({name:s,version:c},a===null?o??{}:u,r)}}function _Q(e){switch(e.via){case`link`:return{kind:`arrived`,handler:e.handler,bar:It};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}async function vQ(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:await t()}}async function yQ(e,t,n,r){return{pullRequests:await vQ(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:await vQ(t.rateLimits,()=>r)}}function bQ(e,t){let n=t.find(e=>e.role===`statusline`);return n===void 0?{kind:`failed`,reason:`the daemon holds no statusline render of session ${e} — none since it started, or dropped for newer sessions' renders, or only a frames display draws it, which reports no width — so no width a statusline client measured is known; run this again once the statusline has redrawn`}:{kind:`ok`,value:{columns:n.termCols,of:{kind:`session`,sessionId:e}}}}async function xQ(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=dK(d.config,r,()=>!1),p=await mQ(e,t.tmux),m=hQ(p,t.terminalEnv),h=[...new Set([...VP(f),...BP(JSON.stringify(d.config))])].join(``),[g,_,v]=await Promise.all([h===``?{kind:`none`}:gQ(e,m,t,h).then(e=>({kind:`glyphs`,glyphs:h,terminal:e})),e.daemons(),yQ(e,jX(d.config,f.preset),n,a)]);return{tmux:p,width:l,terminal:m,nerdFont:g,marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:_,read:u.postMortemsRead},config:dQ(d,n.target),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:v,transcripts:sQ(e,o),claudeSettings:pQ({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:To(wo(t.claudeConfigDir,e.home))},c.kind===`ok`?c.value:[])}}function SQ(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;sn(e,Va(Oo(e),t.path,JSON.stringify(t.value),Ea));let r=e=>({...e,sources:fQ(e.at)}),{origin:i,elsewhere:a}=n.claudeSettings;return{kind:`ok`,value:{...n,claudeSettings:{origin:r(i),elsewhere:a.map(r)}}}}case`post-mortems-read`:{let r=e.postMortemsRead.update(e=>e.through===null||_r(t.through,e.through)?{through:t.through}:e);return r.kind===`failed`?r:{kind:`ok`,value:{...n,daemon:{...n.daemon,read:r}}}}default:return t}}const CQ=16384;var wQ=class e{startedAt;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;constructor(e){this.clock=e,this.startedAt=new Date(e.now())}firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;dirWatchesOpened=0;dirWatchesClosed=0;subprocessTotal=0;subprocessInFlight=0;subprocessRefusals=new Map;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;get subprocessRefused(){return this.subprocessRefusals}launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)},onRefused:e=>{this.subprocessRefusals.set(e,(this.subprocessRefusals.get(e)??0)+1)}};recordRollingNow(){let e=this.clock.now();if(this.rollingTimestamps.length<CQ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%CQ}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=this.clock.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,refused:Object.fromEntries(this.subprocessRefused),p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e({now:()=>0}).snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},fileEvents:{delivery:{kind:`delivering`,unreported:[],missedSince:null},stalls:0,catchUps:0,probes:0,probeFailures:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0,pending:0},journalTurns:{holder:null,heldMs:0,queued:0,gathers:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,dirWatchesActive:0,handlerProbes:[],clients:[],bundle:`/`,sourceDigest:null,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:It,sourceDigest:e.sourceDigest,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((this.clock.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,fileEvents:e.fileEvents,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,journalTurns:e.journalTurns,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors,dirs:{active:e.dirWatchesActive,opened:this.dirWatchesOpened,closed:this.dirWatchesClosed}},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};const TQ={connectMs:200,budgetMs:500};async function EQ(e,t){return DQ(await OQ(e),t.includes(`--json`))}function DQ(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`daemon-stats: ${Wn(e)}\n`,code:1};let n=t?JSON.stringify(e.value,null,2)+`
|
|
474
|
+
`:null,r=kQ(e.value);return r===null?{stdout:n??LQ(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function OQ(e){return Ln(e,()=>({kind:`stats`}),TQ,e=>`stats`in e?e.stats:void 0)}function kQ(e,t=AQ){let n=wQ.referenceSnapshot(),r=jQ(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=NQ(e.version,e.sourceDigest??null),a=NQ(It,zt());return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}const AQ=Object.keys(wQ.referenceSnapshot());function jQ(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!MQ(e))return[];if(!MQ(t))return[n||`<snapshot>`];if(`kind`in e)return[];let r=[];for(let i of Object.keys(e)){let a=n===``?i:`${n}.${i}`;i in t?r.push(...jQ(e[i],t[i],a)):r.push(a)}return r}function MQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function NQ(e,t){return`${e} [${t===null?`no digest`:Ft(t)}]`}function PQ(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function FQ(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function IQ(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${e%60}s`:`${Math.floor(e/3600)}h${Math.floor(e%3600/60)}m`}function LQ(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${NQ(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${IQ(e.uptimeSec)}`),t.push(` rss ${PQ(e.rssBytes)}`),t.push(` heapUsed ${PQ(e.heapUsedBytes)}`),t.push(` heapTotal ${PQ(e.heapTotalBytes)}`),t.push(` external ${PQ(e.externalBytes)}`),t.push(` arrayBuffers ${PQ(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(` unknownFields ${e.unknownHookFields.map(e=>JSON.stringify(e)).join(`, `)||`-`}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${FQ(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` changes ${e.gitCache.changes}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${FQ(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`sources`);for(let n of e.sources.records){let e=Object.entries(n.refreshes).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` ${`${n.scope}/${n.name}`.padEnd(24)} failures=${n.failures} last=${n.lastMs===null?`-`:`${n.lastMs}ms`} refreshes ${e}`)}let n=Object.entries(e.sources.homes).map(([e,t])=>`${e}:${t}`).join(` `),r=Object.entries(e.sources.held).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` homes ${n}`),t.push(` held ${r}`);let i=e.sources.pluginStorage,a=Object.entries(i.faults).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` plugin storage folders=${i.folders} lost=${i.lost} faults ${a}`),t.push(` fileEvents ${kc(e.fileEvents)}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${PQ(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${PQ(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` views ${e.renderCache.views}`),t.push(` pinned ${e.renderCache.pinned}`),t.push(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${PQ(e.renderCache.accountedBytes)} / ${PQ(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`menuIdle`),t.push(` sessions ${e.menuIdle.sessions}`),t.push(` armed ${e.menuIdle.armed}`),t.push(` pending ${e.menuIdle.pending}`),t.push(``),t.push(`journalTurns`),t.push(` holder ${e.journalTurns.holder??`-`}`),t.push(` held ${e.journalTurns.heldMs}ms`),t.push(` queued ${e.journalTurns.queued}`),t.push(` gathers ${e.journalTurns.gathers}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` refused ${e.watchers.refused}`),t.push(` errors ${e.watchers.errors}`),t.push(` dirs ${e.watchers.dirs.active} open (${e.watchers.dirs.opened} opened, ${e.watchers.dirs.closed} closed)`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let o=Object.entries(e.subprocesses.byCategory),s=Object.entries(e.subprocesses.refused).map(([e,t])=>[`${e} refused`,t]),c=[...o,...s].reduce((e,[t])=>Math.max(e,t.length),13);for(let[n,r]of o){let i=e.subprocesses.p50DurationMs[n],a=e.subprocesses.p99DurationMs[n],o=i!==void 0&&a!==void 0?` (p50 ${i}ms · p99 ${a}ms)`:``;t.push(` ${n.padEnd(c)} ${r}${o}`)}for(let[e,n]of s)t.push(` ${e.padEnd(c)} ${n}`);return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
|
|
475
475
|
`)+`
|
|
476
|
-
`}const
|
|
477
|
-
`).join(` — `));let n=
|
|
478
|
-
`);return{inMode:r!==`0`,screen:i}}function u$(e,t,n){return[`load-buffer`,`-b`,t,`-`,`;`,...n.length===0?[]:[`send-keys`,`-t`,e,...n,`;`],`paste-buffer`,`-p`,`-d`,`-b`,t,`-t`,e,`;`,`send-keys`,`-t`,e,`Enter`]}async function d$(e,t,n){let r=await c$(e,t,`claude-input.type`,u$(t.pane,`cc-candybar-slash`,[`C-s`]),n);return r.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${r.reason})`}}function f$(e){return{read:t=>l$(e,t),type:(t,n)=>d$(e,t,n)}}function p$(e){let t=typeof e==`string`?e===``?`is empty`:e===`.`||e===`..`?`is ${JSON.stringify(e)}, which names a folder, not a session`:/[/\\\0]/.test(e)?`contains a path separator or NUL: ${JSON.stringify(e)}`:Buffer.byteLength(e,`utf8`)>250?`is longer than 250 bytes`:null:`is not a string: ${JSON.stringify(e)??String(e)}`;return t===null?{ok:!0,id:e}:{ok:!1,problem:t}}const m$=e=>({gathers:!1,prepare:async t=>n=>e(t,n)});function h$(e){let t=p$(e);if(!t.ok)throw new Z(`session id ${t.problem}`);return t.id}function g$(e){return $K(()=>decodeURIComponent(e))}const _$=5e3;function v$(e,t,n,r){if(e.reason===`rate-limited`){r(`warn`,`${t} rate-limited: ${e.said}`);return}throw e.reason===`aborted`?new ZK(n):Error(`${n} failed (${e.reason}, exit ${e.exitCode??`null`})${e.said===``?``:`: ${e.said}`}`)}async function y$(e,t,n,r){let i=await e.launch({...t,timeoutMs:_$});i.ok||v$({reason:i.reason,exitCode:i.exitCode,said:i.error??i.stderr.trim()},t.category,n,r)}async function b$(e,t,n,r,i,a){let o=h(E.join(a,`cc-candybar-handoff-`));try{let a={stdout:`/dev/null`,stderr:E.join(o,`stderr`),status:E.join(o,`status`)},s=e.launchJobSync(t,a);if(!s.ok){v$({reason:s.reason,exitCode:null,said:s.error},t.category,n,r);return}s.release();let c=e.clock.monotonic()+i;for(;;){let o=lt(s.pid),l=st(a.status);if(l!==null){if(l.kind===`exit`&&l.code===0)return;v$(l.kind===`exit`?{reason:`non-zero`,exitCode:l.code,said:_(a.stderr,`utf8`).trim()}:{reason:`timeout`,exitCode:null,said:``},t.category,n,r);return}if(!o)throw Error(`${n} failed (lost): the opener ended with no verdict`);if(e.clock.monotonic()>=c){r(`info`,`${t.category} handed off at ${i}ms, pid ${s.pid}`);return}await A(e.clock,50)}}finally{y(o,{recursive:!0,force:!0,maxRetries:3})}}function x$(e,t){return t.launch({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`)}const S$=(e,t)=>x$(g$(e),t),C$=new Set([`request`,`feed`]);function w$(e){if(!C$.has(e))throw new Z(`unknown renderer ${JSON.stringify(e)}`);return e}const T$=async(e,t)=>{let[n=``,r=``,i=``]=$K(()=>Qi(e)),a=h$(n),o=t.diagnosticCopy(a,w$(r),i);if(o===void 0)throw new Z(`that message is no longer listed in session ${a}'s diagnostics — open ⚠ again and copy from there`);await x$(o,t)},E$=(e,t)=>t.launch({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,g$(e)],category:`click.open`},`open -a "Visual Studio Code"`),D$=async(e,t)=>{let n=h$(g$(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},O$=async(e,t)=>{let[n=``,...r]=$K(()=>Qi(e)),i=h$(n),a=t.gates.state.gateFor(H$(t,i));if(r.length===0)throw new Z(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new Z(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new Z(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new Z(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}M$(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.log(`info`,`set-state: ${s} (session=${i})`)},k$=/^-?\d+$/;function A$(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const j$=async(e,t)=>{let[n=``,r=``,i=``]=$K(()=>Qi(e)),a=h$(n);if(!r)throw new Z(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!k$.test(i))throw new Z(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=H$(t,a),c=t.gates.state.gateFor(s),l=c.rangeParamsFor(r);if(!l)throw new Z(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&k$.test(u)?N$(l,parseInt(u,10)):P$(`step-state`,r,l,RK(s,e=>t.sessionState.get(a,e),r)),f=A$(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new Z(`step-state: ${p.reason}`);M$(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.log(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function M$(e,t,n,r){let i=r.filter(e=>e.key.startsWith(cN));if(i.length===0)return;let a=DK(H$(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new Z(`${n}: refused — ${a.join(`; `)}`)}function N$(e,t){return Math.max(e.min,Math.min(e.max,t))}function P$(e,t,n,r){if(r===null)return n.min;if(!k$.test(r))throw new Z(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return N$(n,parseInt(r,10))}function F$(e,t,n){let r=t.get(n,XK);return r===null?e:{...e,target:{source:`pick`,path:r}}}function I$(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function L$(e){let t;try{t=JSON.parse(e)}catch{throw new Z(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new Z(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i,source:a}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new Z(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,target:I$(a,i)}}function R$(e,t){let n=B$(e,t);if(n===null)throw new Z(`session ${t} has not rendered yet — no config to act on`);return n}function z$(e,t){let n=e.sessionState.get(t,JK);return n===null?null:L$(n)}function B$(e,t){let n=z$(e,t);return n===null?null:F$(n,e.sessionState,t)}function V$(e,t,n){let r=B$(e,t);if(r===null)return;let{path:i}=G$(e,r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function H$(e,t){return e.configFor(R$(e,t))}function U$(e,t){let n=z$(e,t);if(n===null)return null;let r=()=>e.lanes.of(F$(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function W$(e,t){let n=B$(e,t);return n===null?BK:WK(e.configFor(n))}function G$(e,t){return YH(e.locations,kU(e.stateDir).read(),t.projectDir,t.cwd,t.target.path)}function K$(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.log}}const q$=async(e,t)=>{let[n=``,r=``,i=``]=$K(()=>Qi(e)),a=h$(n),o=R$(t,a),s=t.configFor(o),c=t.gates.config.gateFor(s);if(!r)throw new Z(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new Z(`set-config: ${l.reason}`);let u=G$(t,o),d=TK(s,e=>t.sessionState.get(a,e),r);Hq(K$(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.log(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},J$=async(e,t)=>{let[n=``,r=``,i=``]=$K(()=>Qi(e)),a=h$(n);if(!r)throw new Z(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!k$.test(i))throw new Z(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=R$(t,a),c=t.configFor(s),l=t.gates.config.gateFor(c),u=l.rangeParamsFor(r);if(!u)throw new Z(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=G$(t,s),f=TK(c,e=>t.sessionState.get(a,e),r),p=Vq(d.path,f.key),m=typeof p==`number`?N$(u,p):P$(`step-config`,r,u,zK(f.globals,r)),h=A$(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new Z(`step-config: ${g.reason}`);Hq(K$(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.log(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},Y$=async(e,t)=>{let[n=``]=$K(()=>Qi(e)),r=h$(n),i=R$(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=CK(a,o),c=EK(a,o);if(s.length+c.length===0){t.log(`info`,`save: nothing unsaved (session=${r})`);return}let l=t.gates.state.gateFor(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new Z(`save: ${t.reason}`);return[e.target,t.value]});Z$(`save`,l,c);let d=G$(t,i);Uq(K$(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.log(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(X$)].join(` `)} → ${d.path} (session=${r})`)},X$=e=>`${e.preset}/${e.id}.settings.${e.setting}=${tb(e.value)}`;function Z$(e,t,n){for(let r of n){let n=t.validate(r.key,tb(r.value));if(!n.ok)throw new Z(`${e}: ${n.reason}`)}}const Q$=async(e,t)=>{let[n=``]=$K(()=>Qi(e)),r=h$(n),i=R$(t,r),a=t.configFor(i),o=AK(a,e=>t.sessionState.get(r,e)),s=t.gates.state.gateFor(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new Z(`save-preset: ${t.reason}`);return[e.configKey,t.value]});Z$(`save-preset`,s,o.placements);let l=G$(t,i),u=Xq(K$(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Px.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Mx.preset.sessionKey,u),t.log(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(X$)].join(` `)} → ${l.path} (session=${r})`)},$$=async(e,t)=>{let[n=``]=$K(()=>Qi(e)),r=h$(n),i=R$(t,r),a=MK(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new Z(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=G$(t,i);Zq(K$(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(CK(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=Tx.map(e=>Mx[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.log(`info`,`save-theme-default: ${a.theme} ${Tx.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},e1=async(e,t)=>{let[n=``,r=``]=$K(()=>Qi(e)),i=h$(n);if(!r)throw new Z(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=R$(t,i),o=G$(t,a);Qq(K$(t,i),o,r),t.reloadConfig(a);let s=Mx.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.log(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},t1=async(e,t)=>{let[n=``,...r]=$K(()=>Qi(e)),i=h$(n),a=R$(t,i),o=t.gates.config.gateFor(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new Z(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=G$(t,a),l=r.map(NK),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);qq(K$(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.log(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function n1(e,t){let n=(e,t)=>[...Fy(_S(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(mS(t.presets).flatMap(e=>n(t,e).map(t=>lN(Hj(e),jy(t)))));return mS(e.presets).flatMap(t=>n(e,t).map(e=>({member:lN(Hj(t),jy(e)),node:e})).filter(({member:e})=>!r.has(e)))}function r1(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[aN]:[]])}const i1=async(e,t)=>{let[n=``,r=``,i=``]=$K(()=>Qi(e)),a=h$(n),o=R$(t,a),s=t.configFor(o),c=t.gates.config.gateFor(s);if(!r)throw new Z(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new Z(`apply-layout-op: ${l.reason}`);let u=WR(l.value);if(u===null)throw new Z(`apply-layout-op: "${l.value}" is not a layout op token`);let d=G$(t,o),f=$q(K$(t,a),d,r,u);t.reloadConfig(o);let p=r1(n1(s,t.configFor(o)),t.sessionState.get(a,aN)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.log(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},a1=async(e,t)=>{let[n=``]=$K(()=>Qi(e)),r=h$(n);t.journal.commit();let i=t.history.undo(r);t.journal.wrote(),V$(t,r,i),t.log(`info`,`undo: restored ${wJ(i)} (session=${r})`)},o1=async(e,t)=>{let n=h$(g$(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,t.gates.state.gateFor(H$(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.log(`info`,`back: ${a} discarded=${i} (session=${n})`)},s1=async(e,t)=>{let n=h$(g$(e));t.journal.commit(),t.journal.wrote();let r=t.history.rewind(n);V$(t,n,r),t.log(`info`,`rewind: put back ${wJ(r)||`nothing`} as edit mode found it (session=${n})`)},c1=async(e,t)=>{let[n=``]=$K(()=>Qi(e)),r=h$(n);t.journal.commit();let i=t.history.redo(r);t.journal.wrote(),V$(t,r,i),t.log(`info`,`redo: re-applied ${wJ(i)} (session=${r})`)},l1=async(e,t)=>{h$(g$(e)),await t.applyUpdate()};function u1(e,t){let n=e.sessionState.get(t,YK);if(n===null)throw new Z(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new Z(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new Z(`client hints record is not an object: ${n}`);return yn(r)}function d1(e,t,n){let r=zF(n);e.sessionState.setBatch(t,nI(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${UF(n.config)} ${eI(n.nerdFont,n.marks)} ${WF(n.terminal,n.clicked)} ${GF(n.terminal,n.width)} ${KF(n.install)} ${JF(n.daemon)} ${YF(n.data)} ${$F(n.transcripts)} ${XF(n.frames,n.claudeSettings)} ${QF(n.claudeSettings.origin.sources)} (session=${t})`)}async function f1(e,t,n,r){let i={kind:`clicked`,sessionId:t,via:e.arrival.via},a=e.clients.ofSession(t,e.now()),o;try{o=await SQ({...n,loadConfig:()=>r},u1(e,t),R$(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:a.map(e=>e.rateLimits)},{kind:`ok`,value:a.map(e=>e.transcript)},i,{kind:`ok`,value:GJ(i,a)},xQ(t,a),JZ(e.doctorStores))}catch(e){throw e instanceof VJ?new Z(e.message):e}let s={facts:o,install:KZ(n.install,e.bundle,a.map(e=>e.client)),current:async e=>{let i=n.loadConfig(R$(e,t));return i.config===r.config&&i.error===r.error&&i.warning===r.warning?s:f1(e,t,n,i)}};return s}const p1=(e,t)=>{let n=YZ(e.doctor);return f1(e,t,n,n.loadConfig(R$(e,t)))};async function m1(e,t,n){let{facts:r,install:i}=await e.gather(n.current),a=JZ(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:vQ(e.arrival),install:i,clicked:h1(e,o)}}function h1(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?iF(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>zJ(e,r))}catch(t){return e.log(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const g1={gathers:!0,prepare:async(e,t)=>{let n=h$(g$(e)),r=await p1(t,n);return async e=>d1(e,n,await m1(e,n,r))}},_1=async(e,t)=>{let n=UQ(g$(e));if(n===null)throw new Z(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new Z(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.log(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},v1={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``]=$K(()=>Qi(e)),i=h$(n),a=BF(r);if(a===void 0)throw new Z(`doctor-fix: unknown check "${r}"`);let o=await p1(t,i);return async e=>{let t=await m1(e,i,o),n=a.probe(t);if(n.ok||n.fix===void 0)throw new Z(`doctor-fix: ${a.label} — ${n.ok?`nothing to fix`:n.reason}`);let r=CQ(e.doctorStores,n.fix,t);if(r.kind===`failed`)throw new Z(`doctor-fix: ${a.label} — ${r.reason}`);e.log(`info`,`doctor-fix: ${a.name} → ${fte(n.fix)} (session=${i})`),d1(e,i,r.value)}}},y1={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``,i=``]=$K(()=>Qi(e)),a=h$(n),o=BF(r);if(o===void 0)throw new Z(`doctor-mark: unknown check "${r}"`);if(!cF.includes(i))throw new Z(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${cF.join(` or `)}`);let s=await p1(t,a);return async e=>{let t=await m1(e,a,s),n=o.probe(t);if(n.ok||n.sighting===void 0)throw new Z(`doctor-mark: ${o.label} — ${n.ok?`nothing to mark`:`shows nothing to look at`}`);let r=[o.name,n.sighting.id,i],c=e.doctorStores.marks.update(e=>IJ(e,...r));if(c.kind===`failed`)throw new Z(`doctor-mark: ${c.reason}`);e.log(`info`,`doctor-mark: ${o.name} ${i} on ${n.sighting.id} (session=${a})`),d1(e,a,{...t,marks:c})}}},b1=async(e,t)=>{let[n=``,r=``]=$K(()=>Qi(e)),i=h$(n),a=Object.values(t.configFor(R$(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new Z(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=await t.typing(u1(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.log(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new Z(`${r} was not typed: ${s.reason}`);t.log(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)};function x1([e=``,t=``,n=``,r=``],i){let a=h$(e),o=R$(i,a),s=i.configFor(o).actions,c=Object.hasOwn(s,t)?s[t]:void 0;if(c===void 0||!(`run`in c))throw new Z(`"${t}" is not a run action this session's config declares`);let l=AS(c);if(!i.links.verify({sessionId:a,action:t,declaration:l,evaluated:n},r))throw new Z(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let u;try{u=JSON.parse(n)}catch{throw new Z(`run ${t}: what the link carries is not JSON`)}let[d,...f]=u.run;if(d===void 0||d===``)throw new Z(`run ${t}: the program evaluated to nothing`);let p=i.sourcesFor(o);return{sessionId:a,action:t,argv:[d,...f],envOverlay:{...NJ({sessionId:a,projectDir:o.projectDir,claudeConfigDir:u1(i,a).claudeConfigDir}),...u.env},cwd:c.cwd??i.locations.home,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const S1=new Map([[wi,m$(S$)],[Di,m$(async(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new Z(`load-config: expected <sessionId>/<path> (missing separator)`);let r=h$($K(()=>decodeURIComponent(e.slice(0,n)))),i=$K(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new Z(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new Z(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,XK),t.log(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,XK,i),t.log(`info`,`load-config: ${i} (session=${r})`))})],[Ti,m$(E$)],[Si,m$(O$)],[Ci,m$(j$)],[Oi,m$(q$)],[ki,m$(J$)],[Pi,m$(t1)],[Ai,m$(Y$)],[ji,m$(Q$)],[Mi,m$($$)],[Ni,m$(e1)],[Fi,m$(i1)],[Ii,m$(a1)],[Li,m$(c1)],[Ri,m$(o1)],[zi,m$(s1)],[Ei,m$(D$)],[Bi,m$(l1)],[Vi,g1],[Hi,v1],[Ui,y1],[Wi,m$(_1)],[Gi,m$(b1)],[`run`,m$(async(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=$K(()=>Qi(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=x1(i,t)}catch(e){throw e instanceof Z&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)})],[Ki,m$(async(e,t)=>{let[n=``,r=``,i=``,a=``]=$K(()=>Qi(e)),o=h$(n),s=i;if(!t.links.verify(jU(o,r,s),a))throw new Z(`the answer's signature does not match what it carries: it was not drawn by this daemon`);let c=AU(kU(t.stateDir),r,s);if(c.kind===`failed`)throw Error(`${r} was not ${s}: ${c.reason}`);t.journal.wrote();let{superseded:l,absent:u,unchecked:d}=c.value;t.log(`info`,`repo-config: ${r} ${s} superseded=${l.join(`,`)||`-`} absent=${u.join(`,`)||`-`} unchecked=${d.length===0?`-`:JSON.stringify(d)} (session=${o})`),t.reloadConfig(R$(t,o))})],[qi,m$(T$)]]),C1=new Set([Si,Ci,Oi,ki,Pi,Ai,ji,Mi,Ni,Fi,Ii,Li,Ri,zi,Ei,Bi,Vi,Hi,Ui,Gi,`run`,Ki,Di,qi]);function w1(e,t){return T1(e===`dispatch`?ta(t):[{verb:e,value:t}])}function T1(e){let t=e.find(e=>C1.has(e.verb)),n=t===void 0?``:$K(()=>$i(t.value));return n===``?null:p$(n)}const E1=(e,t,n)=>n.journalTurns.gathering(()=>e.prepare(t,n)).catch(e=>()=>Promise.reject(e));async function D1(e,t,n,r){await(r??await n.gather(n=>e.prepare(t,n)))(n)}async function O1(e,t){let[n]=ra(ta(e)),r=n===void 0?void 0:S1.get(n.verb);return r?.gathers?E1(r,n.value,t):void 0}async function k1(e,t,n){let r=[],i=!1,a=ta(e),o=T1(a);for(let[e,{verb:o,value:s}]of ra(a).entries()){let a=S1.get(o);if(!a){r.push(`unknown effect verb "${o}"`);continue}try{await D1(a,s,t,e===0?n:void 0)}catch(e){if(e instanceof ZK)throw r.length>0&&t.log(`warn`,`dispatch: ${r.join(`; `)}`),e;e instanceof Z||(i=!0),r.push(`${o}: ${e instanceof Error?e.message:String(e)}`)}}if(r.length>0){o?.ok&&Ks(t.sessionState,o.id,r.join(`
|
|
479
|
-
`),t.now());let e=`dispatch: ${r.join(`; `)}`;throw i?Error(e):new Z(e)}}function A1(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}async function j1(e,t,n,r){let i=e===null?null:U$(t,e),a=t.history.begin(),o=t.navigation.begin(a.sessionState),s=n.holds(()=>{let e=[];for(let t of[o,a])try{t.commit()}catch(t){e.push(t)}A1(e)}),c=[],l=e=>qK(e,e=>W$(t,e),e=>t.log(`info`,e)),u={...t,sessionState:l(a.sessionState),journal:a,navigating:l(o.sessionState)},d={launch:(e,r)=>n.landed(y$(t.launcher,e,r,t.log)),typing:(e,r)=>n.landed(s$(t.claudeInput,e,r)),applyUpdate:()=>n.landed(t.applyUpdate())};try{await r({...u,...d,gather:e=>n.landed(e(u))})}catch(e){c.push(e)}let f=!0;try{f=s()}catch(e){c.push(e)}if(f&&i!==null)try{let e=i.read();t.lanes.clicked(i.sessionId,a.written()?i.before:e,e)}catch(e){c.push(e)}if(f&&e!==null)try{let n=B$(t,e);n!==null&&t.views.follow(e,n)}catch(e){c.push(e)}A1(c)}function M1(e,t,n){return async(r,i)=>{let a=w1(e,r),o=a?.ok?a.id:null;return i.journalTurns.click(e,o,{placed:i.placeWaited,waited:i.turnWaited,gone:i.clientGone,gathered:i.gatherTook},()=>t(r,i),(e,t)=>j1(o,i,t,async t=>{try{await n(r,t,e)}finally{o!==null&&i.clickLanded(o)}}))}}const N1=new Map([...[...S1].map(([e,t])=>[e,M1(e,async(e,n)=>t.gathers?E1(t,e,n):void 0,(e,n,r)=>D1(t,e,n,r))]),[xi,M1(xi,O1,k1)],[Wi,_1]]);Object.freeze([...N1.keys()]);function P1(e,t,n){return n.journalTurns.take(`menu-idle`,{waited:t=>n.log(`info`,`menu-idle: waited=${t}ms (session=${e})`),gone:()=>!1},r=>j1(e,n,r,async n=>{if(!t.stillIdle()){n.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}t.closed();let r=KK(W$(n,e),t=>n.navigating.get(e,t));n.navigating.setBatch(e,r.map(({key:e})=>({key:e,value:Yr}))),n.log(`info`,`menu-idle: closed=${r.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)}))}function F1({projectDir:e,cwd:t,target:n}){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path??null,source:n.source})}function I1(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const L1={kind:`hidden`},R1={kind:`shown`};function z1(e,t){try{return I1(e,t)?R1:L1}catch(e){let t=BC(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function B1(e,t){let n=K.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function V1(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function H1({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function U1({text:e,placement:t,lead:n,trail:r}){return{text:W1(e),placement:t,...n!==void 0&&{lead:W1(n)},...r!==void 0&&{trail:W1(r)}}}function W1(e){let t=e.blankCopy(e.plain);t.style=VN(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(VN(i).clearMetaAndLinks(),n,r);return t}function G1(e){let t=H1(e);if(t.length===1)return e.text;let n=B1(t);return n.style=e.text.style,n}function K1(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,placement:s,lead:c=[],trail:l=[]}=t;if(e.length===0)return[];let u=B1(e,a).pad(o),d=new K(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:B1([d,...c],a)},...l.length>0&&{trail:B1([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(V1(u,n,p),[{text:u,...f}])}function q1(e,t,n){let r=`x`.repeat(Math.min(n,t)).replace(/x$/,` `),i=r+e,a=[],o=0;return UP(i,t).forEach(e=>{let t=e.trimEnd(),n=i.indexOf(t,o);t!==``&&n>r.length&&a.push(n-r.length),o=n+t.length}),a}function J1(e,t){if(e.length===0)return 0;let{lines:n}=WP(e.map(({owner:e})=>e),t),r=z(kP(n[n.length-1]));return Math.max(0,r-LP(t)+RP(t))}function Y1(e,t,n){if(e.cellLength<=t)return!0;let{lines:r}=WP([e],{...n,width:1/0});return z(kP(r.flat()))<=n.width}function X1(e,t,n,r){if(Y1(e.owner,t,r))return[e];let i=e.owner.copy().expandTabs(),a=J1(n,r);return i.divide(q1(i.plain,t,a)).map((n,i)=>({...e,owner:n.truncate(t,{marker:``}).padLeft(i>0?r.padding:0)})).filter(({owner:e},t,{length:n})=>n===1||e.plain.trim()!==``)}function Z1(e,t){let n=Math.max(2,HP(t)-LP(t)-t.padding);return Q1(e,t).reduce((e,r)=>[...e,...X1(r,n,e,t)],[])}function Q1(e,t){let n=()=>e.map(e=>({owner:G1(e),placement:e.placement})),r=[];if(e.forEach(({fill:e},t)=>{e!==void 0&&r.push({at:t,how:e})}),r.length===0||!Number.isFinite(t.width))return n();let i=WP(e.map(G1),t).lines;if(i.length>1)return n();let a=Math.max(0,t.width-z(kP(i.flat()))),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];V1(c,c.cellLength+a,n)}),n()}function $1(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=e0(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:VN(a.style)};if(e.style.link){i();let r=e0([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function e0(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>t0(e.frag,n?n.add(e.style):e.style)),i=K.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function t0(e,t){let n=e.copy();return n.style=t,n}function n0(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function r0(e,t){let{look:n}=n0(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function i0(e,t){let{layout:n}=n0(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function a0(e,t){if(e.bound!==void 0)throw Error(`a render bound a compile another render holds`);return e.bound=t,{[Symbol.dispose]:()=>{e.bound=void 0}}}function o0(e,t,n,r){let i=new Map,a=Object.entries(t);for(let[t,o]of[...a.filter(([,e])=>!(`do`in e)),...a.filter(([,e])=>`do`in e)])i.set(t,s0(e,t,o,n,r,i));return i}function s0(e,t,n,r,i,a){if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=ES(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,labelOf:t.labelOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=Lx.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=ES(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,labelOf:t.labelOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=ES(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,labelOf:e.labelOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:u0(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:u0(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`slash`in n)return{kind:`slash`,line:n.slash};if(`run`in n)return{kind:`run`,name:t,declaration:AS(n),argv:n.run.map(n=>u0(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,u0(e,r,t)])};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:u0(e,n.name,t)};if(`themeDefault`in n)return{kind:`theme-default-save`};let[o,...s]=n.do.map(e=>{let n=a.get(e);if(n===void 0)throw Error(`action "${t}" fires "${e}", which is not declared in this config`);return n});return{kind:`do`,head:o,rest:s}}function c0(e){return e.kind===`do`?c0(e.head):e}function l0(e){switch(c0(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`slash`:case`run`:case`do`:return!1}}function u0(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function d0(e,t){return e.has(t)?IC(e.read(t)):``}function f0(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function p0(e,t,n,r){let i=new K(e,{style:U.combine([r,new U({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function m0(e,t,n=!1){let r=new U({link:t,bold:n?!0:void 0}),i=new K(e.plain,{style:U.combine([VN(e.style),r])});for(let t of e.spans)i.stylize(U.combine([VN(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function h0(e,t){return Math.max(e.members.indexOf(d0(t,e.stateVar)),0)}function g0(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=d0(r,e.stateVar);return{effects:[{verb:Si,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=d0(r,e.stateVar);return{effects:[{verb:Si,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=d0(r,e.stateVar);return{effects:[{verb:Si,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(h0(e,r)+1)%e.members.length];return{effects:[{verb:Si,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Ci,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:wi,args:[f0(e.text,ej(r))]}],active:!1};case`open`:return{effects:[{verb:Ti,args:[f0(e.target,ej(r))]}],active:!1};case`persist-literal`:{let t=d0(r,e.stateVar);return{effects:[{verb:Oi,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=d0(r,e.stateVar);return{effects:[{verb:Oi,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(h0(e,r)+1)%e.members.length];return{effects:[{verb:Oi,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:ki,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Pi,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:Ii,args:[i]}],active:!1};case`redo`:return{effects:[{verb:Li,args:[i]}],active:!1};case`back`:return{effects:[{verb:Ri,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:zi,args:[i]}],active:!1};case`save`:return{effects:[{verb:Ai,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:ji,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Mi,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Ni,args:[i,f0(e.name,ej(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:Vi,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Hi,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:Ui,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:Gi,args:[i,e.line]}],active:!1};case`run`:{let t=ej(r),n=JSON.stringify({run:e.argv.map(e=>f0(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,f0(n,t)]))}),o=a.sign({sessionId:i,action:e.name,declaration:e.declaration,evaluated:n});return{effects:[{verb:`run`,args:[i,e.name,n,o]}],active:!1}}case`layout-op`:return{effects:[{verb:Fi,args:[i,e.key,UR(e.op)]}],active:!1};case`do`:{let o=g0(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>g0(e,t,void 0,r,i,a).effects)],active:o.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Fi,args:[i,e.key,UR(r)]}],active:!1}}}}function _0(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:$r(`action "${e}"`,n,t.members.length,h0(t,r)),boundValue:void 0};if(n.length>2)throw Error(`action "${e}" takes a display and an optional bound value, got ${n.length} arguments (per-state displays are a cycle action's form)`);return{display:n[0],boundValue:n[1]?.plain}}function v0(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=n0(n,`action "${e}"`).store,{display:a,boundValue:o}=_0(e,c0(r),t,i),s=d0(i,`session.id`),{effects:c,active:l}=g0(r,a.plain,o,i,s,n.signer);return m0(a,ea(c),l)}function y0(e){return{action:{fn:(t,...n)=>v0(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function b0(e,t){return p0(`✕`,ea([{verb:Si,args:[d0(e,`session.id`),t,Yr]}]),!1)}function x0(e,t,n){return new U({bgcolor:H.fromRgba(t),color:H.fromRgba(bv(e,t,n))})}function S0({tint:e,text:t}){return new U({bgcolor:H.fromRgba(e),color:H.fromRgba(t)})}function C0(e,t,n){return new U({color:H.fromRgba(Mu(e.get(`warning`),t,yv,n))})}function w0(e,t,n){return U.combine([x0(e,t,n),C0(e,t,n)])}function T0(e,t,n){return S0(Mv(e.palette,e.disclosure,t,n))}function E0(e){let t=H.fromRgba(e.get(`background`)),n=K.fromFragments(S_.map(n=>new K(`▀`,{style:new U({color:H.fromRgba(e.get(n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const D0=(e,t)=>{let n=typeof e==`string`?new K(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},O0=e=>new U({bold:e});function k0(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>D0(a,U.combine([T0(e,{...n,distribution:t},i),O0(o)]));let o=x0(e.palette,a,i);return(e,t,i,a)=>A0(i,U.combine([o,O0(a)]),r(t,n))}const A0=(e,t,n)=>D0(K.fromFragments([D0(e,t),D0(` `,t),E0(n)]));function j0(e,t,n,r){return t===void 0?D0(r):A0(r,void 0,t(n,e))}function M0(e,t,n,r,i){let a=x0(e.palette,i,r);return(e,r,i,o)=>D0(K.fromFragments([D0(o?`[`:` `,a),E0(n(r,t)),D0(o?`]`:` `,a)]))}function N0(e,t,n){let r=t.map(t=>({label:t.label,indices:e.flatMap((e,n)=>e.group===t.id?[n]:[])})).filter(e=>e.indices.length>0);if(r.reduce((e,t)=>e+t.indices.length,0)!==e.length){let n=new Set(t.map(e=>e.id)),r=e.flatMap((e,t)=>n.has(e.group)?[]:[`#${t} (group "${e.group}")`]);throw Error(`library: ${r.join(`, `)} name a group the domain does not list (${[...n].join(`, `)})`)}return n?r.flatMap(e=>P0(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function P0(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function F0(e,t){return new K(e).truncate(t,{marker:`…`}).plain}function I0(e){return{current:null,drawnAt:e}}function L0(e,t,n,r,i,a,o){let s={segName:t,placementId:n,palette:r,disclosure:i,tint:a,text:o,bg:void 0,drops:[]};return e.current=s,s}function R0(e,t,n){return B0(e,()=>n(L0(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function z0(e,t){return B0(e,()=>(e.current=null,t()))}function B0(e,t){let n=e.current;try{return t()}finally{e.current=n}}function V0(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function H0(e){return new K(e).cellLength}function U0(e){let{width:t,chromeCols:n,padding:r}=n0(e,`a row fit`);return Math.max(1,t-n-2*r)}function W0(e){let{padding:t,seamCols:n}=n0(e,`a row fit`);return Math.max(1,U0(e)-(H0(`✕`)+2*t+n))}function G0(e,t,n){if(!Number.isFinite(t))return e.length>0?[e.map((e,t)=>t)]:[];let r=Math.max(1,t-n),i=[],a=[],o=0;for(let t=0;t<e.length;t++){let n=e[t];a.length===0?(a=[t],o=n):o+1+n<=r?(a.push(t),o+=1+n):(i.push(a),a=[t],o=n)}return a.length>0&&i.push(a),i}function K0(e,t,n){let r=H0(`←`)+1+H0(`→`)+1,i=G0(e,t,n);return(i.length>1?G0(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function q0(e){let t=[];for(let n of e)t.length>0&&t.push(new K(` `)),t.push(n);let n=K.fromFragments(t);return n.overflow=`ignore`,n.end=``,n}function J0(e,t,n,r,i){let a=e.compiled.get(t);if(!a||a.kind!==n)throw Error(`${i} references action "${t}" which must be ${r}, got ${a?`a ${a.kind} action`:`no such action`}`);return a}function Y0(e,t,n){let r=e.compiled.get(t),i=r&&c0(r);if(!i||i.kind!==`set-option`&&i.kind!==`persist-option`&&i.kind!==`layout-op-option`)throw Error(`${n} references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${i?`a ${i.kind} action`:`no such action`}`);return i}function X0(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=n0(a,`picker`).store,d=d0(u,`session.id`),f=`stateVar`in t?d0(u,t.stateVar):void 0,p=(e,n)=>{let r=t.options[e];return o({index:e,count:t.options.length},r,n,r===f)},m=i?r.kind===`led`?W0(a):U0(a):1/0,h=(r.kind===`led`?0:H0(`✕`)+1)+c.reduce((e,t)=>e+H0(t.glyph)+1,0),g=t.library&&{groups:t.library.groups,entries:t.options.map(t.library.entry)},_=t.labelOf??(e=>e),v=g===void 0?t.options.map((e,t)=>p(t,_(e))):[],y=g===void 0?K0(v.map(e=>e.cellLength),m,h):N0(g.entries,g.groups,i),b=parseInt(d0(u,n.stateVar),10),x=e=>Math.max(0,y.findIndex(t=>t.some(t=>t.indices.includes(e)))),S=x(f===void 0?-1:t.options.indexOf(f)),C=Number.isInteger(b)?b<0?S:Math.min(b,y.length-1):0,w=y[C]??[],ee=e=>ea([{verb:Si,args:[d,n.key,String(e)]}]),T=r.kind===`led`?[]:[{verb:Si,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],te=r.kind===`own`&&r.onPick?T:[],E=e=>ea([...g0(l,e,e,u,d,a.signer).effects,...te]),ne=(e,n)=>m0(e,E(t.options[n])),D=r.kind===`led`?[]:[p0(`✕`,ea(T),!1,s)];D.push(...c.map(({glyph:e,option:r})=>p0(e,ea([...g0(l,r,r,u,d,a.signer).effects,{verb:Si,args:[d,n.key,String(x(t.options.indexOf(r)))]}]),!1))),C>0&&D.push(p0(`←`,ee(C-1),!1));let re=C<y.length-1?[p0(`→`,ee(C+1),!1)]:[];if(g===void 0){let e=w.flatMap(e=>e.indices);return[q0([...D,...e.map(e=>ne(v[e],e)),...re])]}let ie=new U({bold:!0}),O=y.length>1?` ${C+1}/${y.length}`:``,ae=w.length===1?[new K(`${w[0].label}${O}`,{style:ie})]:[],oe=[q0([...D,...ae,...re])];for(let e of w){w.length>1&&oe.push(q0([new K(e.label,{style:ie})]));let n=Math.max(...e.indices.map(e=>H0(_(t.options[e]))));for(let r of e.indices){let e=_(t.options[r]),i=g.entries[r].description,a=i===void 0?void 0:cP(i),o=` `.repeat(n-H0(e)+2),s=a===void 0?e:`${e}${o}${a}`;oe.push(q0([ne(p(r,F0(s,m)),r)]))}}return oe}function Z0(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{AA(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=J0(e,r,`set-int`,`an int action ({ set, int: true })`,`picker`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=Y0(e,n,`picker`),u=V0(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let d=t.drawnAt(),f=t=>X0(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,k0(u,iv(void 0),r0(e,`{{ picker }}`),l.paletteOf,d,t),C0(u.palette,t,d)),p=Av(u.palette,u.disclosure,d),[,...m]=l.library===void 0?[]:f(p.plane);return m.length===0?f(u.bg)[0]:(u.drops.push(...m),f(p.state)[0])},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function Q0(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function $0(e,t,n,r,i){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let a=n0(i,`carousel`).store;if(!a.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let o=i.compiled.get(e),s=d0(a,`session.id`),{options:c}=t;if(c.length===0)return q0([]);let l=Q0(c,d0(a,t.stateVar)),u=e=>c[l(e)],d=e=>ea(g0(o,u(e),u(e),a,s,i.signer).effects);return q0([p0(`◀`,d(-1),!1),m0(j0(r0(i,`{{ carousel }}`),t.paletteOf,u(0),r),ea(g0(i.compiled.get(n),u(0),void 0,a,s,i.signer).effects)),p0(`▶`,d(1),!1)])}function e2(e){return{carousel:{fn:(t,n,r)=>{if(r.trim()===``)throw Error(`carousel "${t}": label is empty`);if(!e.compiled.has(n))throw Error(`carousel "${t}": open must name a declared action, got ${JSON.stringify(n)}`);if(l0(e.compiled.get(n)))throw Error(`carousel "${t}": open "${n}" writes a value the template binds, and the label binds none — name an action that writes a fixed value, a cycle, or a do of them`);return $0(t,Y0(e,t,`carousel`),n,r,e)},argTypes:[`string`,`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}function t2(e,t,n){let r=Y0(e,t,n);if(!(`stateVar`in r))throw Error(`${n} references action "${t}", which inserts a segment and holds no current value — a ${n} needs a { set, from } or { persist, from } action`);if(r.paletteOf===void 0)throw Error(`${n} references action "${t}", whose options are not colour-valued — a swatch draws the palette an option puts in force, as the "themes", "placementThemes" and "styles" domains do`);return r}function n2(e,t,n){let r=Math.imul(e^e>>>16,73244475);return r=Math.imul(r^r>>>16,73244475),r^=r>>>16,(n+1+(r>>>0)%Math.max(t-1,1))%t}function r2(e,t,n,r){let i=t2(e,t,n),a=r??d0(n0(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,r0(e,`{{ ${n} }}`))}function i2(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(AA(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return E0(r2(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function a2(e,t,n){return{swatches:{fn:(r,i)=>{let a=t2(e,r,`swatches`),o=J0(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=V0(t,`{{ swatches }}`);if(s.bg===void 0)throw Error(`{{ swatches }} is not available while segments.${s.segName}'s own "bg:" is being evaluated — a swatch row is drawn on that background`);let c=t.drawnAt(),{options:l}=a,u=l.length,[d]=X0(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,M0(s,r0(e,`{{ swatches }}`),a.paletteOf,c,s.bg),C0(s.palette,s.bg,c),u===0?[]:(()=>{let t=Q0(l,d0(n0(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[n2(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const o2=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function s2(e,t,n,r){let i=Av(e,n,r),a=(t,n)=>({text:t,colour:n,ink:bv(e,n,r)});return[[W_(e,t,r).map((n,i)=>{let a=vv(e,n);return{text:o2[i%o2.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,e.get(`warning`)),a(`error`,e.get(`error`))]]]}function c2(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new K(` ${e} `,{style:S0({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new K(e)),r.push(a)}return r}function l2(e,t,n,r,i){let a=s2(e,t,n,r).map(e=>c2(e,i)),o=K.fromFragments(a.flatMap((e,t)=>t===0?e:[new K(`
|
|
480
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}function
|
|
481
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}const
|
|
476
|
+
`}const RQ=e=>({kind:`ok`,value:e}),zQ=e=>({kind:`failed`,reason:e});var BQ=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const VQ=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function HQ(e){return VQ.test(e)?e:null}function UQ(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return RQ(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return RQ({app:n,missing:zQ(`its script could not be read (${r.reason})`)});let i=Zo(r.value);return RQ({app:n,missing:i===null?zQ("its script is not one `cc-candybar install` wrote"):RQ([i.node,i.script].filter(t=>!e.exists(t)))})}async function WQ(e,t){let n=e.now()+5e3;for(;e.now()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,handler:r.handler,bar:n.value.version}}return null}async function GQ(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${bi}://${Wi}/${n}`);return(r===null?await WQ(e,n):null)??{kind:`lost`,unopened:r,opener:UQ(e)}}function KQ(e,t,n,r){let i=e.launchSync({bin:n,args:[...r],category:t,timeoutMs:5e3});return i.ok?RQ(i.stdout):zQ(i.stderr.trim()||i.error||i.reason)}const qQ=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${bi}://probe"));u.isNil() ? "" : u.path.js`;async function JQ(e){let t=await OQ(e);if(t.kind!==`ok`)return zQ(Wn(t).split(`
|
|
477
|
+
`).join(` — `));let n=kQ(t.value,[`handlerProbes`]);if(n!==null)return zQ(n);let{version:r,handlerProbes:i}=t.value;return RQ({version:r,arrivals:i})}function YQ(e,t){let{host:n,clock:r}=t;return{platform:process.platform,sockets:{own:Gt(n),handler:Kt()},now:()=>r.now(),nonce:le,daemon:()=>JQ(t),open:t=>{let n=KQ(e,`doctor.open`,`/usr/bin/open`,[`-g`,t]);return n.kind===`ok`?null:n.reason},pause:()=>A(r,100),opener:()=>{let t=KQ(e,`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,qQ]);if(t.kind===`failed`)return t;let n=t.value.trim();return RQ(n===``?null:n)},script:t=>KQ(e,`doctor.osadecompile`,`/usr/bin/osadecompile`,[Qo(t)]),exists:l.existsSync}}const XQ=/^─{20,}/,ZQ=/^❯(\s|$)/,QQ=/›\s*stashed$/;function $Q(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>XQ.test(e)?[t]:[]).at(-2);return n===void 0||!ZQ.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function e$(e){if(e.inMode)return{kind:`in-mode`};let t=$Q(e);return t===null?{kind:`no-prompt`}:QQ.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function t$(e){return/^❯\s*\S/u.test($Q(e)?.prompt??``)}const n$=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function r$(e){return e.screen.some(e=>n$.test(e))}const i$={"in-mode":`the Claude Code pane is in tmux copy mode — leave it (q) and click again`,stashed:`Claude Code is holding a stashed prompt (ctrl+s) — restore or send it, then click again`,"no-prompt":`Claude Code is not at its prompt (a dialog or picker is open) — close it and click again`};function a$(e){return e===void 0?{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`}:e===null?{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only act in a tmux pane`}:{kind:`pane`,hint:e}}async function o$(e,t,n){let r=a$(t);if(r.kind===`refused`)return r;let i=r.hint,a=e$(await e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:i$[a.kind]};let o=await e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}async function s$(e,t,n,r,i){let a=await Ws(e,t,n,r,i);if(a.kind===`failed`)throw Error(a.reason);return a}async function c$(e,t){let n=await s$(e,t,`claude-input.read`,[`display`,`-p`,`-t`,t.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,t.pane]);if(n.kind===`rate-limited`)throw Error(n.reason);let[r=``,...i]=n.stdout.split(`
|
|
478
|
+
`);return{inMode:r!==`0`,screen:i}}function l$(e,t,n){return[`load-buffer`,`-b`,t,`-`,`;`,...n.length===0?[]:[`send-keys`,`-t`,e,...n,`;`],`paste-buffer`,`-p`,`-d`,`-b`,t,`-t`,e,`;`,`send-keys`,`-t`,e,`Enter`]}async function u$(e,t,n){let r=await s$(e,t,`claude-input.type`,l$(t.pane,`cc-candybar-slash`,[`C-s`]),n);return r.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${r.reason})`}}function d$(e){return{read:t=>c$(e,t),type:(t,n)=>u$(e,t,n)}}function f$(e){let t=typeof e==`string`?e===``?`is empty`:e===`.`||e===`..`?`is ${JSON.stringify(e)}, which names a folder, not a session`:/[/\\\0]/.test(e)?`contains a path separator or NUL: ${JSON.stringify(e)}`:Buffer.byteLength(e,`utf8`)>250?`is longer than 250 bytes`:null:`is not a string: ${JSON.stringify(e)??String(e)}`;return t===null?{ok:!0,id:e}:{ok:!1,problem:t}}const p$=e=>({gathers:!1,prepare:async t=>n=>e(t,n)});function m$(e){let t=f$(e);if(!t.ok)throw new Z(`session id ${t.problem}`);return t.id}function h$(e){return QK(()=>decodeURIComponent(e))}const g$=5e3;function _$(e,t,n,r){if(e.reason===`rate-limited`){r(`warn`,`${t} rate-limited: ${e.said}`);return}throw e.reason===`aborted`?new XK(n):Error(`${n} failed (${e.reason}, exit ${e.exitCode??`null`})${e.said===``?``:`: ${e.said}`}`)}async function v$(e,t,n,r){let i=await e.launch({...t,timeoutMs:g$});i.ok||_$({reason:i.reason,exitCode:i.exitCode,said:i.error??i.stderr.trim()},t.category,n,r)}async function y$(e,t,n,r,i,a){let o=h(E.join(a,`cc-candybar-handoff-`));try{let a={stdout:`/dev/null`,stderr:E.join(o,`stderr`),status:E.join(o,`status`)},s=e.launchJobSync(t,a);if(!s.ok){_$({reason:s.reason,exitCode:null,said:s.error},t.category,n,r);return}s.release();let c=e.clock.monotonic()+i;for(;;){let o=lt(s.pid),l=st(a.status);if(l!==null){if(l.kind===`exit`&&l.code===0)return;_$(l.kind===`exit`?{reason:`non-zero`,exitCode:l.code,said:_(a.stderr,`utf8`).trim()}:{reason:`timeout`,exitCode:null,said:``},t.category,n,r);return}if(!o)throw Error(`${n} failed (lost): the opener ended with no verdict`);if(e.clock.monotonic()>=c){r(`info`,`${t.category} handed off at ${i}ms, pid ${s.pid}`);return}await A(e.clock,50)}}finally{y(o,{recursive:!0,force:!0,maxRetries:3})}}function b$(e,t){return t.launch({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`)}const x$=(e,t)=>b$(h$(e),t),S$=new Set([`request`,`feed`]);function C$(e){if(!S$.has(e))throw new Z(`unknown renderer ${JSON.stringify(e)}`);return e}const w$=async(e,t)=>{let[n=``,r=``,i=``]=QK(()=>Qi(e)),a=m$(n),o=t.diagnosticCopy(a,C$(r),i);if(o===void 0)throw new Z(`that message is no longer listed in session ${a}'s diagnostics — open ⚠ again and copy from there`);await b$(o,t)},T$=(e,t)=>t.launch({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,h$(e)],category:`click.open`},`open -a "Visual Studio Code"`),E$=async(e,t)=>{let n=m$(h$(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},D$=async(e,t)=>{let[n=``,...r]=QK(()=>Qi(e)),i=m$(n),a=t.gates.state.gateFor(V$(t,i));if(r.length===0)throw new Z(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new Z(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new Z(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new Z(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}j$(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.log(`info`,`set-state: ${s} (session=${i})`)},O$=/^-?\d+$/;function k$(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const A$=async(e,t)=>{let[n=``,r=``,i=``]=QK(()=>Qi(e)),a=m$(n);if(!r)throw new Z(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!O$.test(i))throw new Z(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=V$(t,a),c=t.gates.state.gateFor(s),l=c.rangeParamsFor(r);if(!l)throw new Z(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&O$.test(u)?M$(l,parseInt(u,10)):N$(`step-state`,r,l,LK(s,e=>t.sessionState.get(a,e),r)),f=k$(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new Z(`step-state: ${p.reason}`);j$(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.log(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function j$(e,t,n,r){let i=r.filter(e=>e.key.startsWith(cN));if(i.length===0)return;let a=EK(V$(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new Z(`${n}: refused — ${a.join(`; `)}`)}function M$(e,t){return Math.max(e.min,Math.min(e.max,t))}function N$(e,t,n,r){if(r===null)return n.min;if(!O$.test(r))throw new Z(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return M$(n,parseInt(r,10))}function P$(e,t,n){let r=t.get(n,YK);return r===null?e:{...e,target:{source:`pick`,path:r}}}function F$(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function I$(e){let t;try{t=JSON.parse(e)}catch{throw new Z(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new Z(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i,source:a}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new Z(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,target:F$(a,i)}}function L$(e,t){let n=z$(e,t);if(n===null)throw new Z(`session ${t} has not rendered yet — no config to act on`);return n}function R$(e,t){let n=e.sessionState.get(t,qK);return n===null?null:I$(n)}function z$(e,t){let n=R$(e,t);return n===null?null:P$(n,e.sessionState,t)}function B$(e,t,n){let r=z$(e,t);if(r===null)return;let{path:i}=W$(e,r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function V$(e,t){return e.configFor(L$(e,t))}function H$(e,t){let n=R$(e,t);if(n===null)return null;let r=()=>e.lanes.of(P$(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function U$(e,t){let n=z$(e,t);return n===null?zK:UK(e.configFor(n))}function W$(e,t){return JH(e.locations,OU(e.stateDir).read(),t.projectDir,t.cwd,t.target.path)}function G$(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.log}}const K$=async(e,t)=>{let[n=``,r=``,i=``]=QK(()=>Qi(e)),a=m$(n),o=L$(t,a),s=t.configFor(o),c=t.gates.config.gateFor(s);if(!r)throw new Z(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new Z(`set-config: ${l.reason}`);let u=W$(t,o),d=wK(s,e=>t.sessionState.get(a,e),r);Vq(G$(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.log(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},q$=async(e,t)=>{let[n=``,r=``,i=``]=QK(()=>Qi(e)),a=m$(n);if(!r)throw new Z(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!O$.test(i))throw new Z(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=L$(t,a),c=t.configFor(s),l=t.gates.config.gateFor(c),u=l.rangeParamsFor(r);if(!u)throw new Z(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=W$(t,s),f=wK(c,e=>t.sessionState.get(a,e),r),p=Bq(d.path,f.key),m=typeof p==`number`?M$(u,p):N$(`step-config`,r,u,RK(f.globals,r)),h=k$(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new Z(`step-config: ${g.reason}`);Vq(G$(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.log(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},J$=async(e,t)=>{let[n=``]=QK(()=>Qi(e)),r=m$(n),i=L$(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=SK(a,o),c=TK(a,o);if(s.length+c.length===0){t.log(`info`,`save: nothing unsaved (session=${r})`);return}let l=t.gates.state.gateFor(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new Z(`save: ${t.reason}`);return[e.target,t.value]});X$(`save`,l,c);let d=W$(t,i);Hq(G$(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.log(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(Y$)].join(` `)} → ${d.path} (session=${r})`)},Y$=e=>`${e.preset}/${e.id}.settings.${e.setting}=${tb(e.value)}`;function X$(e,t,n){for(let r of n){let n=t.validate(r.key,tb(r.value));if(!n.ok)throw new Z(`${e}: ${n.reason}`)}}const Z$=async(e,t)=>{let[n=``]=QK(()=>Qi(e)),r=m$(n),i=L$(t,r),a=t.configFor(i),o=kK(a,e=>t.sessionState.get(r,e)),s=t.gates.state.gateFor(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new Z(`save-preset: ${t.reason}`);return[e.configKey,t.value]});X$(`save-preset`,s,o.placements);let l=W$(t,i),u=Yq(G$(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Px.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Mx.preset.sessionKey,u),t.log(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(Y$)].join(` `)} → ${l.path} (session=${r})`)},Q$=async(e,t)=>{let[n=``]=QK(()=>Qi(e)),r=m$(n),i=L$(t,r),a=jK(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new Z(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=W$(t,i);Xq(G$(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(SK(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=Tx.map(e=>Mx[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.log(`info`,`save-theme-default: ${a.theme} ${Tx.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},$$=async(e,t)=>{let[n=``,r=``]=QK(()=>Qi(e)),i=m$(n);if(!r)throw new Z(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=L$(t,i),o=W$(t,a);Zq(G$(t,i),o,r),t.reloadConfig(a);let s=Mx.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.log(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},e1=async(e,t)=>{let[n=``,...r]=QK(()=>Qi(e)),i=m$(n),a=L$(t,i),o=t.gates.config.gateFor(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new Z(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=W$(t,a),l=r.map(MK),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);Kq(G$(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.log(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function t1(e,t){let n=(e,t)=>[...Fy(_S(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(mS(t.presets).flatMap(e=>n(t,e).map(t=>lN(Hj(e),jy(t)))));return mS(e.presets).flatMap(t=>n(e,t).map(e=>({member:lN(Hj(t),jy(e)),node:e})).filter(({member:e})=>!r.has(e)))}function n1(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[aN]:[]])}const r1=async(e,t)=>{let[n=``,r=``,i=``]=QK(()=>Qi(e)),a=m$(n),o=L$(t,a),s=t.configFor(o),c=t.gates.config.gateFor(s);if(!r)throw new Z(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new Z(`apply-layout-op: ${l.reason}`);let u=UR(l.value);if(u===null)throw new Z(`apply-layout-op: "${l.value}" is not a layout op token`);let d=W$(t,o),f=Qq(G$(t,a),d,r,u);t.reloadConfig(o);let p=n1(t1(s,t.configFor(o)),t.sessionState.get(a,aN)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.log(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},i1=async(e,t)=>{let[n=``]=QK(()=>Qi(e)),r=m$(n);t.journal.commit();let i=t.history.undo(r);t.journal.wrote(),B$(t,r,i),t.log(`info`,`undo: restored ${CJ(i)} (session=${r})`)},a1=async(e,t)=>{let n=m$(h$(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,t.gates.state.gateFor(V$(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.log(`info`,`back: ${a} discarded=${i} (session=${n})`)},o1=async(e,t)=>{let n=m$(h$(e));t.journal.commit(),t.journal.wrote();let r=t.history.rewind(n);B$(t,n,r),t.log(`info`,`rewind: put back ${CJ(r)||`nothing`} as edit mode found it (session=${n})`)},s1=async(e,t)=>{let[n=``]=QK(()=>Qi(e)),r=m$(n);t.journal.commit();let i=t.history.redo(r);t.journal.wrote(),B$(t,r,i),t.log(`info`,`redo: re-applied ${CJ(i)} (session=${r})`)},c1=async(e,t)=>{m$(h$(e)),await t.applyUpdate()};function l1(e,t){let n=e.sessionState.get(t,JK);if(n===null)throw new Z(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new Z(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new Z(`client hints record is not an object: ${n}`);return yn(r)}function u1(e,t,n){let r=RF(n);e.sessionState.setBatch(t,tI(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${HF(n.config)} ${$F(n.nerdFont,n.marks)} ${UF(n.terminal,n.clicked)} ${WF(n.terminal,n.width)} ${GF(n.install)} ${qF(n.daemon)} ${JF(n.data)} ${QF(n.transcripts)} ${YF(n.frames,n.claudeSettings)} ${ZF(n.claudeSettings.origin.sources)} (session=${t})`)}async function d1(e,t,n,r){let i={kind:`clicked`,sessionId:t,via:e.arrival.via},a=e.clients.ofSession(t,e.now()),o;try{o=await xQ({...n,loadConfig:()=>r},l1(e,t),L$(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:a.map(e=>e.rateLimits)},{kind:`ok`,value:a.map(e=>e.transcript)},i,{kind:`ok`,value:WJ(i,a)},bQ(t,a),qZ(e.doctorStores))}catch(e){throw e instanceof BJ?new Z(e.message):e}let s={facts:o,install:GZ(n.install,e.bundle,a.map(e=>e.client)),current:async e=>{let i=n.loadConfig(L$(e,t));return i.config===r.config&&i.error===r.error&&i.warning===r.warning?s:d1(e,t,n,i)}};return s}const f1=(e,t)=>{let n=JZ(e.doctor);return d1(e,t,n,n.loadConfig(L$(e,t)))};async function p1(e,t,n){let{facts:r,install:i}=await e.gather(n.current),a=qZ(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:_Q(e.arrival),install:i,clicked:m1(e,o)}}function m1(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?rF(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>RJ(e,r))}catch(t){return e.log(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const h1={gathers:!0,prepare:async(e,t)=>{let n=m$(h$(e)),r=await f1(t,n);return async e=>u1(e,n,await p1(e,n,r))}},g1=async(e,t)=>{let n=HQ(h$(e));if(n===null)throw new Z(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new Z(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.log(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},_1={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``]=QK(()=>Qi(e)),i=m$(n),a=zF(r);if(a===void 0)throw new Z(`doctor-fix: unknown check "${r}"`);let o=await f1(t,i);return async e=>{let t=await p1(e,i,o),n=a.probe(t);if(n.ok||n.fix===void 0)throw new Z(`doctor-fix: ${a.label} — ${n.ok?`nothing to fix`:n.reason}`);let r=SQ(e.doctorStores,n.fix,t);if(r.kind===`failed`)throw new Z(`doctor-fix: ${a.label} — ${r.reason}`);e.log(`info`,`doctor-fix: ${a.name} → ${pte(n.fix)} (session=${i})`),u1(e,i,r.value)}}},v1={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``,i=``]=QK(()=>Qi(e)),a=m$(n),o=zF(r);if(o===void 0)throw new Z(`doctor-mark: unknown check "${r}"`);if(!sF.includes(i))throw new Z(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${sF.join(` or `)}`);let s=await f1(t,a);return async e=>{let t=await p1(e,a,s),n=o.probe(t);if(n.ok||n.sighting===void 0)throw new Z(`doctor-mark: ${o.label} — ${n.ok?`nothing to mark`:`shows nothing to look at`}`);let r=[o.name,n.sighting.id,i],c=e.doctorStores.marks.update(e=>FJ(e,...r));if(c.kind===`failed`)throw new Z(`doctor-mark: ${c.reason}`);e.log(`info`,`doctor-mark: ${o.name} ${i} on ${n.sighting.id} (session=${a})`),u1(e,a,{...t,marks:c})}}},y1=async(e,t)=>{let[n=``,r=``]=QK(()=>Qi(e)),i=m$(n),a=Object.values(t.configFor(L$(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new Z(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=await t.typing(l1(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.log(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new Z(`${r} was not typed: ${s.reason}`);t.log(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)};function b1([e=``,t=``,n=``,r=``],i){let a=m$(e),o=L$(i,a),s=i.configFor(o).actions,c=Object.hasOwn(s,t)?s[t]:void 0;if(c===void 0||!(`run`in c))throw new Z(`"${t}" is not a run action this session's config declares`);let l=AS(c);if(!i.links.verify({sessionId:a,action:t,declaration:l,evaluated:n},r))throw new Z(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let u;try{u=JSON.parse(n)}catch{throw new Z(`run ${t}: what the link carries is not JSON`)}let[d,...f]=u.run;if(d===void 0||d===``)throw new Z(`run ${t}: the program evaluated to nothing`);let p=i.sourcesFor(o);return{sessionId:a,action:t,argv:[d,...f],envOverlay:{...MJ({sessionId:a,projectDir:o.projectDir,claudeConfigDir:l1(i,a).claudeConfigDir}),...u.env},cwd:c.cwd??i.locations.home,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const x1=new Map([[wi,p$(x$)],[Di,p$(async(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new Z(`load-config: expected <sessionId>/<path> (missing separator)`);let r=m$(QK(()=>decodeURIComponent(e.slice(0,n)))),i=QK(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new Z(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new Z(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,YK),t.log(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,YK,i),t.log(`info`,`load-config: ${i} (session=${r})`))})],[Ti,p$(T$)],[Si,p$(D$)],[Ci,p$(A$)],[Oi,p$(K$)],[ki,p$(q$)],[Pi,p$(e1)],[Ai,p$(J$)],[ji,p$(Z$)],[Mi,p$(Q$)],[Ni,p$($$)],[Fi,p$(r1)],[Ii,p$(i1)],[Li,p$(s1)],[Ri,p$(a1)],[zi,p$(o1)],[Ei,p$(E$)],[Bi,p$(c1)],[Vi,h1],[Hi,_1],[Ui,v1],[Wi,p$(g1)],[Gi,p$(y1)],[`run`,p$(async(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=QK(()=>Qi(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=b1(i,t)}catch(e){throw e instanceof Z&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)})],[Ki,p$(async(e,t)=>{let[n=``,r=``,i=``,a=``]=QK(()=>Qi(e)),o=m$(n),s=i;if(!t.links.verify(AU(o,r,s),a))throw new Z(`the answer's signature does not match what it carries: it was not drawn by this daemon`);let c=kU(OU(t.stateDir),r,s);if(c.kind===`failed`)throw Error(`${r} was not ${s}: ${c.reason}`);t.journal.wrote();let{superseded:l,absent:u,unchecked:d}=c.value;t.log(`info`,`repo-config: ${r} ${s} superseded=${l.join(`,`)||`-`} absent=${u.join(`,`)||`-`} unchecked=${d.length===0?`-`:JSON.stringify(d)} (session=${o})`),t.reloadConfig(L$(t,o))})],[qi,p$(w$)]]),S1=new Set([Si,Ci,Oi,ki,Pi,Ai,ji,Mi,Ni,Fi,Ii,Li,Ri,zi,Ei,Bi,Vi,Hi,Ui,Gi,`run`,Ki,Di,qi]);function C1(e,t){return w1(e===`dispatch`?ta(t):[{verb:e,value:t}])}function w1(e){let t=e.find(e=>S1.has(e.verb)),n=t===void 0?``:QK(()=>$i(t.value));return n===``?null:f$(n)}const T1=(e,t,n)=>n.journalTurns.gathering(()=>e.prepare(t,n)).catch(e=>()=>Promise.reject(e));async function E1(e,t,n,r){await(r??await n.gather(n=>e.prepare(t,n)))(n)}async function D1(e,t){let[n]=ra(ta(e)),r=n===void 0?void 0:x1.get(n.verb);return r?.gathers?T1(r,n.value,t):void 0}async function O1(e,t,n){let r=[],i=!1,a=ta(e),o=w1(a);for(let[e,{verb:o,value:s}]of ra(a).entries()){let a=x1.get(o);if(!a){r.push(`unknown effect verb "${o}"`);continue}try{await E1(a,s,t,e===0?n:void 0)}catch(e){if(e instanceof XK)throw r.length>0&&t.log(`warn`,`dispatch: ${r.join(`; `)}`),e;e instanceof Z||(i=!0),r.push(`${o}: ${e instanceof Error?e.message:String(e)}`)}}if(r.length>0){o?.ok&&Ks(t.sessionState,o.id,r.join(`
|
|
479
|
+
`),t.now());let e=`dispatch: ${r.join(`; `)}`;throw i?Error(e):new Z(e)}}function k1(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}async function A1(e,t,n,r){let i=e===null?null:H$(t,e),a=t.history.begin(),o=t.navigation.begin(a.sessionState),s=n.holds(()=>{let e=[];for(let t of[o,a])try{t.commit()}catch(t){e.push(t)}k1(e)}),c=[],l=e=>KK(e,e=>U$(t,e),e=>t.log(`info`,e)),u={...t,sessionState:l(a.sessionState),journal:a,navigating:l(o.sessionState)},d={launch:(e,r)=>n.landed(v$(t.launcher,e,r,t.log)),typing:(e,r)=>n.landed(o$(t.claudeInput,e,r)),applyUpdate:()=>n.landed(t.applyUpdate())};try{await r({...u,...d,gather:e=>n.landed(e(u))})}catch(e){c.push(e)}let f=!0;try{f=s()}catch(e){c.push(e)}if(f&&i!==null)try{let e=i.read();t.lanes.clicked(i.sessionId,a.written()?i.before:e,e)}catch(e){c.push(e)}if(f&&e!==null)try{let n=z$(t,e);n!==null&&t.views.follow(e,n)}catch(e){c.push(e)}k1(c)}function j1(e,t,n){return async(r,i)=>{let a=C1(e,r),o=a?.ok?a.id:null;return i.journalTurns.click(e,o,{placed:i.placeWaited,waited:i.turnWaited,gone:i.clientGone,gathered:i.gatherTook},()=>t(r,i),(e,t)=>A1(o,i,t,async t=>{try{await n(r,t,e)}finally{o!==null&&i.clickLanded(o)}}))}}const M1=new Map([...[...x1].map(([e,t])=>[e,j1(e,async(e,n)=>t.gathers?T1(t,e,n):void 0,(e,n,r)=>E1(t,e,n,r))]),[xi,j1(xi,D1,O1)],[Wi,g1]]);Object.freeze([...M1.keys()]);function N1(e,t,n){return n.journalTurns.take(`menu-idle`,{waited:t=>n.log(`info`,`menu-idle: waited=${t}ms (session=${e})`),gone:()=>!1},r=>A1(e,n,r,async n=>{if(!t.stillIdle()){n.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}t.closed();let r=GK(U$(n,e),t=>n.navigating.get(e,t));n.navigating.setBatch(e,r.map(({key:e})=>({key:e,value:Yr}))),n.log(`info`,`menu-idle: closed=${r.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)}))}function P1({projectDir:e,cwd:t,target:n}){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path??null,source:n.source})}function F1(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const I1={kind:`hidden`},L1={kind:`shown`};function R1(e,t){try{return F1(e,t)?L1:I1}catch(e){let t=BC(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function z1(e,t){let n=K.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function B1(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function V1({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function H1({text:e,placement:t,lead:n,trail:r}){return{text:U1(e),placement:t,...n!==void 0&&{lead:U1(n)},...r!==void 0&&{trail:U1(r)}}}function U1(e){let t=e.blankCopy(e.plain);t.style=VN(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(VN(i).clearMetaAndLinks(),n,r);return t}function W1(e){let t=V1(e);if(t.length===1)return e.text;let n=z1(t);return n.style=e.text.style,n}function G1(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,placement:s,lead:c=[],trail:l=[]}=t;if(e.length===0)return[];let u=z1(e,a).pad(o),d=new K(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:z1([d,...c],a)},...l.length>0&&{trail:z1([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(B1(u,n,p),[{text:u,...f}])}function K1(e,t,n){let r=`x`.repeat(Math.min(n,t)).replace(/x$/,` `),i=r+e,a=[],o=0;return UP(i,t).forEach(e=>{let t=e.trimEnd(),n=i.indexOf(t,o);t!==``&&n>r.length&&a.push(n-r.length),o=n+t.length}),a}function q1(e,t){if(e.length===0)return 0;let{lines:n}=WP(e.map(({owner:e})=>e),t),r=z(kP(n[n.length-1]));return Math.max(0,r-LP(t)+RP(t))}function J1(e,t,n){if(e.cellLength<=t)return!0;let{lines:r}=WP([e],{...n,width:1/0});return z(kP(r.flat()))<=n.width}function Y1(e,t,n,r){if(J1(e.owner,t,r))return[e];let i=e.owner.copy().expandTabs(),a=q1(n,r);return i.divide(K1(i.plain,t,a)).map((n,i)=>({...e,owner:n.truncate(t,{marker:``}).padLeft(i>0?r.padding:0)})).filter(({owner:e},t,{length:n})=>n===1||e.plain.trim()!==``)}function X1(e,t){let n=Math.max(2,HP(t)-LP(t)-t.padding);return Z1(e,t).reduce((e,r)=>[...e,...Y1(r,n,e,t)],[])}function Z1(e,t){let n=()=>e.map(e=>({owner:W1(e),placement:e.placement})),r=[];if(e.forEach(({fill:e},t)=>{e!==void 0&&r.push({at:t,how:e})}),r.length===0||!Number.isFinite(t.width))return n();let i=WP(e.map(W1),t).lines;if(i.length>1)return n();let a=Math.max(0,t.width-z(kP(i.flat()))),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];B1(c,c.cellLength+a,n)}),n()}function Q1(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=$1(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:VN(a.style)};if(e.style.link){i();let r=$1([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function $1(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>e0(e.frag,n?n.add(e.style):e.style)),i=K.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function e0(e,t){let n=e.copy();return n.style=t,n}function t0(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function n0(e,t){let{look:n}=t0(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function r0(e,t){let{layout:n}=t0(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function i0(e,t){if(e.bound!==void 0)throw Error(`a render bound a compile another render holds`);return e.bound=t,{[Symbol.dispose]:()=>{e.bound=void 0}}}function a0(e,t,n,r){let i=new Map,a=Object.entries(t);for(let[t,o]of[...a.filter(([,e])=>!(`do`in e)),...a.filter(([,e])=>`do`in e)])i.set(t,o0(e,t,o,n,r,i));return i}function o0(e,t,n,r,i,a){if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=ES(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,labelOf:t.labelOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=Lx.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=ES(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,labelOf:t.labelOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=ES(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,labelOf:e.labelOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:l0(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:l0(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`slash`in n)return{kind:`slash`,line:n.slash};if(`run`in n)return{kind:`run`,name:t,declaration:AS(n),argv:n.run.map(n=>l0(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,l0(e,r,t)])};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:l0(e,n.name,t)};if(`themeDefault`in n)return{kind:`theme-default-save`};let[o,...s]=n.do.map(e=>{let n=a.get(e);if(n===void 0)throw Error(`action "${t}" fires "${e}", which is not declared in this config`);return n});return{kind:`do`,head:o,rest:s}}function s0(e){return e.kind===`do`?s0(e.head):e}function c0(e){switch(s0(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`slash`:case`run`:case`do`:return!1}}function l0(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function u0(e,t){return e.has(t)?IC(e.read(t)):``}function d0(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function f0(e,t,n,r){let i=new K(e,{style:U.combine([r,new U({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function p0(e,t,n=!1){let r=new U({link:t,bold:n?!0:void 0}),i=new K(e.plain,{style:U.combine([VN(e.style),r])});for(let t of e.spans)i.stylize(U.combine([VN(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function m0(e,t){return Math.max(e.members.indexOf(u0(t,e.stateVar)),0)}function h0(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=u0(r,e.stateVar);return{effects:[{verb:Si,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=u0(r,e.stateVar);return{effects:[{verb:Si,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=u0(r,e.stateVar);return{effects:[{verb:Si,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(m0(e,r)+1)%e.members.length];return{effects:[{verb:Si,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Ci,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:wi,args:[d0(e.text,ej(r))]}],active:!1};case`open`:return{effects:[{verb:Ti,args:[d0(e.target,ej(r))]}],active:!1};case`persist-literal`:{let t=u0(r,e.stateVar);return{effects:[{verb:Oi,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=u0(r,e.stateVar);return{effects:[{verb:Oi,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(m0(e,r)+1)%e.members.length];return{effects:[{verb:Oi,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:ki,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Pi,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:Ii,args:[i]}],active:!1};case`redo`:return{effects:[{verb:Li,args:[i]}],active:!1};case`back`:return{effects:[{verb:Ri,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:zi,args:[i]}],active:!1};case`save`:return{effects:[{verb:Ai,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:ji,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Mi,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Ni,args:[i,d0(e.name,ej(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:Vi,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Hi,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:Ui,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:Gi,args:[i,e.line]}],active:!1};case`run`:{let t=ej(r),n=JSON.stringify({run:e.argv.map(e=>d0(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,d0(n,t)]))}),o=a.sign({sessionId:i,action:e.name,declaration:e.declaration,evaluated:n});return{effects:[{verb:`run`,args:[i,e.name,n,o]}],active:!1}}case`layout-op`:return{effects:[{verb:Fi,args:[i,e.key,HR(e.op)]}],active:!1};case`do`:{let o=h0(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>h0(e,t,void 0,r,i,a).effects)],active:o.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Fi,args:[i,e.key,HR(r)]}],active:!1}}}}function g0(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:$r(`action "${e}"`,n,t.members.length,m0(t,r)),boundValue:void 0};if(n.length>2)throw Error(`action "${e}" takes a display and an optional bound value, got ${n.length} arguments (per-state displays are a cycle action's form)`);return{display:n[0],boundValue:n[1]?.plain}}function _0(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=t0(n,`action "${e}"`).store,{display:a,boundValue:o}=g0(e,s0(r),t,i),s=u0(i,`session.id`),{effects:c,active:l}=h0(r,a.plain,o,i,s,n.signer);return p0(a,ea(c),l)}function v0(e){return{action:{fn:(t,...n)=>_0(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function y0(e,t){return f0(`✕`,ea([{verb:Si,args:[u0(e,`session.id`),t,Yr]}]),!1)}function b0(e,t,n){return new U({bgcolor:H.fromRgba(t),color:H.fromRgba(bv(e,t,n))})}function x0({tint:e,text:t}){return new U({bgcolor:H.fromRgba(e),color:H.fromRgba(t)})}function S0(e,t,n){return new U({color:H.fromRgba(Mu(e.get(`warning`),t,yv,n))})}function C0(e,t,n){return U.combine([b0(e,t,n),S0(e,t,n)])}function w0(e,t,n){return x0(Mv(e.palette,e.disclosure,t,n))}function T0(e){let t=H.fromRgba(e.get(`background`)),n=K.fromFragments(S_.map(n=>new K(`▀`,{style:new U({color:H.fromRgba(e.get(n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const E0=(e,t)=>{let n=typeof e==`string`?new K(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},D0=e=>new U({bold:e});function O0(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>E0(a,U.combine([w0(e,{...n,distribution:t},i),D0(o)]));let o=b0(e.palette,a,i);return(e,t,i,a)=>k0(i,U.combine([o,D0(a)]),r(t,n))}const k0=(e,t,n)=>E0(K.fromFragments([E0(e,t),E0(` `,t),T0(n)]));function A0(e,t,n,r){return t===void 0?E0(r):k0(r,void 0,t(n,e))}function j0(e,t,n,r,i){let a=b0(e.palette,i,r);return(e,r,i,o)=>E0(K.fromFragments([E0(o?`[`:` `,a),T0(n(r,t)),E0(o?`]`:` `,a)]))}function M0(e,t,n){let r=t.map(t=>({label:t.label,indices:e.flatMap((e,n)=>e.group===t.id?[n]:[])})).filter(e=>e.indices.length>0);if(r.reduce((e,t)=>e+t.indices.length,0)!==e.length){let n=new Set(t.map(e=>e.id)),r=e.flatMap((e,t)=>n.has(e.group)?[]:[`#${t} (group "${e.group}")`]);throw Error(`library: ${r.join(`, `)} name a group the domain does not list (${[...n].join(`, `)})`)}return n?r.flatMap(e=>N0(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function N0(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function P0(e,t){return new K(e).truncate(t,{marker:`…`}).plain}function F0(e){return{current:null,drawnAt:e}}function I0(e,t,n,r,i,a,o){let s={segName:t,placementId:n,palette:r,disclosure:i,tint:a,text:o,bg:void 0,drops:[]};return e.current=s,s}function L0(e,t,n){return z0(e,()=>n(I0(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function R0(e,t){return z0(e,()=>(e.current=null,t()))}function z0(e,t){let n=e.current;try{return t()}finally{e.current=n}}function B0(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function V0(e){return new K(e).cellLength}function H0(e){let{width:t,chromeCols:n,padding:r}=t0(e,`a row fit`);return Math.max(1,t-n-2*r)}function U0(e){let{padding:t,seamCols:n}=t0(e,`a row fit`);return Math.max(1,H0(e)-(V0(`✕`)+2*t+n))}function W0(e,t,n){if(!Number.isFinite(t))return e.length>0?[e.map((e,t)=>t)]:[];let r=Math.max(1,t-n),i=[],a=[],o=0;for(let t=0;t<e.length;t++){let n=e[t];a.length===0?(a=[t],o=n):o+1+n<=r?(a.push(t),o+=1+n):(i.push(a),a=[t],o=n)}return a.length>0&&i.push(a),i}function G0(e,t,n){let r=V0(`←`)+1+V0(`→`)+1,i=W0(e,t,n);return(i.length>1?W0(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function K0(e){let t=[];for(let n of e)t.length>0&&t.push(new K(` `)),t.push(n);let n=K.fromFragments(t);return n.overflow=`ignore`,n.end=``,n}function q0(e,t,n,r,i){let a=e.compiled.get(t);if(!a||a.kind!==n)throw Error(`${i} references action "${t}" which must be ${r}, got ${a?`a ${a.kind} action`:`no such action`}`);return a}function J0(e,t,n){let r=e.compiled.get(t),i=r&&s0(r);if(!i||i.kind!==`set-option`&&i.kind!==`persist-option`&&i.kind!==`layout-op-option`)throw Error(`${n} references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${i?`a ${i.kind} action`:`no such action`}`);return i}function Y0(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=t0(a,`picker`).store,d=u0(u,`session.id`),f=`stateVar`in t?u0(u,t.stateVar):void 0,p=(e,n)=>{let r=t.options[e];return o({index:e,count:t.options.length},r,n,r===f)},m=i?r.kind===`led`?U0(a):H0(a):1/0,h=(r.kind===`led`?0:V0(`✕`)+1)+c.reduce((e,t)=>e+V0(t.glyph)+1,0),g=t.library&&{groups:t.library.groups,entries:t.options.map(t.library.entry)},_=t.labelOf??(e=>e),v=g===void 0?t.options.map((e,t)=>p(t,_(e))):[],y=g===void 0?G0(v.map(e=>e.cellLength),m,h):M0(g.entries,g.groups,i),b=parseInt(u0(u,n.stateVar),10),x=e=>Math.max(0,y.findIndex(t=>t.some(t=>t.indices.includes(e)))),S=x(f===void 0?-1:t.options.indexOf(f)),C=Number.isInteger(b)?b<0?S:Math.min(b,y.length-1):0,w=y[C]??[],ee=e=>ea([{verb:Si,args:[d,n.key,String(e)]}]),T=r.kind===`led`?[]:[{verb:Si,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],te=r.kind===`own`&&r.onPick?T:[],E=e=>ea([...h0(l,e,e,u,d,a.signer).effects,...te]),ne=(e,n)=>p0(e,E(t.options[n])),D=r.kind===`led`?[]:[f0(`✕`,ea(T),!1,s)];D.push(...c.map(({glyph:e,option:r})=>f0(e,ea([...h0(l,r,r,u,d,a.signer).effects,{verb:Si,args:[d,n.key,String(x(t.options.indexOf(r)))]}]),!1))),C>0&&D.push(f0(`←`,ee(C-1),!1));let re=C<y.length-1?[f0(`→`,ee(C+1),!1)]:[];if(g===void 0){let e=w.flatMap(e=>e.indices);return[K0([...D,...e.map(e=>ne(v[e],e)),...re])]}let ie=new U({bold:!0}),O=y.length>1?` ${C+1}/${y.length}`:``,ae=w.length===1?[new K(`${w[0].label}${O}`,{style:ie})]:[],oe=[K0([...D,...ae,...re])];for(let e of w){w.length>1&&oe.push(K0([new K(e.label,{style:ie})]));let n=Math.max(...e.indices.map(e=>V0(_(t.options[e]))));for(let r of e.indices){let e=_(t.options[r]),i=g.entries[r].description,a=i===void 0?void 0:cP(i),o=` `.repeat(n-V0(e)+2),s=a===void 0?e:`${e}${o}${a}`;oe.push(K0([ne(p(r,P0(s,m)),r)]))}}return oe}function X0(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{AA(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=q0(e,r,`set-int`,`an int action ({ set, int: true })`,`picker`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=J0(e,n,`picker`),u=B0(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let d=t.drawnAt(),f=t=>Y0(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,O0(u,iv(void 0),n0(e,`{{ picker }}`),l.paletteOf,d,t),S0(u.palette,t,d)),p=Av(u.palette,u.disclosure,d),[,...m]=l.library===void 0?[]:f(p.plane);return m.length===0?f(u.bg)[0]:(u.drops.push(...m),f(p.state)[0])},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function Z0(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function Q0(e,t,n,r,i){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let a=t0(i,`carousel`).store;if(!a.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let o=i.compiled.get(e),s=u0(a,`session.id`),{options:c}=t;if(c.length===0)return K0([]);let l=Z0(c,u0(a,t.stateVar)),u=e=>c[l(e)],d=e=>ea(h0(o,u(e),u(e),a,s,i.signer).effects);return K0([f0(`◀`,d(-1),!1),p0(A0(n0(i,`{{ carousel }}`),t.paletteOf,u(0),r),ea(h0(i.compiled.get(n),u(0),void 0,a,s,i.signer).effects)),f0(`▶`,d(1),!1)])}function $0(e){return{carousel:{fn:(t,n,r)=>{if(r.trim()===``)throw Error(`carousel "${t}": label is empty`);if(!e.compiled.has(n))throw Error(`carousel "${t}": open must name a declared action, got ${JSON.stringify(n)}`);if(c0(e.compiled.get(n)))throw Error(`carousel "${t}": open "${n}" writes a value the template binds, and the label binds none — name an action that writes a fixed value, a cycle, or a do of them`);return Q0(t,J0(e,t,`carousel`),n,r,e)},argTypes:[`string`,`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}function e2(e,t,n){let r=J0(e,t,n);if(!(`stateVar`in r))throw Error(`${n} references action "${t}", which inserts a segment and holds no current value — a ${n} needs a { set, from } or { persist, from } action`);if(r.paletteOf===void 0)throw Error(`${n} references action "${t}", whose options are not colour-valued — a swatch draws the palette an option puts in force, as the "themes", "placementThemes" and "styles" domains do`);return r}function t2(e,t,n){let r=Math.imul(e^e>>>16,73244475);return r=Math.imul(r^r>>>16,73244475),r^=r>>>16,(n+1+(r>>>0)%Math.max(t-1,1))%t}function n2(e,t,n,r){let i=e2(e,t,n),a=r??u0(t0(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,n0(e,`{{ ${n} }}`))}function r2(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(AA(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return T0(n2(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function i2(e,t,n){return{swatches:{fn:(r,i)=>{let a=e2(e,r,`swatches`),o=q0(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=B0(t,`{{ swatches }}`);if(s.bg===void 0)throw Error(`{{ swatches }} is not available while segments.${s.segName}'s own "bg:" is being evaluated — a swatch row is drawn on that background`);let c=t.drawnAt(),{options:l}=a,u=l.length,[d]=Y0(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,j0(s,n0(e,`{{ swatches }}`),a.paletteOf,c,s.bg),S0(s.palette,s.bg,c),u===0?[]:(()=>{let t=Z0(l,u0(t0(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[t2(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const a2=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function o2(e,t,n,r){let i=Av(e,n,r),a=(t,n)=>({text:t,colour:n,ink:bv(e,n,r)});return[[W_(e,t,r).map((n,i)=>{let a=vv(e,n);return{text:a2[i%a2.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,e.get(`warning`)),a(`error`,e.get(`error`))]]]}function s2(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new K(` ${e} `,{style:x0({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new K(e)),r.push(a)}return r}function c2(e,t,n,r,i){let a=o2(e,t,n,r).map(e=>s2(e,i)),o=K.fromFragments(a.flatMap((e,t)=>t===0?e:[new K(`
|
|
480
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}function l2(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(AA(`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}=n0(e,`{{ themePreview }}`);return c2(r===void 0?a:n2(e,r,`themePreview`),o,{...B0(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),U0(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const u2=e=>e.slice(e.lastIndexOf(`.`)+1),d2=(e,t)=>{let n=new K(u2(e));return n.truncate(t,{marker:`…`}),n.plain};function f2(e,t){let n=e.map(e=>e.map(({name:e})=>V0(u2(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 p2(e,t,n,r){let i=f2(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new K(` ${d2(s,i)} `,{style:x0(Hv(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=K.fromFragments(a.flatMap((e,t)=>t===0?e:[new K(`
|
|
481
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}const m2=`layoutPreview`;function h2(e,t){return{[m2]:{fn:()=>p2(r0(e,`{{ layoutPreview }}`),n0(e,`{{ layoutPreview }}`).decor,t.drawnAt(),U0(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function g2(e,t,n,r){let i=B0(r.activeSegment,`{{ menu }}`),a=r.action,o=Wj(i.placementId,e,n.key),s=qj(o),c=Uj(e),l=t0(a,`menu`).store,u=u0(l,o)===c,d=u0(l,`session.id`),f=u?Yr:c,p=f0($r(`{{ menu "${e}" }}`,t,2,+!!u),ea([{verb:Si,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=Av(i.palette,i.disclosure,t).plane,l=J0(a,e,`menu`);return Y0(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,Yr],[s,`0`]],onPick:n.closeOnPick},n.paged,a,O0(i,n.distribution,n0(a,`{{ menu }}`),l.paletteOf,t,c),S0(i.palette,c,t))})():[]),p}const _2=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function v2(e,t){let n=t[t.length-1],r=_2(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:Xj(r??{})}}function y2(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=v2(t,n);return g2(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function b2(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=x2(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 K(t?i:a,{style:l===void 0?void 0:new U({color:l})}))}let l=K.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function x2(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 S2(e){let t={fn:(()=>{let t=B0(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:(()=>B0(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=B0(e,`{{ roleTextOn }}`);return T2(r,t,xu(r,n)).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i={fn:((t,n)=>{let{palette:r}=B0(e,`{{ keptOn }}`),i=xu(r,t),a=xu(r,n),o=ll(Nu(i,V.TRUECOLOR),Nu(a,V.TRUECOLOR)),s=Math.min(yv,Math.max(o,3));return(yee(i,e.drawnAt(),(e,t)=>ll(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},a=dA(()=>B0(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),o={fn:((e,t,n,r,i,o,...s)=>{let c=o===void 0?void 0:[o,...E2(s)];return b2({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 C2={"#000000":[`darken-1`,`darken-2`,`darken-3`],"#ffffff":[`lighten-1`,`lighten-2`,`lighten-3`]},w2=Object.values(C2).flat();function T2(e,t,n){let r=Nu(n,V.TRUECOLOR),i=t=>{let n=xu(e,t);return{colour:n,ratio:ll(Nu(n,V.TRUECOLOR),r)}},a=ju(r).hex,o=C2[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,...w2.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 E2(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 D2(e,t){if(e.kind!==`shell`&&e.kind!==`file`)return[];let n=`key`in e.cache&&[...t.calls(e.cache.key)].some(e=>QA.has(e));return[...t.ofVariable(e).flatMap(({reaches:e})=>e.length===0?[null]:e),...n?[null]:[]]}const O2={input:`view`,state:`view`,template:`view`,time:`view`,literal:`directory`,env:`directory`,dropped:`directory`,source:`view`},k2=new WeakMap;function A2(e){let t=k2.get(e);return t===void 0&&(t=j2(e),k2.set(e,t)),t}function j2(e){let t=new Map(gC(e)),n=jW(e),r=new Map([...t].map(([e,t])=>[e,t.kind===`shell`||t.kind===`file`?`directory`:O2[t.kind]])),i=new Map([...t].map(([e,t])=>[e,D2(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 M2(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
482
482
|
`)){n.push(r);continue}let e=r.split(`
|
|
483
|
-
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function P2(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 F2=e=>e.kind===`failed`?L1:e;function I2(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function L2(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 R2(e){return{...e,cells:e.cells.map(U1)}}function z2(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,...B2(e,r)]}function B2(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 V2(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:z2(e.direction,e.children.map((t,i)=>n(t,[...r,H2(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function H2(e,t){return e.steps[t]}function U2(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=W2(e);return{width:G2(t),reach:K2(t)}}function W2(e){let t=e.children.map(U2),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 G2=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),K2=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function q2(e,t){let n=W2(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=Ay[e.direction],i=iv(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),K2(n),G2(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const J2={compile(e,t){let n=q2(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,Iy(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),z2(e.direction,e.children.map((n,r)=>t.renderChild(n,F2(t.gate),H2(e,r))))}},Y2={drop:e=>e.place,above:()=>`above`},X2={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},Z2={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:jy(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(ni(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Ly(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,Q2(e,t))};function Q2(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=nj(t.scope,e.settings);if(t.gate.kind===`failed`)return i4(e,r,t,t.gate.message);try{let i=t.placement(e),a=I2(t.gate,i.gate());if(a.kind===`failed`)return i4(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 i4(e,r,t,s.message);let c=Ux(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:yN(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`?$2(f.variable):e4(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?t4(p.segment,u):n4(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:L1,h.disclosure).map(e=>({...e,place:Y2[v.placement](e)})),b=(e,t,n)=>K1($1([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?X2[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},w=S.flatMap(e=>b(new K(` `.repeat(r4(H1(e)))),h.trigger,0)),ee=(e,t)=>e.band===`own`?t===x?S:w:[],T=y.map((e,t)=>({cells:[...ee(e,t),...e.cells],band:`deeper`,place:e.place})),te=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...te.flatMap(e=>e.cells),...y.flatMap(ee)].flatMap(H1)),[...te,...T]}catch(n){return i4(e,r,t,n.message??String(n))}}const $2=e=>({kind:`waiting`,variable:e});function e4(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=BC(e);if(t===void 0)throw e;return $2(t.variable)}}function t4(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:N2($1(r,c)).map((e,t)=>({cells:K1(e,{...l,lead:t===0?$1(i,c):[],trail:t===0?$1(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:K1($1([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function n4(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=$1(a4(e.lead,e,t,n),l),d=$1(a4(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 K1($1([new K(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function r4(e){return e.reduce((e,t)=>e+t.cellLength,0)}function i4(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:K1([new K(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:yN(n.palette)},lead:a4(e.lead,e,t,n),trail:a4(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function a4(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=BC(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const o4={container:J2,segment:Z2};function s4(e){return o4[e]}var c4=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?l4:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const l4={kind:`hidden`},u4={palette:`theme`,style:`style`,effect:`effect`},d4=Lx.get(`colorCompatibility`),f4={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function p4(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function m4(e){if(e.ok)return e.value;throw e.error}const h4=e=>({read:()=>e}),g4=b_({basePalette:y_,palette:y_,decor:Fv});var _4=class{evaluated=0;memory=new c4;scope;binding;facts;look=Y.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&g4(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=ej(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(d4);return typeof e==`string`&&yy(e)?e:`truecolor`});let i=(0,Y.observable)(f4,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 V2(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=jR(e);return i===void 0?[]:[{name:i,address:n,palette:Ux(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>by(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=zj(e);return t===void 0?Lj(e)===void 0?Ej(this.view.get().payload(),e):Ej(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()[u4[e]];if(t.kind===`decided`)return b4(t.name,null,null);let r=S4(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=C4(this.source,e,i.name,r.where,e=>{t=e}),b4(n,t,null)}case`pending`:return b4(n??oy[e],null,i.variable);case`failed`:return n=oy[e],b4(n,sy(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!x4(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)??oy[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 z1(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>z0(this.source.activeSegment,()=>z1(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new w4(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:a0(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=BC(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:p4(e)}),m4(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:jR(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function v4(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new _4(t,n,e,r);return e.views.set(t,a),a}function y4(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 b4=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),x4=(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 S4(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 C4(e,t,n,r,i){switch(t){case`palette`:return Jx(n,r,i).name;case`style`:return ry(n,e.styles).name;case`effect`:return py(n).name}}var w4=class{where=T4(b_({palette:y_,region:Nv}));ground=T4(b_({colours:D4,bodyOpen:y_}));opened=T4(b_({colours:D4,open:y_}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=nj(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?h4(R1):e.derive(`${t.id} when`,e.readsInstant(a),()=>z0(r,()=>z1(a,i))),this.open=d===void 0?h4(L1):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>z0(r,()=>z1(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return A4(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 j4(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?h4(N4):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return M4(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}),F4(n,r,this.affixes.read())}};function T4(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 E4=(e,t)=>e.hex===t.hex,D4=b_({palette:y_,drawnAt:y_,tint:E4,text:E4,bg:E4,disclosure:Iv});function O4(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const k4=e=>Av(e.palette,e.disclosure,e.drawnAt);function A4(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Hv(n,r,i)};return R0(e,O4(t,c),e=>{let t=xN(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function j4(e,t,n,r,i,a){return R0(e,O4(t,n),e=>(e.bg=i?k4(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function M4(e,t,n,r,i,a,o){return R0(e,O4(t,n),e=>(e.bg=r?k4(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const N4={lead:[],trail:[],drops:[]};function P4(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return x0(t,k4(e).state,n)},get band(){return x0(t,k4(e).plane,n)},get close(){return w0(t,k4(e).state,n)},disclosure:r}}function F4(e,t,n){return{styles:P4(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function I4(e,t,n,r,i,a,o){let s=A4(e,t,n,r,i,void 0,void 0,o);return F4(s,j4(e,t,s,a,!1,o),N4)}function L4(e,t,n,r,i){return P4(A4(e,t,n,r,i,void 0,void 0,{}))}function R4(e,t){return{payload:()=>e,selections:()=>t}}function z4(e){if(`ttl`in e)return{kind:`ttl`,durationMs:hj(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 B4(e,t){switch(By(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 V4(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:z4(n.cache),parse:B4(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:z4(n.cache),parse:B4(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 H4(e,t,n,r=Ow.EMPTY){let i=r;for(let[r,a]of Object.entries(t))try{i=e.parse(`{{ define "${r}" }}${a}{{ end }}`,i).defines()}catch(e){throw Error(`Template parse error in ${n}.${r}: ${e.message}`,{cause:e})}return i}function U4(e,t,n){let{compiled:r,loadWarnings:i}=G4(e,t,n.cwd,W4(n.signer),Y4);return{...r,loadWarnings:i}}const W4=e=>(t,n)=>X4(n,e);function G4(e,t,n,r,i=Y4){let a=K4(e),o=q4(a);return{compiled:r(o,a),compileKey:o,loadWarnings:J4(e,t,n,i)}}function K4(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of Rx)n in t&&r.set(e,n);for(let[t,n]of qy(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...IW(e)].sort(([e],[t])=>e<t?-1:1)}}function q4(e){return oe(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function J4(e,t,n,r){let i=j2(e),a=IW(e),o=[];for(let[s,c]of gC(e))if(r.has(i.get(s)))try{V4(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const Y4=new Set([`directory`,`view`]);function X4({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>n0(i,`drawnAt`).registry.drawnAt(),o=I0(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=mS(e.presets),u=bR(e),d=[e=>a2(i,o,e.now)],f=$A({extraFuncs:{...y0(i),...i2(i),...Z0(i,o),...e2(i),...u2(i,o),...g2(i,o),...b2(s),...C2(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=H4(f,e.helpers,`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=o0(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=n.partials===void 0?p:H4(f,n.partials,`segments.${t}.partials`,p),r=t=>{let n=f.parse(t,e);return m.set(n,t),n},i=(e,i,a=n.partials===void 0?_:r)=>{try{return a(e)}catch(e){throw Error(`Template parse error in segments.${t}.${i}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:i(n.when,`when`),template:i(n.template,`template`,r),bg:n.bg===void 0?void 0:i(n.bg,`bg`,r),fg:n.fg===void 0?void 0:i(n.fg,`fg`,r)}}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=Zy(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Tee(t,e,a,t=>String(n0(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 s4(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=_S(e,t);C.set(t,S(n,r,void 0))}let w=new Map(Qv.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of RW(e)){let e=t.join(`.`),i=w.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:$4(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let ee=new Set(n.map(([e])=>e)),T={reads:kW({names:ee,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:XA(d)},te=VW(T),E=[...C.values()].flatMap(Q4(y)).some(e=>te(m.get(e))),ne=E?new Set([...T.clock,h2]):T.clock,D=VW({...T,clock:ne}),re=new Set([...m].flatMap(([e,t])=>D(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=VW({reads:kW({names:ee,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:T.projections,clock:ne});for(let e of uH){let n=y[t][e];n!==void 0&&r(m.get(n))&&re.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:w,instant:re,layoutReadsInstant:E,styles:e.styles,runtime:i,views:new WeakMap}}function Z4(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 Q4=e=>t=>{let n=[];return V2(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 $4(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 e3=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function t3(e,t,n,r,i){let a=n3(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function n3(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??oy[e];case`failed`:return r({kind:`rule`,slot:e,message:sy(t.where,e,`the rule failed — ${n.error}`)}),oy[e]}}function r3(e){return i3(e).filter(e=>!e.name.startsWith(fi)).map(e=>e.id)}function i3(e){return e.kind===`container`?e.children.flatMap(i3):[e,...e.opens===void 0?[]:i3(e.opens.body)]}function a3(e,t,n,r,i,a){let o={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return v4(e,t,n,R4(o,a)),o}function o3(e,t,n,r,i,a,o,s,c){try{var l=io();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new $N(``),h=m.clockAt(a,ly[c.animationSpeed]),g=l.u(BA(a,h.timeline)),_=y4(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:LP(v),padding:v.padding,seamCols:RP(v),preset:c.preset},i);let y=_.evaluated;l.u(a0(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:H_[c.variation],shade:N_[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},w=_.memory.begin(C,L2),ee=_.memory.from(C),T=new Set,te={held:e=>ee?.rules.get(e),waited:e=>T.add(e),settled:w.rule},E=new Map,ne=e=>{let n=_.slot(e);if(E.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&&T.add(n.waited),n.name;let r=C4(t,e,t3(e,n.rule,_,p,te),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:D,style:re,effect:ie}=_.selections(),O=D.kind===`decided`?D:Jx(ne(`palette`),``,e3),ae=re.kind===`decided`?re:ry(ne(`style`),e.styles),oe=ie.kind===`decided`?ie:py(ne(`effect`)),se=O.value,ce=Gx(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:bv(ce,le,r.drawnAt())},de=m.motion(oe.value,h,{transitions:x,source:C,last:ee,returned:L2,hold:R2},ue);u?.clear();let fe=t=>e.segments[t],pe=(e,i,a)=>{let o=i.kind===`hidden`?i:I2(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${r3(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)=>I4(t.activeSegment,e,i,a,r.drawnAt(),o,n),lookupSegment:fe,renderChild:(e,t,n)=>pe(e,t,Bv(a,n)),renderBody:(e,t,n)=>pe(e,t,Vv(n)),closeDisclosure:e=>b0(n,e),placed:(e,t)=>w.placed(e,de.placed(e,t)),lastDrawn:e=>ee?.placements.get(e),waited:e=>T.add(e),decorations:(e,n)=>L4(t.activeSegment,e,n,a,r.drawnAt())};return s4(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 "${pS}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let he=P2(pe(me,R1,zv(S))).map(({line:e,row:t})=>{let n=Z1(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...WP(n.map(e=>e.owner),v,de.row(t,r,n))}});de.drawn(),w.commit();let ge=()=>he.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||i3(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:[...T].sort()},evaluated:_.evaluated-y,cellBreaks:he.reduce((e,t)=>e+t.cellBreaks,0),rules:E}}catch(e){l.e=e}finally{l.d()}}const s3={moving:1e3/30,still:1e3},c3=[`data`,`state`,`reload`,`visibility`];function l3(e){return Vb.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 u3(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const d3=(e,t)=>Bb[t].handsOff?e.resp:e.statusline,f3=e=>Math.round(1e3/e);var p3=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 Jb;let r=t-1,i=this.shown(n);return qb(e=>{let a=n.rates.get(e);if(a===void 0)return Gb;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.clock.monotonic(),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`&&e.phase.clear(),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.clock.monotonic(),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: ${C(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,f3(this.spacingOf(e)),r);if(i===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=n;let a=this.deps.clock.monotonic();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.clock.monotonic(),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){let r=Math.max(0,(t-n)*1e3);this.setTimer(e,t,this.deps.clock.monotonic()+r,r)}setTimer(e,t,n,r){e.phase.kind===`due`&&e.phase.clear(),e.phase={kind:`due`,at:n,clear:this.deps.clock.after(r,()=>this.fire(e,t,n))}}fire(e,t,n){let r=n-this.deps.clock.monotonic();r>0?this.setTimer(e,t,n,r):this.draw(e,t)}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||d3(a,t)!==d3(i,t))&&u3(r,n);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let n=d3(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:mM(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.clock.monotonic(),r=this.deps.refreshes(),i=(n-e.since)/1e3,a=i===0?`-`:`${(e.drawn/i).toFixed(1)}fps`,o=uj.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=${f3(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${c3.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 m3(e,t){return Vb.filter(n=>e[n]&&Bb[n].handsOff&&t.has(n))}function h3(e,t){return{severity:iU,lines:[[aU(`[⟲ claude]`,ea([{verb:Pi,args:[e,...t.map(e=>Bb[e].switch.setting)]}]))]]}}function g3(e,t){for(let n of Object.entries(t))e.push(n)}const _3={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function v3(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,C(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function y3(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...v3(n)];return{level:_3[n.kind],line:`${e}${i.map(([e,t])=>` ${e}=${R(t)}`).join(``)}`}}const b3=()=>{},x3=e=>({ok:!1,error:e instanceof Error?e.message:C(e),code:`RENDER_FAILED`,daemonV:3}),S3={ansi:e=>({ok:!0,output:EP(e)}),frame:e=>({ok:!0,frame:e})};function C3(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.now(),s=[];try{try{var c=io();let i=c.u(k3(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=j3(e,i,{by:`feed`,fps:n}),p=S3.ansi(o.body),m=R3(t,o,m3(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:S3.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}=y3(`render`,s,{kind:`threw`,error:e},i.now()-o),r=x3(e);return{bar:gP(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:b3,failure:{level:t,line:`frame ${n}`}}}}function w3(e,t,n){let{sessionState:r}=e;return fK(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function T3(e,t){try{var n=io();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:lK(i.view.source.effective(),pc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function E3(e,t,n){try{var r=io();let{renderCache:i,frameFeeds:a}=e,o=r.u(i.hold(t.projectDir,t.cwd,t.target.path)),s=a.latest(n);return lK(w3(e,n,o.state),s===null||pc(s.hints.tmux))}catch(e){r.e=e}finally{r.d()}}function D3(e,t,n){g3(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=bn(e,r),a=xn(i);return g3(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 O3(e,t,n,r){let{sessionState:i,renderCache:a}=e,o=t.hookData.workspace?.current_dir??t.cwd,s={...t,hookData:{...t.hookData,...o!==void 0&&E.isAbsolute(o)&&{location:dc(o)}}},c=s.sessionId,l=D3(s,n,r);g3(r,{encoding:s.encoding});let u=F$(s.requested,i,c);return A3(e,a.holdSession(u.projectDir,u.cwd,u.target.path,s),s,l,n,r)}function k3(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=D3(o,n,r)}catch(e){throw a[Symbol.dispose](),e}return A3(e,a,o,s,n,r)}function A3(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 j3(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=lK(S,pc(b.facts().hints.tmux));g3(g,{lanes:Vb.filter(e=>C[e]).join(`,`)||`-`});let{hints:w}=b.facts(),ee=sX(w);g3(g,{width:String(ee)});let T=b.source.payload(),te=Ys(r,_,h,n.by),E=te.kind===`held`||te.kind===`owed`?te.error:null,ne=o.notice({sessionId:_,dismissed:r.get(_,xz),enabled:S.updateNotice}),D=MU(v.repos,_,s),re=(e,t)=>({about:e,text:t,copy:t}),ie=e=>re(e??``,e),O=[ie(Cn(m.refusedArgs)),ie(x),re(`load`,v.lastError),re(`update-act`,o.error()),...y.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),ie(E?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),ae=v.watch===null?null:TC(`config watch`,v.watch,null),oe=[...Oc(c.delivery()),...p.lifelineWarnings(),...ae===null?[]:[{kind:`config-watch`,message:ae}],...v.lastWarning===null?[]:[{kind:`load`,message:v.lastWarning}]],se={config:y.config},ce=oU(_,n.by,O,[...ne,...D],[...oe,...l.ofSession(_,n.by,se)].map(e=>({about:`${e.kind}\0${e.message}`,text:e.message,copy:e.message}))),le={diagnostics:gU(ce),drawing:n,feeds:i.feedsOf(_,h),today:CX(u,b.lanes().today,b.facts().hookData,h)},ue=ro(T.metrics)?void 0:T.metrics;g3(g,vX(b.lanes().sources)),g3(g,{prompts:String(ue?.messageCount??`-`),nonPrompts:String(ue?.nonPrompts??`-`),pr:GY(T.git,rX(t.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:l3(le.feeds)});let de=[],fe=HY(S,ee),pe=d.of(_),me=f.since(_,h),{frame:he,evaluated:ge,cellBreaks:_e,rules:ve}=o3(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=cU(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);g3(g,{menuIdle:Se===void 0?`-`:`${(h-Se).toFixed(1)}s/${S.menuTimeout}s`});let Ce=l.drawn(_,n.by,se,de),we={width:ee,rows:vU(w.termRows,n.by===`feed`?Vb.flatMap(e=>{let t=Bb[e].rows;return C[e]&&t!==null?[t]:[]}):[]),colorCompatibility:he.depth},Te=_U(r.get(_,yi),ce),Ee=Te===null?he:mP(he,yU(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 g3(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:te.kind===`none`?`-`:te.kind,upd:String(ne.length),ask:String(D.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:E,delivered:xe,lanes:C}}function M3(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,YK,o);let s=F1(t.requested);n.get(r,`render-origin`)!==s&&n.set(r,JK,s)}async function N3(e,t,n,r,i){return M3(e,t),L3(e,t,n,r,i)}function P3(e,t,n){let{laneSetups:r,tmuxStatusLines:i}=e;r.noted(F3(e,t),n),i.observe(t.hookData.session_id,t.hints.tmux,n.tmuxStatus)}function F3(e,t){let{sessionState:n}=e,r=t.hookData.session_id;return{sessionId:r,hints:t.hints,origin:F$(t.requested,n,r),transcript:t.hookData.transcript_path,answered:qP(t.hookData)}}function I3(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);a.clicked(t,s===null?null:F3(e,s),n,r),s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus)}async function L3(e,t,n,r,i){try{var a=io();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(O3(e,t,n,i));P3(e,t,lK(l.view.source.effective(),pc(t.hints.tmux)));let u=o.monotonic(),d=r-u;g3(i,{deadline:`${t.deadline.kind}:${Math.round(d)}ms`});let f=new Map,p=await RY(e=>Promise.all([wX(l.payloadInputs,n,f),l.view.registry.inFlight(e)]),d,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${C(e)}`),o.after),m=o.monotonic();g3(i,{waited:`${Math.round(m-u)}ms`,ended:p,refreshed:lX(f)});let{drawn:h,clickShown:g,delivered:_,lanes:v}=j3(e,l,Ub),y=t.sessionId,b=m3(v,s.following(y)),x=YP(t.hints.client??null)===`statusline`,S=S3[t.encoding](x?R3(y,h,b):h.body);return g3(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 R3(e,t,n){let[r,...i]=n;return r===void 0||t.viewerOpen?t.body:mP(t.body,bU(h3(e,[r,...i]),t.diagnostics,e,t.geometry))}const z3=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`]),B3=[[`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`]],V3=[[`workspace.added_dirs`,`string-list`]];function H3(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of B3){let i=G3(n,e);if(i==null)t.missingRequired.push(e);else{let n=U3(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of V3){let i=G3(n,e),a=i===void 0?r:W3(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))z3.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function U3(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function W3(e){return Array.isArray(e)&&e.every(e=>U3(e)===`string`)?`string-list`:U3(e)}function G3(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 K3(e,t,n){let{tokens:r}=w({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),i=(r??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),a=(r??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===i&&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:PN(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function q3(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=_n.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${_n.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function J3(e,t,n,r){let{report:i}=H3(e.hookData),a=[];for(let e of i.missingRequired)a.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of i.typeMismatches)a.push(`field '${e}' expected ${t}, got ${n}`);let o=p$(e.hookData?.session_id);o.ok||a.push(`field 'session_id' ${o.problem}`),(typeof e.cwd!=`string`||!re(e.cwd))&&a.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&a.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let s=q3(e.encoding);s.ok||a.push(s.problem);let c=Gn(e.deadline);if(c.kind===`refused`)return{ok:!1,problems:[...a,c.problem]};if(a.length>0||!o.ok||!s.ok)return{ok:!1,problems:a};for(let e of i.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let l=yn(e),{configFile:u,refusedArgs:d}=K3(e.args,e.cwd,r);return{ok:!0,req:{...e,deadline:c,encoding:s.encoding,sessionId:o.id,hints:l,rateLimits:Zee(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:LN(u,l.configEnv)},refusedArgs:d}}}function Y3(e,t){switch(e){case`vars`:return{what:e,vars:X3(t)};case`segments`:return{what:e,segments:t6(t)};case`config`:return{what:e,config:a6(t)}}}function X3(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=$3(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=Z3(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:Q3(r.lastUpdatedMs(),t.clock)})}return o}function Z3(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 Q3(e,t){return e===null?null:Math.max(0,t.now()-e)}function $3(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,e6(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}`,e6(i));return t}function e6(e){return e.kind}function t6(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=r6(n),o=n6(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:i6(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function n6(e){let t=new Map;for(let n of mS(e.presets))for(let r of Fy(_S(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=jy(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function r6(e){let t=[],n=new Set;for(let r of Fy(rS(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 i6(e,t,n){let r=new Set([...tC(e,t).keys()].flatMap(e=>_C(e,n)));return Array.from(r).sort()}function a6(e){return e===null?null:e.config}const o6=[`vars`,`segments`,`config`];function s6(e){return typeof e==`string`&&o6.includes(e)}const c6=e=>({resp:e,exitAfterFlush:null,delivered:b3}),l6=e=>({kind:`reply`,...e}),u6={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},d6=(e,t)=>l6(c6({ok:!1,error:t,code:e,daemonV:3}));function f6(e){let t=p$(e.sessionId);if(!t.ok)return d6(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return d6(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Vb.join(`, `)}): it predates the lane toggles — update it`);let n=Yb(e.lane);return n===null?d6(`BAD_REQUEST`,`subscribe needs a lane, one of ${Vb.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function p6(e,t,n,r,i){return!t||typeof t!=`object`||typeof t.v!=`number`?d6(`BAD_REQUEST`,`malformed request`):t.v===3?t.kind===`subscribe`?f6(t):typeof t.kind!=`string`||!Object.hasOwn(u6,t.kind)?d6(`BAD_REQUEST`,`unknown kind`):l6(await m6(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:b3})}async function m6(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:w,doctorStores:ee}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:b3};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return c6(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 c6({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:h6(e),fileEvents:d.stats(),runs:f.stats(),transcriptReads:po(),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(LA(new Date(o.now()))),bundle:S,sourceDigest:w,daemon:y.serving(),doctorStores:JZ(ee)})});if(t.kind===`render`){let c=new Date(o.now()),l=LA(c),u=o.monotonic(),d=Math.round(u-r),f=[],p=++a.requestsTotal,m=J3(t,a,e.log,e.home),h=(t,n)=>x.see(t.sessionId,{client:t.hints.client??null,termCols:t.hints.termCols??null,rateLimits:t.rateLimits,claudeConfigDir:wo(t.hints.claudeConfigDir,e.home),projectDir:t.requested.projectDir,transcript:Qee(t.hookData),frame:n},l,p);m.ok&&(h(m.req,`drawing`),s.note(m.req.sessionId,m.req,p));let _=m.ok?await N3(e,m.req,l,u+Kn(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&&qs(g,m.req.sessionId,n)}}),e=>(h(m.req,`failed`),{outcome:{kind:`threw`,error:e},resp:x3(e),delivered:b3})):w6(m.problems);_.outcome.kind!==`ok`&&a.requestsErrored++,g3(f,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:v,line:y}=y3(`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 y6(e,t,s,()=>n()||i());g3(s,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`});let{level:l,line:u}=y3(`click`,s,c,Math.round(o.monotonic()-a));return e.log(l,u),c6(S6(c))}if(t.kind===`debug`){if(!s6(t.what))return c6({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${o6.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`?v6(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??Ox(`colorCompatibility`)):_6};return c6({ok:!0,debug:Y3(t.what,n)})}throw Error(`no reply for request ${C(t)}`)}function h6(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 g6={endcaps:Ox(`endcaps`),colorCompatibility:Ox(`colorCompatibility`),wrap:Ox(`autoWrap`),padding:Ox(`padding`),width:1/0},_6=new Map;function v6(e,t){let n=new Map;for(let[r,i]of e)n.set(r,GP(i,{...g6,colorCompatibility:t}));return n}async function y6(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 x6(e,i,a,{via:`link`,handler:kn(t.clientVersion)},n,r)}catch(e){return e instanceof Z?{kind:`bad-request`,problems:[e.message]}:e instanceof ZK?{kind:`closing`,error:e}:e instanceof QK?{kind:`abandoned`,error:e}:{kind:`threw`,error:e}}}const b6={link:`verb`,"tmux-status":`linkVerb`};async function x6(e,t,n,r,i,a){let{menuIdle:o,verbCtx:s}=e;if(t===`tmux-status-click`)return g3(i,{verb:t}),C6(e,n,i,a);let c=N1.get(t);if(!c)return{kind:`bad-request`,problems:[`unknown click verb: ${t}`]};g3(i,{[b6[r.via]]:t});let l=w1(t,n),u=l?.ok?l.id:null;l===null?g3(i,{sid:`-`}):u!==null&&(g3(i,{sid:u}),o.clickArrived(u));try{await c(n,{...s,arrival:r,placeWaited:e=>g3(i,{placeWait:`${e}ms`}),gatherTook:e=>g3(i,{gather:`${e}ms`}),turnWaited:e=>g3(i,{turnWait:`${e}ms`}),clientGone:a})}finally{u!==null&&o.clickSettled(u)}return{kind:`ok`}}function S6(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 x3(e.error)}}async function C6(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(g3(r,{link:s.url}),s.url.startsWith(`cc-candybar://`)){let t=$K(()=>ss(s.url));return t.verb===`tmux-status-click`?o(`a status-line link names another status-line click`):x6(e,t.verb,t.value,{via:`tmux-status`},r,i)}return await b$(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,_$,e.tmp),{kind:`ok`}}const w6=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:b3});function T6(e,t){let n=oe(`sha256`).update(t).digest(`hex`).slice(0,16);return E.join(e,`update-act`,n)}const E6={kind:`idle`};function D6(e){if(e===null)return E6;let{act:t,record:n,alive:r,end:i,lastLine:a}=e;if(r)return{kind:`running`,act:t};if(i===null)return{kind:`failed`,act:t,identity:n.identity,reason:`lost: the act ended without a verdict`};if(i.kind===`exit`&&i.code===0)return{kind:`succeeded`,act:t};let o=i.kind===`timeout`?`timeout`:`non-zero (exit ${i.code}): ${a??`no output`}`;return{kind:`failed`,act:t,identity:n.identity,reason:o}}const O6=e=>({stdout:E.join(e,`stdout`),stderr:E.join(e,`stderr`),status:E.join(e,`status`)}),k6=e=>E.join(e,`record.json`);function A6(e){let t;try{t=l.readdirSync(e)}catch(e){if(e.code===`ENOENT`)return[];throw e}return t.filter(e=>/^\d+$/.test(e)).map(Number).sort((e,t)=>e-t)}function j6(e){let t=xo(e,4096);switch(t.kind){case`absent`:return null;case`failed`:throw Error(`${e}: ${t.reason}`);case`ok`:return t.value.buf.toString(`utf8`).split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1)??null}}function M6(e,t){let n=E.join(e,`.removed-${t}-${process.pid}`);try{l.renameSync(E.join(e,String(t)),n)}catch(e){if(e.code===`ENOENT`)return;throw e}l.rmSync(n,{recursive:!0,force:!0})}const N6=e=>e.now()-o.uptime()*1e3;async function P6(e,t,n){if(e.started<=n||!lt(e.pid))return!1;let r=await t(e.pid);return e.startTime===null||r.kind===`unavailable`||r.token===e.startTime}function F6(e){try{return JSON.parse(l.readFileSync(k6(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}const I6=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function L6(e,t,n){let r=null;async function i(i){let a=E.join(e,String(i)),o=F6(a);if(o===null)return null;if((r===null||!I6(r.record,o))&&(r={record:o,ours:await P6(o,t,N6(n)),final:null}),r.final!==null)return r.final;r.ours=r.ours&<(o.pid);let s=O6(a),c=st(s.status),u=c===null?null:j6(s.stderr)??j6(s.stdout);if(!l.existsSync(a))return null;let d={act:i,record:o,alive:r.ours,end:c,lastLine:u};return d.alive||(r.final=d),d}return{async read(){let t=null;for(;;){let n=A6(e).at(-1);if(n===void 0)return null;if(n===t)throw Error(`${E.join(e,String(n))}: an act with no record`);let r=await i(n);if(r!==null)return r;t=n}}}}function R6(e,t,n){l.mkdirSync(e,{recursive:!0});let r=l.mkdtempSync(E.join(e,`.claim-`));try{return l.writeFileSync(k6(r),JSON.stringify(n)),l.renameSync(r,t),!0}catch(e){let t=e.code;if(t===`ENOTEMPTY`||t===`EEXIST`)return!1;throw e}finally{l.rmSync(r,{recursive:!0,force:!0})}}async function z6(e,t,n,r,i,a,o,s){let c=(n??0)+1,l=E.join(t,String(c)),u=e.launchJobSync(i,O6(l));if(!u.ok)throw Error(`apply-update: ${u.error}`);let d=!1;try{let e=await s(u.pid);if(!R6(t,l,{identity:r,pid:u.pid,startTime:e.kind===`start`?e.token:null,started:o,deadline:o+a}))return B6;if(A6(t).some(e=>e>c))return M6(t,c),B6;d=!0}finally{d?u.release():u.withdraw()}for(let e of A6(t).filter(e=>e<c))M6(t,e);return{ok:!0,act:c}}const B6={ok:!1,reason:`another act claimed this bundle first`};function V6(e,t,n){let r=O6(E.join(e,String(t.act))).status;return dt(t.record.pid,r,{kind:`timeout`},n)}var H6=class{waiting=new Map;run(e,t){return new Promise((n,r)=>{let i=async()=>{try{n(await t())}catch(e){r(e)}},a=this.waiting.get(e);if(a!==void 0){a.push(i);return}let o=[];this.waiting.set(e,o);let s=t=>void t().then(()=>{let t=o.shift();t===void 0?this.waiting.delete(e):s(t)});s(i)})}};function U6(e){return e.kind===`source`?e.newer.digest:Po(e.newer)}const W6=e=>`${e.version} [${Ft(e.digest)}]`;function G6(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:W6(e.newer),running:W6(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:Po(e.newer),running:Po(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${Fo}@${Po(e.newer)}`,`install`]}}}}function K6(e,t,n){if(e===null)return[];let r=U6(e);if(!n.enabled||n.dismissed===r)return[];let i=G6(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
|
|
484
|
-
`),c=t.kind===`running`?aU(`[${i.busy}]`,null):aU(`[${i.act}]`,ea([{verb:Bi,args:[n.sessionId]}])),l=[aU(a,null),c,aU(`[dismiss]`,ea([{verb:Si,args:[n.sessionId,xz,r]}])),aU(`[disable]`,ea([{verb:Oi,args:[n.sessionId,Sz,`false`]},{verb:Si,args:[n.sessionId,Cz,`false`]}]))],u=o.map(e=>[aU(e,null)]);return[{severity:nU,about:`update\0${r}`,message:s,copy:s,lines:[l,...u]}]}function q6(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function J6(e){switch(e.kind){case`current`:return[`info`,`build: current ${W6(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${W6(e.source)}, running ${W6(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function Y6(e){switch(e.kind){case`current`:return[`info`,`release: current ${Po(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${Po(e.latest)}, running ${Po(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${Po(e.installed)}, latest ${Po(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function X6(e){let{clock:t,launcher:n,entryUrl:r,digest:i,actsDir:a,intervalMs:o,releaseIntervalMs:s,registryUrl:c,fetchImpl:l,gates:u,onApplied:d,log:f}=e,p={kind:`unchecked`,reason:`not sampled yet`},m=null,h=async e=>{let t=await vs(e,n.launch);if(C)throw new ZK(`apply-update`);return t},g=L6(a,h,t),_=null,v=null,y=Ne(f),b=Ne(f),x=new H6,S=e=>x.run(`acts`,e),C=!1,w=[],ee=(e,n)=>{w.push(t.every(n,e,{unref:!0}))},T=()=>C?null:q6(p,m);function te(){let e=T(),t=e===null?null:U6(e);(v===null?null:v.identity)!==t&&(v?.dispose(),v=t===null?null:{identity:t,dispose:u.state.register(xz,[t])})}function E(){p=Vt(r,()=>Rt(i)),y(J6(p)),te()}async function ne(){m=Lo(It,await Io(Fo,l,c,t)),b(Y6(m)),te()}let D=null,re=Ne(f);async function ie(e){try{let t=await e();return D=null,{ok:!0,value:t}}catch(e){return e instanceof ZK?{ok:!1,error:e.message}:(D=`update act files (${a}): ${e.message}`,re([`error`,D]),{ok:!1,error:D})}}function O(e){if(!e?.alive||t.now()<=e.record.deadline)return;let{stands:n,signalled:r}=V6(a,e,t),i=n?`timed out`:`outlived its verdict`,o=r?`ending it`:`its group took no signal`;f(`error`,`apply-update: act ${e.act} ${i}; ${o}`)}async function ae(){let e=await ie(async()=>{let e=await g.read();return C||O(e),e});if(C||!e.ok)return;let t=D6(e.value);_===null&&t.kind===`running`&&f(`info`,`apply-update: act ${t.act} is running; watching it`),_?.kind===`running`&&t.kind!==`running`&&(t.kind===`succeeded`&&(f(`info`,`apply-update: act ${t.act} succeeded`),E(),d()),t.kind===`failed`&&f(`error`,`apply-update: act ${t.act} failed: ${t.reason}`)),_=t}let oe;async function se(){await S(ae),!C&&(oe=t.after(2e3,()=>void se(),{unref:!0}))}return{arm(){E(),ee(E,o),w.push(()=>oe?.()),se(),p.kind===`not-source-checkout`&&(ne(),ee(()=>void ne(),s))},close(){C=!0,te(),w.forEach(e=>e())},notice:e=>K6(T(),_??E6,e),running:()=>S(async()=>{let e=await ie(()=>g.read());return e.ok&&D6(e.value).kind===`running`}),error:()=>D,act:()=>S(async()=>{if(C)throw new ZK(`apply-update`);let e=await ie(()=>g.read());if(C)throw new ZK(`apply-update`);if(!e.ok)throw new Z(`apply-update: ${e.error}`);let r=T();if(r===null)throw new Z(`apply-update: nothing newer is known to apply`);let i=G6(r),o=e.value;if(D6(o).kind===`running`)throw new Z(`apply-update: already ${i.busy}`);let s=await z6(n,a,o===null?null:o.act,U6(r),{...i.command,category:`update.apply`},6e5,t.now(),h);if(!s.ok)throw new Z(`apply-update: ${s.reason}`);f(`info`,`apply-update: act ${s.act}: ${i.act} — ${i.command.bin} ${i.command.args?.join(` `)??``}`),_={kind:`running`,act:s.act}})}}function Z6(e,t){try{return F(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?I:L(e.message)}}function Q6(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function $6(e){let{targets:t,intervalMs:n,stat:r,held:i,exit:a,log:o,clock:s}=e,c=Ne(o),l=t.map(e=>({path:e,stamp:Z6(e,r)})),u=l.filter(({stamp:e})=>e.kind!==`failed`),d=null,f=!1,p=()=>{f=!0,d?.()},m=async()=>{if(!f)for(let{path:e,stamp:t}of u){let n=Z6(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!Q6(t,n)){let t=`binary ${n.kind===`absent`?`gone`:`changed`} (${e})`,r=await i();if(f)return;if(r){c([`info`,`${t}; the restart waits for the running update`]);return}o(`info`,`${t}; shutting down`),p(),a();return}}},h=()=>m().catch(e=>{o(`error`,`binary check failed: ${e.message}`)});return{arm(){for(let{path:e,stamp:t}of l)t.kind===`failed`&&o(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);d=s.every(n,()=>void h(),{unref:!0})},checkNow:h,close:p}}function e8(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var t8=class{stop=null;state=`released`;last=null;constructor(e,t){this.tick=e,this.clock=t}landed(e,t=this.clock.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.clock.now());this.stop=this.clock.after(e,()=>{this.stop=null,this.tick()},{unref:!0})}cancel(){this.stop?.(),this.stop=null}};const n8=`pass`,r8={okMs:5*6e4,failedMs:45e3};function i8(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function a8(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function o8(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function s8(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:E.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>vc(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${yc(i[t])}`).join(`|`)}`,targets:{dirs:r},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function c8(e){return e.find(e=>e.kind===`ok`)?.value.branch}function l8(e){e.missed=!0,NY(e,`unread`)}function u8(e,t){return e.missed&&e.reading.get().kind===`pending`&&MY(e,t.size>0?L([...t].join(`; `)):I),`unkeyed`}function d8(e,t){let n=IY(e);return t===null||n.kind!==`ok`?n:F({...n.value,pullRequest:IY(t)})}function f8(e){return t=>L(`${e} threw: ${String(t)}`)}var p8=class{repos=new Map;resolutions=new Map;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;watchers;ownsWatchers;logger;clock;constructor(e){this.inner=e.inner,this.clock=e.clock,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Pe;let t=e.ledger??new dj(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 jC({clock:this.clock,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=this.clock.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=L(`resolver threw: ${String(e)}`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`not-a-repo`)return zY(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>d8(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 lj,watch:this.followWatch(e,null).watch,period:new t8(()=>{n.refresh.share(n8,()=>this.refreshPass(n))},this.clock),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=s8(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(n8,()=>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&&l8(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(n8,()=>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:AY(),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=o8(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(a8(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=this.clock.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(f8(`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,MY(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of eY(n.value))c.add(e)});let l=c8(o),u=a===null||i.length===0?`-`:l===void 0?u8(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}`,i8(n),c.size===0?F(null):L([...c].join(`; `)),this.clock.now()-t)}prSource(e){let t={period:new t8(()=>{this.readPr(e,t,`period`)},this.clock),seen:new Map,holders:0,missed:!0,key:``,remote:I,reading:AY(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(f8(`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?(l8(t),`owed`):(NY(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,MY(t,a.outcome),t.period.landed(e8(r8,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=this.clock.now(),o=(i.kind===`ok`?this.inner.resolvePullRequest(e.root,i.value).catch(f8(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:I)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${R(r)}`,n,i,this.clock.now()-a);let o=this.clock.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||(MY(t,i),t.period.landed(e8(r8,i),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=L(`git state dropped: ${e.root}`);for(let n of e.values.values())PY(n,t);e.pr!==null&&PY(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()}},m8=class{static usageDir(e){return E.join(e,`usage`)}static locksDir(e){return E.join(e,`locks`)}static isLocked(e,t){let n=E.join(this.locksDir(e),t);if(!l.existsSync(n))return!1;try{let e=l.readFileSync(n,`utf-8`),r=parseInt(e.trim(),10);if(isNaN(r))return k(`Invalid PID in lock file ${t}, removing stale lock`),l.unlinkSync(n),!1;try{return process.kill(r,0),!0}catch(e){return e.code===`ESRCH`?(k(`Removing stale lock file ${t} for dead process ${r}`),l.unlinkSync(n),!1):(k(`Error checking process ${r} for lock ${t}:`,e),!0)}}catch(e){return k(`Error reading lock file ${t}:`,e),!0}}static async acquireLock(e,t,n,r=5e3){await this.ensureCacheDirectories(e);let i=E.join(this.locksDir(e),n),a=t.now(),o=String(process.pid);for(;t.now()-a<r;)try{return await l.promises.writeFile(i,o,{flag:`wx`}),k(`Lock acquired for ${n}`),!0}catch(e){if(e.code===`EEXIST`)await A(t,50);else throw e}return k(`Failed to acquire lock for ${n} within ${r}ms`),!1}static async releaseLock(e,t){let n=E.join(this.locksDir(e),t);try{await l.promises.unlink(n),k(`Lock released for ${t}`)}catch(e){e.code!==`ENOENT`&&k(`Error releasing lock for ${t}:`,e)}}static async ensureCacheDirectories(e){try{await Promise.all([l.promises.mkdir(e,{recursive:!0}),l.promises.mkdir(this.usageDir(e),{recursive:!0}),l.promises.mkdir(this.locksDir(e),{recursive:!0})])}catch(e){k(`Failed to create cache directories:`,e)}}static createProjectHash(e){return oe(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t,n,r){await this.ensureCacheDirectories(e);let i=E.join(this.usageDir(e),`${n}.json`),a=`${n}.usage.lock`;for(let o=0;o<3;o++){if(this.isLocked(e,a)){k(`Cache for ${n} is locked, waiting...`),await A(t,75);continue}try{let e=await l.promises.readFile(i,`utf-8`),t=JSON.parse(e);return!r||t.timestamp>=r?(k(`[CACHE-HIT] ${n} disk cache: found`),this.deserializeDates(t.data)):(k(`${n} cache outdated: cache=${t.timestamp}, latest=${r}`),null)}catch(e){if(e.code===`ENOENT`)return k(`No shared ${n} usage cache found`),null;k(`Attempt ${o+1} failed to read ${n} cache: ${e.message}. Retrying...`),await A(t,75)}}return k(`Failed to read ${n} 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,r,i){let a=`${n}.usage.lock`;if(!await this.acquireLock(e,t,a)){k(`Could not acquire lock to set usage cache for ${n}`);return}try{await this.ensureCacheDirectories(e);let a=E.join(this.usageDir(e),`${n}.json`),o={data:r,timestamp:i||t.now()},s=JSON.stringify(o);await l.promises.writeFile(a,s,`utf-8`),k(`[CACHE-SET] ${n} disk cache stored`)}catch(e){k(`Failed to save ${n} usage cache:`,e)}finally{await this.releaseLock(e,a)}}};const h8={"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 g8=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(e,t){let n=t.now()-1440*60*1e3;return await m8.getUsageCache(e,t,`pricing`,n)}static async saveDiskCache(e,t,n){await m8.setUsageCache(e,t,`pricing`,n)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=_e({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.setEncoding(`utf8`),t.on(`data`,t=>{if(i+=Buffer.byteLength(t),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(e,t){if(this.executionCache!==null)return k(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let n=await this.loadDiskCache(e,t);if(n)return k(`[CACHE-HIT] Pricing disk cache: ${Object.keys(n).length} models`),this.executionCache=n,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(n).length} models`),n;let r=await this.fetchPricingData();return r?(await this.saveDiskCache(e,t,r),k(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(r).length} models`),this.executionCache=r,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(r).length} models`),r):(k(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(h8).length} models`),this.executionCache=h8,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(h8).length} models`),h8)}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,t,n){if(this.modelPricingCache.has(e))return k(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let r=await this.getCurrentPricing(t,n),i;return i=r[e]?r[e]:this.fuzzyMatchModel(e,r),this.modelPricingCache.set(e,i),k(`[CACHE-SET] Model pricing cache: ${e}`),i}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,t,n){let r=e.message?.usage;if(!r)return 0;let i=this.extractModelId(e),a=await this.getModelPricing(i,t,n),o=r.input_tokens||0,s=r.output_tokens||0,c=r.cache_creation_input_tokens||0,l=r.cache_read_input_tokens||0,u=o/1e6*a.input,d=s/1e6*a.output,f=l/1e6*a.cache_read,p=c/1e6*a.cache_write_5m;return u+d+p+f}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`}},_8=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}},v8=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:()=>IY(r)}}supersede(e){let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,NY(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:AY(),holders:0,flight:null,changed:!1,superseding:0,revisit:y8(this.spec.every,this.spec.clock,{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=this.spec.clock.now();x8(()=>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,this.spec.clock.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{MY(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(),PY(e,L(`${this.spec.name} entry dropped`))}};function y8(e,t,n){if(e===null)return new b8(n.holdReturned);let r=new t8(n.period,t);return{landed:t=>r.landed(e8(e,t)),hold:e=>r.hold(e),dispose:()=>r.dispose()}}var b8=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 x8(e){let t=e=>L(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function S8(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 C8={okMs:60*1e3,failedMs:10*1e3},w8={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},T8={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function E8(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function D8(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-1),t.getTime()}function O8(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const k8={entries:0,cost:0,breakdown:O8(),days:new Map};async function A8(e,t,n,r){let i=E8(new Date(D8(r.now()))),a=e.entries,o=e.cost,s={...e.breakdown},c=new Map;for(let[t,n]of e.days)t>=i&&c.set(t,{...n});for(let e of t){let t=e.message?.usage;if(!t)continue;a++;let l=e.costUSD??await g8.calculateCostForEntry(e.raw,n,r);o+=l,s.input+=t.input_tokens||0,s.output+=t.output_tokens||0,s.cacheCreation+=t.cache_creation_input_tokens||0,s.cacheRead+=t.cache_read_input_tokens||0;let u=E8(new Date(e.timestamp));if(u<i)continue;let d=c.get(u)??{...w8};d.cost+=l,d.input+=t.input_tokens||0,d.output+=t.output_tokens||0,d.cacheCreation+=t.cache_creation_input_tokens||0,d.cacheRead+=t.cache_read_input_tokens||0,c.set(u,d)}return{entries:a,cost:o,breakdown:s,days:c}}function j8(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function M8(e){let t=0,n=0,r=O8(),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)??{...w8};j8(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:T8,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 N8(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function P8(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!N8(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...w8};j8(r,t),n.set(e,r)}return n}async function F8(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 I8(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function L8(e,t){(0,Y.runInAction)(()=>e.set(t))}var R8=class{sessions=Y.observable.map(void 0,{deep:!1});flight=new _8;scans;daySets=new Map;speedFlight=new _8;requestFlight=new _8;staleAgeMs;host;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;stopSweep=null;clock;constructor(e){this.host=e.host,this.clock=e.clock,this.log=e.logger??Pe,this.ledger=e.ledger??new dj(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new v8({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${R(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??C8,maxEntries:8,logger:this.log,ledger:this.ledger,clock:this.clock});let t=e.sweepIntervalMs??3e5;t>0&&(this.stopSweep=this.clock.every(t,()=>this.sweepStale(),{unref:!0}))}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=ao(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async e=>{let t=await r().record;return t.kind===`failed`?t:F(I8(t.kind===`ok`?t.value.sessionInfo:T8,e))},speed:t=>this.observed(e,r,t),today:async e=>{await BY(e),await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return no;let r=n.failure.get();return r===null?F(I8(n.record?.sessionInfo??T8,t)):L(r)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=this.clock.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=${R(e)}`,`request`,a,this.clock.now()-i),L8(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=RX(t,this.host.home),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?F({roots:i.roots,sums:i.sums.read()}):e}}}todayAt(e,t,n){let r=this.sessions.get(t?.session_id??``),i=r?.failure.get()??null;if(i!==null)return L(i);let a=E8(RA(n)),o={...w8},s=e.sums.get(a);s!==void 0&&j8(o,s);let c=N8(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&j8(o,c),s===void 0&&c===void 0?I:F({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:a})}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return I;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return L8(this.hold(e).speed,t),t;let r=S8(t.kind===`ok`?t.value.sessionInfo.tokenBreakdown:null,n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=F({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return L8(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??no:I}async ingest(e,t,n,r){if(!e)return I;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,F(i);if(!t)return i?F(i):I;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,sessionInfo:s.value.sessionInfo,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),F(c)):l===void 0?F(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,Y.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=this.clock.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:this.clock.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=>ie(e,`projects`)+O),i={roots:r,sums:new UC(`today over ${e.join(`,`)}`,()=>P8(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await VX(e,D(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of XX(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 ZX(e,r,k8,(e,t)=>A8(e,t,j(this.host),this.clock));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 XX(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...M8(i),mainStamp:a})}async scan(e){try{let t=D8(this.clock.now()),n=await zX(e),r=[];for(let e of n){let n=await BX(lo(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=ie(e,i),a=await BX(uo(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:oo(a)})}}let i=[],a={hits:0,misses:0};return await F8(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=${R(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?L(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`):F({sessions:r.length,read:a.misses})}catch(e){return L(`usage scan: ${e instanceof Error?e.message:String(e)}`)}}sweepStale(){let e=this.clock.now(),t=E8(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.stopSweep?.(),this.stopSweep=null,this.scans.close(),(0,Y.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},z8=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)}})}},B8=class{sessions;constructor(e,t,n,r,i=Pe,a=256){this.empty=e,this.step=t,this.refreshes=n,this.clock=r,this.log=i,this.sessions=new z8(a)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=ao(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=this.clock.now(),o=await ZX(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${R(e)}`,`request`,o,this.clock.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 XX(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??no}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function V8(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 H8=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new B8(void 0,V8,(e.ledger??new dj(t)).declare({name:`context`,scope:`session`,refresh:[`request`]}),e.clock,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?F(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,U8(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return F(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,U8(e))}contextFrom(e,t){if(e.kind===`failed`)return L(`context transcript: ${e.reason}`);let n=e.value;return n===void 0?(k(`No main chain entries with usage data found`),I):(k(`Most recent main chain context: ${n} tokens (limit: ${t})`),F({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function U8(e){return e.context_window?.context_window_size??2e5}const W8={messageCount:0,nonPrompts:0,recent:[]},G8=new Set([`turn`,`interrupt`,`claude-code`]);function K8(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!G8.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function q8(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 J8=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new B8(W8,K8,(e.ledger??new dj(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getMetricsInfo(e,t){k(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?Y8(e,n,await this.fold.read(e,t.transcript_path)):I}metricsOf(e,t){let n=t.cost;if(!n)return I;let r=this.fold.answer(e);return r.kind===`pending`?r:Y8(e,n,r)}};function Y8(e,t,n){return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`):F({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:q8(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 X8={command:null,todos:[],pending:[],done:[]};function Z8(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 Q8(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 $8(e,t){if(t.isSidechain)return e;let n=Q8(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=Z8(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 e5(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>Z8(e,t.name),[]),done:e.done}}var t5=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new B8(X8,$8,(e.ledger??new dj(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getActivityInfo(e,t){return n5(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:n5(e,t)}};function n5(e,t){return t.kind===`failed`?L(`activity (${e}): ${t.reason}`):F(e5(t.value))}const r5=3e4;var i5=class{names;constructor(e){let t=e.logger??Pe;this.names=new v8({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${R(e.pane)} socket=${R(e.socket)}`,read:t=>a5(e.launcher,t),every:{okMs:r5,failedMs:r5},maxEntries:64,logger:t,ledger:e.ledger??new dj(t),clock:e.clock})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function a5(e,t){let n=await Ws(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return L(n.reason);let r=n.stdout.trim();return r?F(r):I}const o5=6e4,s5={okMs:o5,failedMs:o5};function c5(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function l5(e,t){try{let e=t();return Promise.resolve(e===``?I:F(e))}catch(t){return Promise.resolve(L(`host.${e}: ${String(t)}`))}}var u5=class{name;user;constructor(e){let t=e.logger??Pe,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:s5,maxEntries:1,logger:t,ledger:e.ledger??new dj(t),clock:e.clock};this.name=new v8({...n,name:`host.name`,read:()=>l5(`name`,()=>c5(o.hostname()))}),this.user=new v8({...n,name:`host.user`,read:()=>l5(`user`,()=>o.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()}},d5=class{known=new z8(64);refreshes;constructor(e,t=Pe,n=new dj(t)){this.clock=e,this.refreshes=n.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=f5(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=this.clock.now(),i=bI(e);return this.refreshes.recorded(`path=${R(e)} stamp=${R(t)}`,`request`,i,this.clock.now()-r),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??no}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}};function f5(e){try{let t=l.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:oo(t)}catch(e){return`unread:${e.code??`error`}`}}const p5=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function m5(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 h5=class{known=new z8(256);refreshes;constructor(e,t=Pe,n=new dj(t)){this.clock=e,this.refreshes=n.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=ao(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??no}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=this.clock.now(),i=await g5(t);return this.refreshes.recorded(`sid=${R(e)} stamp=${R(n)}`,`request`,i,this.clock.now()-r),i}};async function g5(e){let t=await _5(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function _5(e){for(let t of[65536,1048576]){let n=await bo(e,t);if(n.kind!==`ok`)return n;let r=v5(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function v5(e,t){let n=e.toString(`utf8`).split(`
|
|
485
|
-
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!p5.test(t))continue;let r=m5(t);if(r!=null)return r}return null}var y5=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:L(n)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,Y.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const b5=e=>JV(e),x5=e=>E.join(e.storage.folder,b5(e.sessionId)),S5=e=>JSON.stringify([e.folder,e.generation]),C5=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var w5=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;identityOf;fileEvents;clock;unsubscribe;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??hc,this.fileEvents=e.fileEvents,this.clock=e.clock,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new v8({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${R(x5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new dj(e.logger),clock:e.clock})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{l.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`||!gc(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${R(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(S5(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:${S5(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),stopSweep:this.clock.every(864e5,()=>void this.sweep(e),{unref:!0}),health:{kind:`watching`}};this.watched.set(S5(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=S5(e.key);this.watched.delete(t),e.health={kind:`closed`},e.stopSweep(),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>C5(e.storage,n);switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.has(E.join(n.folder,E.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(x5(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`&&gc(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${R(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>C5(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=${R(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>C5(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(S5(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=Dc(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 L(t);let n=x5(e),r;try{r=await l.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?I:L(`${n}: ${t.message}`)}if(r.trim()===``)return I;let i=cj(r);return i.kind===`failed`?L(`${n}: ${i.reason}`):i}async sweep(e){let t=this.clock.now(),n=t-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${R(e.folder)} scanned=${r} removed=${i} took=${this.clock.now()-t}ms`;try{let t=await l.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=E.join(e.folder,a.name);try{let{mtimeMs:r}=await l.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&b5(t.sessionId)===a.name);if(r>=n||o)continue;await l.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 T5(e){let{launcher:t,clock:n,logger:r,ledger:i}=e;return{home:e.host.home,hostService:new u5({clock:n,logger:r,ledger:i}),gitProvider:new p8({inner:new OY(t),watchers:e.watchers,clock:n,logger:r,ledger:i}),usageStore:new R8({host:e.host,clock:n,logger:r,ledger:i}),contextProvider:new H8({clock:n,logger:r,ledger:i}),metricsProvider:new J8({clock:n,logger:r,ledger:i}),activityProvider:new t5({clock:n,logger:r,ledger:i}),tmuxService:new i5({launcher:t,clock:n,logger:r,ledger:i}),autoCompact:new d5(n,r,i),cacheExpiry:new h5(n,r,i),managedStorage:new w5({watchers:e.watchers,fileEvents:e.fileEvents,clock:n,logger:r,ledger:i}),faults:new y5,log:e.logger,clock:n}}function*E5(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*D5(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);yield*Object.values(t.partials??{})}for(let t of mS(e.presets)){for(let n of Fy(_S(e,t).node))n.when!==void 0&&(yield n.when);let n=bS(e,t);for(let e of Qv){let t=n[e];$v(t)&&(yield t)}}for(let[,t]of E5(e))for(let[,e]of Wy(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of jS(t))yield e}function O5(e,t,n){let r=MW(t),i=new Set,a=new Set,o=new Set;for(let e of D5(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of aC(e,t.helpers))a.add(n);for(let n of dC(e,t.helpers))o.add(n)}for(let[,e]of E5(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 mS(t.presets))for(let n of Fy(_S(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=>!hi(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(E5(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 k5(e){return oe(`sha256`).update(JSON.stringify(e)).digest(`hex`)}var A5=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 j5(e){return Math.floor(Math.max(e/4,e*yr-67108864))}const M5={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function N5(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[qV(FS(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[FS(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>IS(e)(t)&&t!==qV(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${zN(e,`<default>`)}: projections=${[...IW(n).keys()].join(`,`)||`-`} instantSegments=${Z4(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 P5=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},F5=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${P5(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function I5(e,t,n){let r=e=>R(e.join(`,`)||`-`);return`config loaded projectDir=${R(e.projectDir)} cwd=${R(e.cwd)} cause=${R(F5(t))} state=${n} files=${R(zN(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 L5(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function R5(e,t,n){return e+`\0`+t+`\0`+(n??``)}function z5(e,t){return new Set(mS(e.presets).filter(n=>_S(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function B5(e,t){let{loaded:n,dropped:r,unreached:i}=e.state.plugins,a=[...new Set([...e.state.plugins.roots,E.join(e.projectDir,DH)])];return wC({named:[...VH(t,e.projectDir,e.cwd,e.configFile),...a,...n.map(e=>e.path),...[...r,...i].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))],whole:a})}function V5(e){return e.filter(Boolean).join(`
|
|
486
|
-
`)||null}const H5=e=>e instanceof Error?e.message:String(e);function U5(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function W5(e){let{loaded:t,chain:n}=e;return k5({cwd:e.cwd,chain:{layers:n.layers,home:n.home,repo:n.repo,locs:n.locs},loaded:{layers:t.layers.map(e=>({path:e.path,raw:e.raw,config:e.config,plugins:U5(e.plugins),source:null,warnings:null})),base:t.base,installed:{...U5(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 G5(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 K5(e,t,n){let r=[];try{let i=jG(t.locs,t.layers,rK,{warned:e=>r.push(...e)},{repo:t.repo,cwd:e}),a={cwd:e,chain:t,loaded:i,sources:G5(i.config,n)};return{kind:`resolved`,...a,key:W5(a),warnings:r}}catch(e){return e instanceof ib&&r.push(...e.warnings),{kind:`failed`,cause:e,warnings:r}}}function q5(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??rK,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new $C(t.clock),m=new Aj(t.launcher,p,o.globals.default_empty_value??``,t.sessionState,null,t.ledger,t.fileEvents,t.watchers,t.env),h;try{h=G4(o,m,n,t.compile??W4(t.signer),Q5),f.push(...h.loadWarnings);let r=m.view();f.push(...J4(o,r,n,$5)),r.dispose(),t.gates.state.gateFor(o),t.gates.config.gateFor(o);for(let n of new Set(e.sources.values()))m.own(t.storage.watch(n))}catch(e){return m.dispose(),e instanceof ib&&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:tX(o),authoredRoots:z5(l,u),fileHeldSettings:PK(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>O5(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 J5(e,t,n,r,i){let a={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:Math.round(i.monotonic()-e.started)},o=t=>V5([...e.advisories,...n,...t]);switch(r.kind){case`built`:case`kept`:return{...a,kind:r.kind,warning:o(r.state.buildWarnings),state:r.state,error:null};case`failed`:return{...a,kind:`failed`,warning:o(r.warnings),state:null,error:H5(r.cause),cause:r.cause}}}function Y5(e,t,n,r,i=null){let a=K5(t,n,r.storage);if(a.kind===`failed`)return J5(e,n,[],a,r.clock);let o=i?.loadKey===a.key?{kind:`kept`,state:i}:q5(a,r);return J5(e,n,a.warnings,o,r.clock)}function X5(e,t,n,r,i=null){let a=r.clock.monotonic(),o=GH(r.locations,kU(r.stateDir).read(),e,t,n),{repos:s}=o,c={layers:o.kind===`chain`?o.layers:[],home:o.home,repo:s.plugins,locs:r.locations};return Y5({repos:s,advisories:[QH(r.locations,e,t),XH(o),RH(s)],started:a},t,c,r,i)}function Z5(e,t,n){let r=K5(e,{layers:[],home:``,repo:t,locs:n.locations},n.storage),i=r.kind===`failed`?r:q5(r,n);if(i.kind===`failed`)throw Error(`bundled default failed to load: ${H5(i.cause)}`,{cause:i.cause});return i.state}const Q5=new Set([`directory`]),$5=new Set([`view`]);function e7(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new A5;J4(e.config,l,t,$5);let d=()=>dK(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)}`),fX(L(`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()});v4(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 t7=class{entries=new Map;answersWatch;stopSweep=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??{},l.mkdirSync(DU(e.stateDir),{recursive:!0});let{dir:n,name:r}=xC(OU(e.stateDir));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)??X4(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=R5(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`,N5(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??Z5(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=${mr(this.accountedBytes())}/${mr(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=io();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(R5(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=e7(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.stopSweep===null&&(this.stopSweep=this.deps.clock.every(15e4,()=>this.releaseIdle(),{unref:!0}))}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.stopSweep!==null&&(this.stopSweep(),this.stopSweep=null)}close(){if(this.closed)return;this.closed=!0,this.stopSweep?.(),this.stopSweep=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 X5(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=${mr(this.accountedBytes())}/${mr(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`,L5(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`,N5(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=B5(e,this.deps.locations),{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 n7=e=>!oJ(e)&&!cI(e)&&e!==`update.dismissed`&&e!==yi;var r7=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:tJ(e,n7,(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 Z(`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 i7(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>fK(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return SX({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...FK(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 a7=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,o7=`#{session_id} #{client_control_mode} #{pane_id}`;function s7(e){let t=new Set;for(let n of e.split(`
|
|
483
|
+
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function N2(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 P2=e=>e.kind===`failed`?I1:e;function F2(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function I2(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 L2(e){return{...e,cells:e.cells.map(H1)}}function R2(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,...z2(e,r)]}function z2(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 B2(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:R2(e.direction,e.children.map((t,i)=>n(t,[...r,V2(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function V2(e,t){return e.steps[t]}function H2(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=U2(e);return{width:W2(t),reach:G2(t)}}function U2(e){let t=e.children.map(H2),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 W2=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),G2=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function K2(e,t){let n=U2(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=Ay[e.direction],i=iv(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),G2(n),W2(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const q2={compile(e,t){let n=K2(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,Iy(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),R2(e.direction,e.children.map((n,r)=>t.renderChild(n,P2(t.gate),V2(e,r))))}},J2={drop:e=>e.place,above:()=>`above`},Y2={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},X2={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:jy(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(ni(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Ly(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,Z2(e,t))};function Z2(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=nj(t.scope,e.settings);if(t.gate.kind===`failed`)return r4(e,r,t,t.gate.message);try{let i=t.placement(e),a=F2(t.gate,i.gate());if(a.kind===`failed`)return r4(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 r4(e,r,t,s.message);let c=Ux(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:yN(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`?Q2(f.variable):$2(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?e4(p.segment,u):t4(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:I1,h.disclosure).map(e=>({...e,place:J2[v.placement](e)})),b=(e,t,n)=>G1(Q1([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?Y2[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},w=S.flatMap(e=>b(new K(` `.repeat(n4(V1(e)))),h.trigger,0)),ee=(e,t)=>e.band===`own`?t===x?S:w:[],T=y.map((e,t)=>({cells:[...ee(e,t),...e.cells],band:`deeper`,place:e.place})),te=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...te.flatMap(e=>e.cells),...y.flatMap(ee)].flatMap(V1)),[...te,...T]}catch(n){return r4(e,r,t,n.message??String(n))}}const Q2=e=>({kind:`waiting`,variable:e});function $2(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=BC(e);if(t===void 0)throw e;return Q2(t.variable)}}function e4(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:M2(Q1(r,c)).map((e,t)=>({cells:G1(e,{...l,lead:t===0?Q1(i,c):[],trail:t===0?Q1(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:G1(Q1([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function t4(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=Q1(i4(e.lead,e,t,n),l),d=Q1(i4(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 G1(Q1([new K(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function n4(e){return e.reduce((e,t)=>e+t.cellLength,0)}function r4(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:G1([new K(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:yN(n.palette)},lead:i4(e.lead,e,t,n),trail:i4(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function i4(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=BC(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const a4={container:q2,segment:X2};function o4(e){return a4[e]}var s4=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?c4:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const c4={kind:`hidden`},l4={palette:`theme`,style:`style`,effect:`effect`},u4=Lx.get(`colorCompatibility`),d4={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function f4(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function p4(e){if(e.ok)return e.value;throw e.error}const m4=e=>({read:()=>e}),h4=b_({basePalette:y_,palette:y_,decor:Fv});var g4=class{evaluated=0;memory=new s4;scope;binding;facts;look=Y.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&h4(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=ej(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(u4);return typeof e==`string`&&yy(e)?e:`truecolor`});let i=(0,Y.observable)(d4,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 B2(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=AR(e);return i===void 0?[]:[{name:i,address:n,palette:Ux(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>by(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=zj(e);return t===void 0?Lj(e)===void 0?Ej(this.view.get().payload(),e):Ej(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()[l4[e]];if(t.kind===`decided`)return y4(t.name,null,null);let r=x4(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=S4(this.source,e,i.name,r.where,e=>{t=e}),y4(n,t,null)}case`pending`:return y4(n??oy[e],null,i.variable);case`failed`:return n=oy[e],y4(n,sy(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!b4(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)??oy[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 R1(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>R0(this.source.activeSegment,()=>R1(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new C4(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:i0(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=BC(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:f4(e)}),p4(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:AR(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function _4(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new g4(t,n,e,r);return e.views.set(t,a),a}function v4(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 y4=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),b4=(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 x4(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 S4(e,t,n,r,i){switch(t){case`palette`:return Jx(n,r,i).name;case`style`:return ry(n,e.styles).name;case`effect`:return py(n).name}}var C4=class{where=w4(b_({palette:y_,region:Nv}));ground=w4(b_({colours:E4,bodyOpen:y_}));opened=w4(b_({colours:E4,open:y_}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=nj(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?m4(L1):e.derive(`${t.id} when`,e.readsInstant(a),()=>R0(r,()=>R1(a,i))),this.open=d===void 0?m4(I1):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>R0(r,()=>R1(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return k4(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 A4(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?m4(M4):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return j4(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}),P4(n,r,this.affixes.read())}};function w4(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 T4=(e,t)=>e.hex===t.hex,E4=b_({palette:y_,drawnAt:y_,tint:T4,text:T4,bg:T4,disclosure:Iv});function D4(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const O4=e=>Av(e.palette,e.disclosure,e.drawnAt);function k4(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Hv(n,r,i)};return L0(e,D4(t,c),e=>{let t=xN(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function A4(e,t,n,r,i,a){return L0(e,D4(t,n),e=>(e.bg=i?O4(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function j4(e,t,n,r,i,a,o){return L0(e,D4(t,n),e=>(e.bg=r?O4(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const M4={lead:[],trail:[],drops:[]};function N4(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return b0(t,O4(e).state,n)},get band(){return b0(t,O4(e).plane,n)},get close(){return C0(t,O4(e).state,n)},disclosure:r}}function P4(e,t,n){return{styles:N4(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function F4(e,t,n,r,i,a,o){let s=k4(e,t,n,r,i,void 0,void 0,o);return P4(s,A4(e,t,s,a,!1,o),M4)}function I4(e,t,n,r,i){return N4(k4(e,t,n,r,i,void 0,void 0,{}))}function L4(e,t){return{payload:()=>e,selections:()=>t}}function R4(e){if(`ttl`in e)return{kind:`ttl`,durationMs:hj(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 z4(e,t){switch(By(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 B4(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:R4(n.cache),parse:z4(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:R4(n.cache),parse:z4(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 V4(e,t,n,r=Ow.EMPTY){let i=r;for(let[r,a]of Object.entries(t))try{i=e.parse(`{{ define "${r}" }}${a}{{ end }}`,i).defines()}catch(e){throw Error(`Template parse error in ${n}.${r}: ${e.message}`,{cause:e})}return i}function H4(e,t,n){let{compiled:r,loadWarnings:i}=W4(e,t,n.cwd,U4(n.signer),J4);return{...r,loadWarnings:i}}const U4=e=>(t,n)=>Y4(n,e);function W4(e,t,n,r,i=J4){let a=G4(e),o=K4(a);return{compiled:r(o,a),compileKey:o,loadWarnings:q4(e,t,n,i)}}function G4(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of Rx)n in t&&r.set(e,n);for(let[t,n]of qy(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...FW(e)].sort(([e],[t])=>e<t?-1:1)}}function K4(e){return oe(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function q4(e,t,n,r){let i=A2(e),a=FW(e),o=[];for(let[s,c]of gC(e))if(r.has(i.get(s)))try{B4(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const J4=new Set([`directory`,`view`]);function Y4({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>t0(i,`drawnAt`).registry.drawnAt(),o=F0(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=mS(e.presets),u=yR(e),d=[e=>i2(i,o,e.now)],f=$A({extraFuncs:{...v0(i),...r2(i),...X0(i,o),...$0(i),...l2(i,o),...h2(i,o),...y2(s),...S2(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=V4(f,e.helpers,`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=a0(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=n.partials===void 0?p:V4(f,n.partials,`segments.${t}.partials`,p),r=t=>{let n=f.parse(t,e);return m.set(n,t),n},i=(e,i,a=n.partials===void 0?_:r)=>{try{return a(e)}catch(e){throw Error(`Template parse error in segments.${t}.${i}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:i(n.when,`when`),template:i(n.template,`template`,r),bg:n.bg===void 0?void 0:i(n.bg,`bg`,r),fg:n.fg===void 0?void 0:i(n.fg,`fg`,r)}}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=Zy(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Tee(t,e,a,t=>String(t0(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 o4(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=_S(e,t);C.set(t,S(n,r,void 0))}let w=new Map(Qv.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of LW(e)){let e=t.join(`.`),i=w.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:Q4(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let ee=new Set(n.map(([e])=>e)),T={reads:OW({names:ee,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:XA(d)},te=BW(T),E=[...C.values()].flatMap(Z4(y)).some(e=>te(m.get(e))),ne=E?new Set([...T.clock,m2]):T.clock,D=BW({...T,clock:ne}),re=new Set([...m].flatMap(([e,t])=>D(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=BW({reads:OW({names:ee,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:T.projections,clock:ne});for(let e of lH){let n=y[t][e];n!==void 0&&r(m.get(n))&&re.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:w,instant:re,layoutReadsInstant:E,styles:e.styles,runtime:i,views:new WeakMap}}function X4(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 Z4=e=>t=>{let n=[];return B2(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 Q4(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 $4=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function e3(e,t,n,r,i){let a=t3(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function t3(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??oy[e];case`failed`:return r({kind:`rule`,slot:e,message:sy(t.where,e,`the rule failed — ${n.error}`)}),oy[e]}}function n3(e){return r3(e).filter(e=>!e.name.startsWith(fi)).map(e=>e.id)}function r3(e){return e.kind===`container`?e.children.flatMap(r3):[e,...e.opens===void 0?[]:r3(e.opens.body)]}function i3(e,t,n,r,i,a){let o={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return _4(e,t,n,L4(o,a)),o}function a3(e,t,n,r,i,a,o,s,c){try{var l=io();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new $N(``),h=m.clockAt(a,ly[c.animationSpeed]),g=l.u(BA(a,h.timeline)),_=v4(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:LP(v),padding:v.padding,seamCols:RP(v),preset:c.preset},i);let y=_.evaluated;l.u(i0(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:H_[c.variation],shade:N_[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},w=_.memory.begin(C,I2),ee=_.memory.from(C),T=new Set,te={held:e=>ee?.rules.get(e),waited:e=>T.add(e),settled:w.rule},E=new Map,ne=e=>{let n=_.slot(e);if(E.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&&T.add(n.waited),n.name;let r=S4(t,e,e3(e,n.rule,_,p,te),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:D,style:re,effect:ie}=_.selections(),O=D.kind===`decided`?D:Jx(ne(`palette`),``,$4),ae=re.kind===`decided`?re:ry(ne(`style`),e.styles),oe=ie.kind===`decided`?ie:py(ne(`effect`)),se=O.value,ce=Gx(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:bv(ce,le,r.drawnAt())},de=m.motion(oe.value,h,{transitions:x,source:C,last:ee,returned:I2,hold:L2},ue);u?.clear();let fe=t=>e.segments[t],pe=(e,i,a)=>{let o=i.kind===`hidden`?i:F2(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${n3(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)=>F4(t.activeSegment,e,i,a,r.drawnAt(),o,n),lookupSegment:fe,renderChild:(e,t,n)=>pe(e,t,Bv(a,n)),renderBody:(e,t,n)=>pe(e,t,Vv(n)),closeDisclosure:e=>y0(n,e),placed:(e,t)=>w.placed(e,de.placed(e,t)),lastDrawn:e=>ee?.placements.get(e),waited:e=>T.add(e),decorations:(e,n)=>I4(t.activeSegment,e,n,a,r.drawnAt())};return o4(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 "${pS}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let he=N2(pe(me,L1,zv(S))).map(({line:e,row:t})=>{let n=X1(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...WP(n.map(e=>e.owner),v,de.row(t,r,n))}});de.drawn(),w.commit();let ge=()=>he.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||r3(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:[...T].sort()},evaluated:_.evaluated-y,cellBreaks:he.reduce((e,t)=>e+t.cellBreaks,0),rules:E}}catch(e){l.e=e}finally{l.d()}}const o3={moving:1e3/30,still:1e3},s3=[`data`,`state`,`reload`,`visibility`];function c3(e){return Vb.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 l3(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const u3=(e,t)=>Bb[t].handsOff?e.resp:e.statusline,d3=e=>Math.round(1e3/e);var f3=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 Jb;let r=t-1,i=this.shown(n);return qb(e=>{let a=n.rates.get(e);if(a===void 0)return Gb;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.clock.monotonic(),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`&&e.phase.clear(),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.clock.monotonic(),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: ${C(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,d3(this.spacingOf(e)),r);if(i===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=n;let a=this.deps.clock.monotonic();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.clock.monotonic(),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){let r=Math.max(0,(t-n)*1e3);this.setTimer(e,t,this.deps.clock.monotonic()+r,r)}setTimer(e,t,n,r){e.phase.kind===`due`&&e.phase.clear(),e.phase={kind:`due`,at:n,clear:this.deps.clock.after(r,()=>this.fire(e,t,n))}}fire(e,t,n){let r=n-this.deps.clock.monotonic();r>0?this.setTimer(e,t,n,r):this.draw(e,t)}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||u3(a,t)!==u3(i,t))&&l3(r,n);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let n=u3(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:mM(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.clock.monotonic(),r=this.deps.refreshes(),i=(n-e.since)/1e3,a=i===0?`-`:`${(e.drawn/i).toFixed(1)}fps`,o=uj.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=${d3(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${s3.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 p3(e,t){return Vb.filter(n=>e[n]&&Bb[n].handsOff&&t.has(n))}function m3(e,t){return{severity:rU,lines:[[iU(`[⟲ claude]`,ea([{verb:Pi,args:[e,...t.map(e=>Bb[e].switch.setting)]}]))]]}}function h3(e,t){for(let n of Object.entries(t))e.push(n)}const g3={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function _3(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,C(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function v3(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],..._3(n)];return{level:g3[n.kind],line:`${e}${i.map(([e,t])=>` ${e}=${R(t)}`).join(``)}`}}const y3=()=>{},b3=e=>({ok:!1,error:e instanceof Error?e.message:C(e),code:`RENDER_FAILED`,daemonV:3}),x3={ansi:e=>({ok:!0,output:EP(e)}),frame:e=>({ok:!0,frame:e})};function S3(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.now(),s=[];try{try{var c=io();let i=c.u(O3(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=A3(e,i,{by:`feed`,fps:n}),p=x3.ansi(o.body),m=L3(t,o,p3(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:x3.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}=v3(`render`,s,{kind:`threw`,error:e},i.now()-o),r=b3(e);return{bar:gP(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:y3,failure:{level:t,line:`frame ${n}`}}}}function C3(e,t,n){let{sessionState:r}=e;return dK(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function w3(e,t){try{var n=io();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:cK(i.view.source.effective(),pc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function T3(e,t,n){try{var r=io();let{renderCache:i,frameFeeds:a}=e,o=r.u(i.hold(t.projectDir,t.cwd,t.target.path)),s=a.latest(n);return cK(C3(e,n,o.state),s===null||pc(s.hints.tmux))}catch(e){r.e=e}finally{r.d()}}function E3(e,t,n){h3(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=bn(e,r),a=xn(i);return h3(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 D3(e,t,n,r){let{sessionState:i,renderCache:a}=e,o=t.hookData.workspace?.current_dir??t.cwd,s={...t,hookData:{...t.hookData,...o!==void 0&&E.isAbsolute(o)&&{location:dc(o)}}},c=s.sessionId,l=E3(s,n,r);h3(r,{encoding:s.encoding});let u=P$(s.requested,i,c);return k3(e,a.holdSession(u.projectDir,u.cwd,u.target.path,s),s,l,n,r)}function O3(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=E3(o,n,r)}catch(e){throw a[Symbol.dispose](),e}return k3(e,a,o,s,n,r)}function k3(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 A3(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=cK(S,pc(b.facts().hints.tmux));h3(g,{lanes:Vb.filter(e=>C[e]).join(`,`)||`-`});let{hints:w}=b.facts(),ee=oX(w);h3(g,{width:String(ee)});let T=b.source.payload(),te=Ys(r,_,h,n.by),E=te.kind===`held`||te.kind===`owed`?te.error:null,ne=o.notice({sessionId:_,dismissed:r.get(_,bz),enabled:S.updateNotice}),D=jU(v.repos,_,s),re=(e,t)=>({about:e,text:t,copy:t}),ie=e=>re(e??``,e),O=[ie(Cn(m.refusedArgs)),ie(x),re(`load`,v.lastError),re(`update-act`,o.error()),...y.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),ie(E?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),ae=v.watch===null?null:TC(`config watch`,v.watch,null),oe=[...Oc(c.delivery()),...p.lifelineWarnings(),...ae===null?[]:[{kind:`config-watch`,message:ae}],...v.lastWarning===null?[]:[{kind:`load`,message:v.lastWarning}]],se={config:y.config},ce=aU(_,n.by,O,[...ne,...D],[...oe,...l.ofSession(_,n.by,se)].map(e=>({about:`${e.kind}\0${e.message}`,text:e.message,copy:e.message}))),le={diagnostics:hU(ce),drawing:n,feeds:i.feedsOf(_,h),today:SX(u,b.lanes().today,b.facts().hookData,h)},ue=ro(T.metrics)?void 0:T.metrics;h3(g,_X(b.lanes().sources)),h3(g,{prompts:String(ue?.messageCount??`-`),nonPrompts:String(ue?.nonPrompts??`-`),pr:WY(T.git,nX(t.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:c3(le.feeds)});let de=[],fe=VY(S,ee),pe=d.of(_),me=f.since(_,h),{frame:he,evaluated:ge,cellBreaks:_e,rules:ve}=a3(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=sU(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);h3(g,{menuIdle:Se===void 0?`-`:`${(h-Se).toFixed(1)}s/${S.menuTimeout}s`});let Ce=l.drawn(_,n.by,se,de),we={width:ee,rows:_U(w.termRows,n.by===`feed`?Vb.flatMap(e=>{let t=Bb[e].rows;return C[e]&&t!==null?[t]:[]}):[]),colorCompatibility:he.depth},Te=gU(r.get(_,yi),ce),Ee=Te===null?he:mP(he,vU(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 h3(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:te.kind===`none`?`-`:te.kind,upd:String(ne.length),ask:String(D.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:E,delivered:xe,lanes:C}}function j3(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,JK,o);let s=P1(t.requested);n.get(r,`render-origin`)!==s&&n.set(r,qK,s)}async function M3(e,t,n,r,i){return j3(e,t),I3(e,t,n,r,i)}function N3(e,t,n){let{laneSetups:r,tmuxStatusLines:i}=e;r.noted(P3(e,t),n),i.observe(t.hookData.session_id,t.hints.tmux,n.tmuxStatus)}function P3(e,t){let{sessionState:n}=e,r=t.hookData.session_id;return{sessionId:r,hints:t.hints,origin:P$(t.requested,n,r),transcript:t.hookData.transcript_path,answered:qP(t.hookData)}}function F3(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);a.clicked(t,s===null?null:P3(e,s),n,r),s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus)}async function I3(e,t,n,r,i){try{var a=io();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(D3(e,t,n,i));N3(e,t,cK(l.view.source.effective(),pc(t.hints.tmux)));let u=o.monotonic(),d=r-u;h3(i,{deadline:`${t.deadline.kind}:${Math.round(d)}ms`});let f=new Map,p=await LY(e=>Promise.all([CX(l.payloadInputs,n,f),l.view.registry.inFlight(e)]),d,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${C(e)}`),o.after),m=o.monotonic();h3(i,{waited:`${Math.round(m-u)}ms`,ended:p,refreshed:cX(f)});let{drawn:h,clickShown:g,delivered:_,lanes:v}=A3(e,l,Ub),y=t.sessionId,b=p3(v,s.following(y)),x=JP(t.hints.client??null)===`statusline`,S=x3[t.encoding](x?L3(y,h,b):h.body);return h3(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 L3(e,t,n){let[r,...i]=n;return r===void 0||t.viewerOpen?t.body:mP(t.body,yU(m3(e,[r,...i]),t.diagnostics,e,t.geometry))}const R3=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`]),z3=[[`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`]],B3=[[`workspace.added_dirs`,`string-list`]];function V3(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of z3){let i=W3(n,e);if(i==null)t.missingRequired.push(e);else{let n=H3(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of B3){let i=W3(n,e),a=i===void 0?r:U3(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))R3.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function H3(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function U3(e){return Array.isArray(e)&&e.every(e=>H3(e)===`string`)?`string-list`:H3(e)}function W3(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 G3(e,t,n){let{tokens:r}=w({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),i=(r??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),a=(r??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===i&&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:PN(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function K3(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=_n.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${_n.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function q3(e,t,n,r){let{report:i}=V3(e.hookData),a=[];for(let e of i.missingRequired)a.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of i.typeMismatches)a.push(`field '${e}' expected ${t}, got ${n}`);let o=f$(e.hookData?.session_id);o.ok||a.push(`field 'session_id' ${o.problem}`),(typeof e.cwd!=`string`||!re(e.cwd))&&a.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&a.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let s=K3(e.encoding);s.ok||a.push(s.problem);let c=Gn(e.deadline);if(c.kind===`refused`)return{ok:!1,problems:[...a,c.problem]};if(a.length>0||!o.ok||!s.ok)return{ok:!1,problems:a};for(let e of i.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let l=yn(e),{configFile:u,refusedArgs:d}=G3(e.args,e.cwd,r);return{ok:!0,req:{...e,deadline:c,encoding:s.encoding,sessionId:o.id,hints:l,rateLimits:Qee(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:LN(u,l.configEnv)},refusedArgs:d}}}function J3(e,t){switch(e){case`vars`:return{what:e,vars:Y3(t)};case`segments`:return{what:e,segments:e6(t)};case`config`:return{what:e,config:i6(t)}}}function Y3(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=Q3(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=X3(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:Z3(r.lastUpdatedMs(),t.clock)})}return o}function X3(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 Z3(e,t){return e===null?null:Math.max(0,t.now()-e)}function Q3(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,$3(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}`,$3(i));return t}function $3(e){return e.kind}function e6(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=n6(n),o=t6(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:r6(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function t6(e){let t=new Map;for(let n of mS(e.presets))for(let r of Fy(_S(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=jy(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function n6(e){let t=[],n=new Set;for(let r of Fy(rS(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 r6(e,t,n){let r=new Set([...tC(e,t).keys()].flatMap(e=>_C(e,n)));return Array.from(r).sort()}function i6(e){return e===null?null:e.config}const a6=[`vars`,`segments`,`config`];function o6(e){return typeof e==`string`&&a6.includes(e)}const s6=e=>({resp:e,exitAfterFlush:null,delivered:y3}),c6=e=>({kind:`reply`,...e}),l6={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},u6=(e,t)=>c6(s6({ok:!1,error:t,code:e,daemonV:3}));function d6(e){let t=f$(e.sessionId);if(!t.ok)return u6(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return u6(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Vb.join(`, `)}): it predates the lane toggles — update it`);let n=Yb(e.lane);return n===null?u6(`BAD_REQUEST`,`subscribe needs a lane, one of ${Vb.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function f6(e,t,n,r,i){return!t||typeof t!=`object`||typeof t.v!=`number`?u6(`BAD_REQUEST`,`malformed request`):t.v===3?t.kind===`subscribe`?d6(t):typeof t.kind!=`string`||!Object.hasOwn(l6,t.kind)?u6(`BAD_REQUEST`,`unknown kind`):c6(await p6(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:y3})}async function p6(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:w,doctorStores:ee}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:y3};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return s6(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 s6({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:m6(e),fileEvents:d.stats(),runs:f.stats(),transcriptReads:po(),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(LA(new Date(o.now()))),bundle:S,sourceDigest:w,daemon:y.serving(),doctorStores:qZ(ee)})});if(t.kind===`render`){let c=new Date(o.now()),l=LA(c),u=o.monotonic(),d=Math.round(u-r),f=[],p=++a.requestsTotal,m=q3(t,a,e.log,e.home),h=(t,n)=>x.see(t.sessionId,{client:t.hints.client??null,termCols:t.hints.termCols??null,rateLimits:t.rateLimits,claudeConfigDir:wo(t.hints.claudeConfigDir,e.home),projectDir:t.requested.projectDir,transcript:$ee(t.hookData),frame:n},l,p);m.ok&&(h(m.req,`drawing`),s.note(m.req.sessionId,m.req,p));let _=m.ok?await M3(e,m.req,l,u+Kn(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&&qs(g,m.req.sessionId,n)}}),e=>(h(m.req,`failed`),{outcome:{kind:`threw`,error:e},resp:b3(e),delivered:y3})):C6(m.problems);_.outcome.kind!==`ok`&&a.requestsErrored++,h3(f,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:v,line:y}=v3(`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 v6(e,t,s,()=>n()||i());h3(s,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`});let{level:l,line:u}=v3(`click`,s,c,Math.round(o.monotonic()-a));return e.log(l,u),s6(x6(c))}if(t.kind===`debug`){if(!o6(t.what))return s6({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${a6.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`?_6(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??Ox(`colorCompatibility`)):g6};return s6({ok:!0,debug:J3(t.what,n)})}throw Error(`no reply for request ${C(t)}`)}function m6(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 h6={endcaps:Ox(`endcaps`),colorCompatibility:Ox(`colorCompatibility`),wrap:Ox(`autoWrap`),padding:Ox(`padding`),width:1/0},g6=new Map;function _6(e,t){let n=new Map;for(let[r,i]of e)n.set(r,GP(i,{...h6,colorCompatibility:t}));return n}async function v6(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 b6(e,i,a,{via:`link`,handler:kn(t.clientVersion)},n,r)}catch(e){return e instanceof Z?{kind:`bad-request`,problems:[e.message]}:e instanceof XK?{kind:`closing`,error:e}:e instanceof ZK?{kind:`abandoned`,error:e}:{kind:`threw`,error:e}}}const y6={link:`verb`,"tmux-status":`linkVerb`};async function b6(e,t,n,r,i,a){let{menuIdle:o,verbCtx:s}=e;if(t===`tmux-status-click`)return h3(i,{verb:t}),S6(e,n,i,a);let c=M1.get(t);if(!c)return{kind:`bad-request`,problems:[`unknown click verb: ${t}`]};h3(i,{[y6[r.via]]:t});let l=C1(t,n),u=l?.ok?l.id:null;l===null?h3(i,{sid:`-`}):u!==null&&(h3(i,{sid:u}),o.clickArrived(u));try{await c(n,{...s,arrival:r,placeWaited:e=>h3(i,{placeWait:`${e}ms`}),gatherTook:e=>h3(i,{gather:`${e}ms`}),turnWaited:e=>h3(i,{turnWait:`${e}ms`}),clientGone:a})}finally{u!==null&&o.clickSettled(u)}return{kind:`ok`}}function x6(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 b3(e.error)}}async function S6(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(h3(r,{link:s.url}),s.url.startsWith(`cc-candybar://`)){let t=QK(()=>ss(s.url));return t.verb===`tmux-status-click`?o(`a status-line link names another status-line click`):b6(e,t.verb,t.value,{via:`tmux-status`},r,i)}return await y$(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,g$,e.tmp),{kind:`ok`}}const C6=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:y3});function w6(e,t){let n=oe(`sha256`).update(t).digest(`hex`).slice(0,16);return E.join(e,`update-act`,n)}const T6={kind:`idle`};function E6(e){if(e===null)return T6;let{act:t,record:n,alive:r,end:i,lastLine:a}=e;if(r)return{kind:`running`,act:t};if(i===null)return{kind:`failed`,act:t,identity:n.identity,reason:`lost: the act ended without a verdict`};if(i.kind===`exit`&&i.code===0)return{kind:`succeeded`,act:t};let o=i.kind===`timeout`?`timeout`:`non-zero (exit ${i.code}): ${a??`no output`}`;return{kind:`failed`,act:t,identity:n.identity,reason:o}}const D6=e=>({stdout:E.join(e,`stdout`),stderr:E.join(e,`stderr`),status:E.join(e,`status`)}),O6=e=>E.join(e,`record.json`);function k6(e){let t;try{t=l.readdirSync(e)}catch(e){if(e.code===`ENOENT`)return[];throw e}return t.filter(e=>/^\d+$/.test(e)).map(Number).sort((e,t)=>e-t)}function A6(e){let t=xo(e,4096);switch(t.kind){case`absent`:return null;case`failed`:throw Error(`${e}: ${t.reason}`);case`ok`:return t.value.buf.toString(`utf8`).split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1)??null}}function j6(e,t){let n=E.join(e,`.removed-${t}-${process.pid}`);try{l.renameSync(E.join(e,String(t)),n)}catch(e){if(e.code===`ENOENT`)return;throw e}l.rmSync(n,{recursive:!0,force:!0})}const M6=e=>e.now()-o.uptime()*1e3;async function N6(e,t,n){if(e.started<=n||!lt(e.pid))return!1;let r=await t(e.pid);return e.startTime===null||r.kind===`unavailable`||r.token===e.startTime}function P6(e){try{return JSON.parse(l.readFileSync(O6(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}const F6=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function I6(e,t,n){let r=null;async function i(i){let a=E.join(e,String(i)),o=P6(a);if(o===null)return null;if((r===null||!F6(r.record,o))&&(r={record:o,ours:await N6(o,t,M6(n)),final:null}),r.final!==null)return r.final;r.ours=r.ours&<(o.pid);let s=D6(a),c=st(s.status),u=c===null?null:A6(s.stderr)??A6(s.stdout);if(!l.existsSync(a))return null;let d={act:i,record:o,alive:r.ours,end:c,lastLine:u};return d.alive||(r.final=d),d}return{async read(){let t=null;for(;;){let n=k6(e).at(-1);if(n===void 0)return null;if(n===t)throw Error(`${E.join(e,String(n))}: an act with no record`);let r=await i(n);if(r!==null)return r;t=n}}}}function L6(e,t,n){l.mkdirSync(e,{recursive:!0});let r=l.mkdtempSync(E.join(e,`.claim-`));try{return l.writeFileSync(O6(r),JSON.stringify(n)),l.renameSync(r,t),!0}catch(e){let t=e.code;if(t===`ENOTEMPTY`||t===`EEXIST`)return!1;throw e}finally{l.rmSync(r,{recursive:!0,force:!0})}}async function R6(e,t,n,r,i,a,o,s){let c=(n??0)+1,l=E.join(t,String(c)),u=e.launchJobSync(i,D6(l));if(!u.ok)throw Error(`apply-update: ${u.error}`);let d=!1;try{let e=await s(u.pid);if(!L6(t,l,{identity:r,pid:u.pid,startTime:e.kind===`start`?e.token:null,started:o,deadline:o+a}))return z6;if(k6(t).some(e=>e>c))return j6(t,c),z6;d=!0}finally{d?u.release():u.withdraw()}for(let e of k6(t).filter(e=>e<c))j6(t,e);return{ok:!0,act:c}}const z6={ok:!1,reason:`another act claimed this bundle first`};function B6(e,t,n){let r=D6(E.join(e,String(t.act))).status;return dt(t.record.pid,r,{kind:`timeout`},n)}var V6=class{waiting=new Map;run(e,t){return new Promise((n,r)=>{let i=async()=>{try{n(await t())}catch(e){r(e)}},a=this.waiting.get(e);if(a!==void 0){a.push(i);return}let o=[];this.waiting.set(e,o);let s=t=>void t().then(()=>{let t=o.shift();t===void 0?this.waiting.delete(e):s(t)});s(i)})}};function H6(e){return e.kind===`source`?e.newer.digest:Po(e.newer)}const U6=e=>`${e.version} [${Ft(e.digest)}]`;function W6(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:U6(e.newer),running:U6(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:Po(e.newer),running:Po(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${Fo}@${Po(e.newer)}`,`install`]}}}}function G6(e,t,n){if(e===null)return[];let r=H6(e);if(!n.enabled||n.dismissed===r)return[];let i=W6(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
|
|
484
|
+
`),c=t.kind===`running`?iU(`[${i.busy}]`,null):iU(`[${i.act}]`,ea([{verb:Bi,args:[n.sessionId]}])),l=[iU(a,null),c,iU(`[dismiss]`,ea([{verb:Si,args:[n.sessionId,bz,r]}])),iU(`[disable]`,ea([{verb:Oi,args:[n.sessionId,xz,`false`]},{verb:Si,args:[n.sessionId,Sz,`false`]}]))],u=o.map(e=>[iU(e,null)]);return[{severity:tU,about:`update\0${r}`,message:s,copy:s,lines:[l,...u]}]}function K6(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function q6(e){switch(e.kind){case`current`:return[`info`,`build: current ${U6(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${U6(e.source)}, running ${U6(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function J6(e){switch(e.kind){case`current`:return[`info`,`release: current ${Po(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${Po(e.latest)}, running ${Po(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${Po(e.installed)}, latest ${Po(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function Y6(e){let{clock:t,launcher:n,entryUrl:r,digest:i,actsDir:a,intervalMs:o,releaseIntervalMs:s,registryUrl:c,fetchImpl:l,gates:u,onApplied:d,log:f}=e,p={kind:`unchecked`,reason:`not sampled yet`},m=null,h=async e=>{let t=await vs(e,n.launch);if(C)throw new XK(`apply-update`);return t},g=I6(a,h,t),_=null,v=null,y=Ne(f),b=Ne(f),x=new V6,S=e=>x.run(`acts`,e),C=!1,w=[],ee=(e,n)=>{w.push(t.every(n,e,{unref:!0}))},T=()=>C?null:K6(p,m);function te(){let e=T(),t=e===null?null:H6(e);(v===null?null:v.identity)!==t&&(v?.dispose(),v=t===null?null:{identity:t,dispose:u.state.register(bz,[t])})}function E(){p=Vt(r,()=>Rt(i)),y(q6(p)),te()}async function ne(){m=Lo(It,await Io(Fo,l,c,t)),b(J6(m)),te()}let D=null,re=Ne(f);async function ie(e){try{let t=await e();return D=null,{ok:!0,value:t}}catch(e){return e instanceof XK?{ok:!1,error:e.message}:(D=`update act files (${a}): ${e.message}`,re([`error`,D]),{ok:!1,error:D})}}function O(e){if(!e?.alive||t.now()<=e.record.deadline)return;let{stands:n,signalled:r}=B6(a,e,t),i=n?`timed out`:`outlived its verdict`,o=r?`ending it`:`its group took no signal`;f(`error`,`apply-update: act ${e.act} ${i}; ${o}`)}async function ae(){let e=await ie(async()=>{let e=await g.read();return C||O(e),e});if(C||!e.ok)return;let t=E6(e.value);_===null&&t.kind===`running`&&f(`info`,`apply-update: act ${t.act} is running; watching it`),_?.kind===`running`&&t.kind!==`running`&&(t.kind===`succeeded`&&(f(`info`,`apply-update: act ${t.act} succeeded`),E(),d()),t.kind===`failed`&&f(`error`,`apply-update: act ${t.act} failed: ${t.reason}`)),_=t}let oe;async function se(){await S(ae),!C&&(oe=t.after(2e3,()=>void se(),{unref:!0}))}return{arm(){E(),ee(E,o),w.push(()=>oe?.()),se(),p.kind===`not-source-checkout`&&(ne(),ee(()=>void ne(),s))},close(){C=!0,te(),w.forEach(e=>e())},notice:e=>G6(T(),_??T6,e),running:()=>S(async()=>{let e=await ie(()=>g.read());return e.ok&&E6(e.value).kind===`running`}),error:()=>D,act:()=>S(async()=>{if(C)throw new XK(`apply-update`);let e=await ie(()=>g.read());if(C)throw new XK(`apply-update`);if(!e.ok)throw new Z(`apply-update: ${e.error}`);let r=T();if(r===null)throw new Z(`apply-update: nothing newer is known to apply`);let i=W6(r),o=e.value;if(E6(o).kind===`running`)throw new Z(`apply-update: already ${i.busy}`);let s=await R6(n,a,o===null?null:o.act,H6(r),{...i.command,category:`update.apply`},6e5,t.now(),h);if(!s.ok)throw new Z(`apply-update: ${s.reason}`);f(`info`,`apply-update: act ${s.act}: ${i.act} — ${i.command.bin} ${i.command.args?.join(` `)??``}`),_={kind:`running`,act:s.act}})}}function X6(e,t){try{return F(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?I:L(e.message)}}function Z6(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function Q6(e){let{targets:t,intervalMs:n,stat:r,held:i,exit:a,log:o,clock:s}=e,c=Ne(o),l=t.map(e=>({path:e,stamp:X6(e,r)})),u=l.filter(({stamp:e})=>e.kind!==`failed`),d=null,f=!1,p=()=>{f=!0,d?.()},m=async()=>{if(!f)for(let{path:e,stamp:t}of u){let n=X6(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!Z6(t,n)){let t=`binary ${n.kind===`absent`?`gone`:`changed`} (${e})`,r=await i();if(f)return;if(r){c([`info`,`${t}; the restart waits for the running update`]);return}o(`info`,`${t}; shutting down`),p(),a();return}}},h=()=>m().catch(e=>{o(`error`,`binary check failed: ${e.message}`)});return{arm(){for(let{path:e,stamp:t}of l)t.kind===`failed`&&o(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);d=s.every(n,()=>void h(),{unref:!0})},checkNow:h,close:p}}function $6(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var e8=class{stop=null;state=`released`;last=null;constructor(e,t){this.tick=e,this.clock=t}landed(e,t=this.clock.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.clock.now());this.stop=this.clock.after(e,()=>{this.stop=null,this.tick()},{unref:!0})}cancel(){this.stop?.(),this.stop=null}};const t8=`pass`,n8={okMs:5*6e4,failedMs:45e3};function r8(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function i8(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function a8(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function o8(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:E.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>vc(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${yc(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,MY(e,`unread`)}function l8(e,t){return e.missed&&e.reading.get().kind===`pending`&&jY(e,t.size>0?L([...t].join(`; `)):I),`unkeyed`}function u8(e,t){let n=FY(e);return t===null||n.kind!==`ok`?n:F({...n.value,pullRequest:FY(t)})}const d8=L(`git cache closed`);function f8(e){return t=>L(`${e} threw: ${String(t)}`)}var p8=class{repos=new Map;resolutions=new Map;closed=!1;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;watchers;ownsWatchers;logger;clock;constructor(e){this.inner=e.inner,this.clock=e.clock,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Pe;let t=e.ledger??new dj(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 jC({clock:this.clock,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=this.clock.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=L(`resolver threw: ${String(e)}`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`settled`)return RY(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>u8(a,o)}}asked(e,t,n,r){if(this.closed)return{kind:`settled`,outcome:d8};let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`settled`,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 lj,watch:this.followWatch(e,null).watch,period:new e8(()=>{n.refresh.share(t8,()=>this.refreshPass(n))},this.clock),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=o8(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(t8,()=>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(t8,()=>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:kY(),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=a8(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(i8(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=this.clock.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(f8(`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,jY(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of $J(n.value))c.add(e)});let l=s8(o),u=a===null||i.length===0?`-`:l===void 0?l8(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}`,r8(n),c.size===0?F(null):L([...c].join(`; `)),this.clock.now()-t)}prSource(e){let t={period:new e8(()=>{this.readPr(e,t,`period`)},this.clock),seen:new Map,holders:0,missed:!0,key:``,remote:I,reading:kY(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(f8(`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`):(MY(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,jY(t,a.outcome),t.period.landed($6(n8,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=this.clock.now(),o=(i.kind===`ok`?this.inner.resolvePullRequest(e.root,i.value).catch(f8(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:I)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${R(r)}`,n,i,this.clock.now()-a);let o=this.clock.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||(jY(t,i),t.period.landed($6(n8,i),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=L(`git state dropped: ${e.root}`);for(let n of e.values.values())NY(n,t);e.pr!==null&&NY(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(){this.closed=!0;for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},m8=class{static usageDir(e){return E.join(e,`usage`)}static locksDir(e){return E.join(e,`locks`)}static isLocked(e,t){let n=E.join(this.locksDir(e),t);if(!l.existsSync(n))return!1;try{let e=l.readFileSync(n,`utf-8`),r=parseInt(e.trim(),10);if(isNaN(r))return k(`Invalid PID in lock file ${t}, removing stale lock`),l.unlinkSync(n),!1;try{return process.kill(r,0),!0}catch(e){return e.code===`ESRCH`?(k(`Removing stale lock file ${t} for dead process ${r}`),l.unlinkSync(n),!1):(k(`Error checking process ${r} for lock ${t}:`,e),!0)}}catch(e){return k(`Error reading lock file ${t}:`,e),!0}}static async acquireLock(e,t,n,r=5e3){await this.ensureCacheDirectories(e);let i=E.join(this.locksDir(e),n),a=t.now(),o=String(process.pid);for(;t.now()-a<r;)try{return await l.promises.writeFile(i,o,{flag:`wx`}),k(`Lock acquired for ${n}`),!0}catch(e){if(e.code===`EEXIST`)await A(t,50);else throw e}return k(`Failed to acquire lock for ${n} within ${r}ms`),!1}static async releaseLock(e,t){let n=E.join(this.locksDir(e),t);try{await l.promises.unlink(n),k(`Lock released for ${t}`)}catch(e){e.code!==`ENOENT`&&k(`Error releasing lock for ${t}:`,e)}}static async ensureCacheDirectories(e){try{await Promise.all([l.promises.mkdir(e,{recursive:!0}),l.promises.mkdir(this.usageDir(e),{recursive:!0}),l.promises.mkdir(this.locksDir(e),{recursive:!0})])}catch(e){k(`Failed to create cache directories:`,e)}}static createProjectHash(e){return oe(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t,n,r){await this.ensureCacheDirectories(e);let i=E.join(this.usageDir(e),`${n}.json`),a=`${n}.usage.lock`;for(let o=0;o<3;o++){if(this.isLocked(e,a)){k(`Cache for ${n} is locked, waiting...`),await A(t,75);continue}try{let e=await l.promises.readFile(i,`utf-8`),t=JSON.parse(e);return!r||t.timestamp>=r?(k(`[CACHE-HIT] ${n} disk cache: found`),this.deserializeDates(t.data)):(k(`${n} cache outdated: cache=${t.timestamp}, latest=${r}`),null)}catch(e){if(e.code===`ENOENT`)return k(`No shared ${n} usage cache found`),null;k(`Attempt ${o+1} failed to read ${n} cache: ${e.message}. Retrying...`),await A(t,75)}}return k(`Failed to read ${n} 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,r,i){let a=`${n}.usage.lock`;if(!await this.acquireLock(e,t,a)){k(`Could not acquire lock to set usage cache for ${n}`);return}try{await this.ensureCacheDirectories(e);let a=E.join(this.usageDir(e),`${n}.json`),o={data:r,timestamp:i||t.now()},s=JSON.stringify(o);await l.promises.writeFile(a,s,`utf-8`),k(`[CACHE-SET] ${n} disk cache stored`)}catch(e){k(`Failed to save ${n} usage cache:`,e)}finally{await this.releaseLock(e,a)}}};const h8={"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 g8=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(e,t){let n=t.now()-1440*60*1e3;return await m8.getUsageCache(e,t,`pricing`,n)}static async saveDiskCache(e,t,n){await m8.setUsageCache(e,t,`pricing`,n)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=_e({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.setEncoding(`utf8`),t.on(`data`,t=>{if(i+=Buffer.byteLength(t),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(e,t){if(this.executionCache!==null)return k(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let n=await this.loadDiskCache(e,t);if(n)return k(`[CACHE-HIT] Pricing disk cache: ${Object.keys(n).length} models`),this.executionCache=n,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(n).length} models`),n;let r=await this.fetchPricingData();return r?(await this.saveDiskCache(e,t,r),k(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(r).length} models`),this.executionCache=r,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(r).length} models`),r):(k(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(h8).length} models`),this.executionCache=h8,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(h8).length} models`),h8)}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,t,n){if(this.modelPricingCache.has(e))return k(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let r=await this.getCurrentPricing(t,n),i;return i=r[e]?r[e]:this.fuzzyMatchModel(e,r),this.modelPricingCache.set(e,i),k(`[CACHE-SET] Model pricing cache: ${e}`),i}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,t,n){let r=e.message?.usage;if(!r)return 0;let i=this.extractModelId(e),a=await this.getModelPricing(i,t,n),o=r.input_tokens||0,s=r.output_tokens||0,c=r.cache_creation_input_tokens||0,l=r.cache_read_input_tokens||0,u=o/1e6*a.input,d=s/1e6*a.output,f=l/1e6*a.cache_read,p=c/1e6*a.cache_write_5m;return u+d+p+f}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`}},_8=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}},v8=class{entries=new Map;refreshes;closed=!1;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){if(this.closed)return RY(L(`${this.spec.name} closed`));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:()=>FY(r)}}supersede(e){if(this.closed)return()=>{};let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,MY(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(){this.closed=!0;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:kY(),holders:0,flight:null,changed:!1,superseding:0,revisit:y8(this.spec.every,this.spec.clock,{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=this.spec.clock.now();x8(()=>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,this.spec.clock.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{jY(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(),NY(e,L(`${this.spec.name} entry dropped`))}};function y8(e,t,n){if(e===null)return new b8(n.holdReturned);let r=new e8(n.period,t);return{landed:t=>r.landed($6(e,t)),hold:e=>r.hold(e),dispose:()=>r.dispose()}}var b8=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 x8(e){let t=e=>L(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function S8(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 C8={okMs:60*1e3,failedMs:10*1e3},w8={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},T8={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function E8(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function D8(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-1),t.getTime()}function O8(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const k8={entries:0,cost:0,breakdown:O8(),days:new Map};async function A8(e,t,n,r){let i=E8(new Date(D8(r.now()))),a=e.entries,o=e.cost,s={...e.breakdown},c=new Map;for(let[t,n]of e.days)t>=i&&c.set(t,{...n});for(let e of t){let t=e.message?.usage;if(!t)continue;a++;let l=e.costUSD??await g8.calculateCostForEntry(e.raw,n,r);o+=l,s.input+=t.input_tokens||0,s.output+=t.output_tokens||0,s.cacheCreation+=t.cache_creation_input_tokens||0,s.cacheRead+=t.cache_read_input_tokens||0;let u=E8(new Date(e.timestamp));if(u<i)continue;let d=c.get(u)??{...w8};d.cost+=l,d.input+=t.input_tokens||0,d.output+=t.output_tokens||0,d.cacheCreation+=t.cache_creation_input_tokens||0,d.cacheRead+=t.cache_read_input_tokens||0,c.set(u,d)}return{entries:a,cost:o,breakdown:s,days:c}}function j8(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function M8(e){let t=0,n=0,r=O8(),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)??{...w8};j8(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:T8,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 N8(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function P8(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!N8(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...w8};j8(r,t),n.set(e,r)}return n}async function F8(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 I8(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function L8(e,t){(0,Y.runInAction)(()=>e.set(t))}var R8=class{sessions=Y.observable.map(void 0,{deep:!1});flight=new _8;scans;daySets=new Map;speedFlight=new _8;requestFlight=new _8;staleAgeMs;host;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;stopSweep=null;closed=!1;clock;constructor(e){this.host=e.host,this.clock=e.clock,this.log=e.logger??Pe,this.ledger=e.ledger??new dj(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new v8({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${R(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??C8,maxEntries:8,logger:this.log,ledger:this.ledger,clock:this.clock});let t=e.sweepIntervalMs??3e5;t>0&&(this.stopSweep=this.clock.every(t,()=>this.sweepStale(),{unref:!0}))}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=ao(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async e=>{let t=await r().record;return t.kind===`failed`?t:F(I8(t.kind===`ok`?t.value.sessionInfo:T8,e))},speed:t=>this.observed(e,r,t),today:async e=>{await zY(e),await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return no;let r=n.failure.get();return r===null?F(I8(n.record?.sessionInfo??T8,t)):L(r)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=this.clock.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=${R(e)}`,`request`,a,this.clock.now()-i),L8(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){if(this.closed)return RY(L(`usage store closed`));let n=LX(t,this.host.home),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?F({roots:i.roots,sums:i.sums.read()}):e}}}todayAt(e,t,n){let r=this.sessions.get(t?.session_id??``),i=r?.failure.get()??null;if(i!==null)return L(i);let a=E8(RA(n)),o={...w8},s=e.sums.get(a);s!==void 0&&j8(o,s);let c=N8(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&j8(o,c),s===void 0&&c===void 0?I:F({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:a})}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return I;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return L8(this.hold(e).speed,t),t;let r=S8(t.kind===`ok`?t.value.sessionInfo.tokenBreakdown:null,n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=F({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return L8(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??no:I}async ingest(e,t,n,r){if(!e)return I;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,F(i);if(!t)return i?F(i):I;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,sessionInfo:s.value.sessionInfo,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),F(c)):l===void 0?F(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,Y.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=this.clock.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:this.clock.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=>ie(e,`projects`)+O),i={roots:r,sums:new UC(`today over ${e.join(`,`)}`,()=>P8(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await BX(e,D(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of YX(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 XX(e,r,k8,(e,t)=>A8(e,t,j(this.host),this.clock));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 YX(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...M8(i),mainStamp:a})}async scan(e){try{let t=D8(this.clock.now()),n=await RX(e),r=[];for(let e of n){let n=await zX(lo(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=ie(e,i),a=await zX(uo(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:oo(a)})}}let i=[],a={hits:0,misses:0};return await F8(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=${R(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?L(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`):F({sessions:r.length,read:a.misses})}catch(e){return L(`usage scan: ${e instanceof Error?e.message:String(e)}`)}}sweepStale(){let e=this.clock.now(),t=E8(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.closed=!0,this.stopSweep?.(),this.stopSweep=null,this.scans.close(),(0,Y.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},z8=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)}})}},B8=class{sessions;constructor(e,t,n,r,i=Pe,a=256){this.empty=e,this.step=t,this.refreshes=n,this.clock=r,this.log=i,this.sessions=new z8(a)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=ao(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=this.clock.now(),o=await XX(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${R(e)}`,`request`,o,this.clock.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 YX(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??no}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function V8(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 H8=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new B8(void 0,V8,(e.ledger??new dj(t)).declare({name:`context`,scope:`session`,refresh:[`request`]}),e.clock,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?F(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,U8(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return F(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,U8(e))}contextFrom(e,t){if(e.kind===`failed`)return L(`context transcript: ${e.reason}`);let n=e.value;return n===void 0?(k(`No main chain entries with usage data found`),I):(k(`Most recent main chain context: ${n} tokens (limit: ${t})`),F({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function U8(e){return e.context_window?.context_window_size??2e5}const W8={messageCount:0,nonPrompts:0,recent:[]},G8=new Set([`turn`,`interrupt`,`claude-code`]);function K8(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!G8.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function q8(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 J8=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new B8(W8,K8,(e.ledger??new dj(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getMetricsInfo(e,t){k(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?Y8(e,n,await this.fold.read(e,t.transcript_path)):I}metricsOf(e,t){let n=t.cost;if(!n)return I;let r=this.fold.answer(e);return r.kind===`pending`?r:Y8(e,n,r)}};function Y8(e,t,n){return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`):F({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:q8(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 X8={command:null,todos:[],pending:[],done:[]};function Z8(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 Q8(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 $8(e,t){if(t.isSidechain)return e;let n=Q8(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=Z8(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 e5(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>Z8(e,t.name),[]),done:e.done}}var t5=class{fold;constructor(e){let t=e.logger??Pe;this.fold=new B8(X8,$8,(e.ledger??new dj(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getActivityInfo(e,t){return n5(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:n5(e,t)}};function n5(e,t){return t.kind===`failed`?L(`activity (${e}): ${t.reason}`):F(e5(t.value))}const r5=3e4;var i5=class{names;constructor(e){let t=e.logger??Pe;this.names=new v8({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${R(e.pane)} socket=${R(e.socket)}`,read:t=>a5(e.launcher,t),every:{okMs:r5,failedMs:r5},maxEntries:64,logger:t,ledger:e.ledger??new dj(t),clock:e.clock})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function a5(e,t){let n=await Ws(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return L(n.reason);let r=n.stdout.trim();return r?F(r):I}const o5=6e4,s5={okMs:o5,failedMs:o5};function c5(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function l5(e,t){try{let e=t();return Promise.resolve(e===``?I:F(e))}catch(t){return Promise.resolve(L(`host.${e}: ${String(t)}`))}}var u5=class{name;user;constructor(e){let t=e.logger??Pe,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:s5,maxEntries:1,logger:t,ledger:e.ledger??new dj(t),clock:e.clock};this.name=new v8({...n,name:`host.name`,read:()=>l5(`name`,()=>c5(o.hostname()))}),this.user=new v8({...n,name:`host.user`,read:()=>l5(`user`,()=>o.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()}},d5=class{known=new z8(64);refreshes;constructor(e,t=Pe,n=new dj(t)){this.clock=e,this.refreshes=n.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=f5(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=this.clock.now(),i=yI(e);return this.refreshes.recorded(`path=${R(e)} stamp=${R(t)}`,`request`,i,this.clock.now()-r),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??no}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}};function f5(e){try{let t=l.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:oo(t)}catch(e){return`unread:${e.code??`error`}`}}const p5=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function m5(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 h5=class{known=new z8(256);refreshes;constructor(e,t=Pe,n=new dj(t)){this.clock=e,this.refreshes=n.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=ao(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??no}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=this.clock.now(),i=await g5(t);return this.refreshes.recorded(`sid=${R(e)} stamp=${R(n)}`,`request`,i,this.clock.now()-r),i}};async function g5(e){let t=await _5(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function _5(e){for(let t of[65536,1048576]){let n=await bo(e,t);if(n.kind!==`ok`)return n;let r=v5(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function v5(e,t){let n=e.toString(`utf8`).split(`
|
|
485
|
+
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!p5.test(t))continue;let r=m5(t);if(r!=null)return r}return null}var y5=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:L(n)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,Y.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const b5=e=>qV(e),x5=e=>E.join(e.storage.folder,b5(e.sessionId)),S5=e=>JSON.stringify([e.folder,e.generation]),C5=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var w5=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;identityOf;fileEvents;clock;unsubscribe;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??hc,this.fileEvents=e.fileEvents,this.clock=e.clock,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new v8({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${R(x5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new dj(e.logger),clock:e.clock})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{l.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`||!gc(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${R(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(S5(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:${S5(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),stopSweep:this.clock.every(864e5,()=>void this.sweep(e),{unref:!0}),health:{kind:`watching`}};this.watched.set(S5(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=S5(e.key);this.watched.delete(t),e.health={kind:`closed`},e.stopSweep(),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>C5(e.storage,n);switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.has(E.join(n.folder,E.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(x5(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`&&gc(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${R(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>C5(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=${R(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>C5(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(S5(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=Dc(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 L(t);let n=x5(e),r;try{r=await l.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?I:L(`${n}: ${t.message}`)}if(r.trim()===``)return I;let i=cj(r);return i.kind===`failed`?L(`${n}: ${i.reason}`):i}async sweep(e){let t=this.clock.now(),n=t-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${R(e.folder)} scanned=${r} removed=${i} took=${this.clock.now()-t}ms`;try{let t=await l.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=E.join(e.folder,a.name);try{let{mtimeMs:r}=await l.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&b5(t.sessionId)===a.name);if(r>=n||o)continue;await l.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 T5(e){let{launcher:t,clock:n,logger:r,ledger:i}=e;return{home:e.host.home,hostService:new u5({clock:n,logger:r,ledger:i}),gitProvider:new p8({inner:new DY(t),watchers:e.watchers,clock:n,logger:r,ledger:i}),usageStore:new R8({host:e.host,clock:n,logger:r,ledger:i}),contextProvider:new H8({clock:n,logger:r,ledger:i}),metricsProvider:new J8({clock:n,logger:r,ledger:i}),activityProvider:new t5({clock:n,logger:r,ledger:i}),tmuxService:new i5({launcher:t,clock:n,logger:r,ledger:i}),autoCompact:new d5(n,r,i),cacheExpiry:new h5(n,r,i),managedStorage:new w5({watchers:e.watchers,fileEvents:e.fileEvents,clock:n,logger:r,ledger:i}),faults:new y5,log:e.logger,clock:n}}function*E5(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*D5(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);yield*Object.values(t.partials??{})}for(let t of mS(e.presets)){for(let n of Fy(_S(e,t).node))n.when!==void 0&&(yield n.when);let n=bS(e,t);for(let e of Qv){let t=n[e];$v(t)&&(yield t)}}for(let[,t]of E5(e))for(let[,e]of Wy(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of jS(t))yield e}function O5(e,t,n){let r=jW(t),i=new Set,a=new Set,o=new Set;for(let e of D5(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of aC(e,t.helpers))a.add(n);for(let n of dC(e,t.helpers))o.add(n)}for(let[,e]of E5(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 mS(t.presets))for(let n of Fy(_S(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=>!hi(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(E5(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 k5(e){return oe(`sha256`).update(JSON.stringify(e)).digest(`hex`)}var A5=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 j5(e){return Math.floor(Math.max(e/4,e*yr-67108864))}const M5={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function N5(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[KV(FS(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[FS(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>IS(e)(t)&&t!==KV(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${zN(e,`<default>`)}: projections=${[...FW(n).keys()].join(`,`)||`-`} instantSegments=${X4(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 P5=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},F5=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${P5(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function I5(e,t,n){let r=e=>R(e.join(`,`)||`-`);return`config loaded projectDir=${R(e.projectDir)} cwd=${R(e.cwd)} cause=${R(F5(t))} state=${n} files=${R(zN(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 L5(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function R5(e,t,n){return e+`\0`+t+`\0`+(n??``)}function z5(e,t){return new Set(mS(e.presets).filter(n=>_S(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function B5(e,t){let{loaded:n,dropped:r,unreached:i}=e.state.plugins,a=[...new Set([...e.state.plugins.roots,E.join(e.projectDir,EH)])];return wC({named:[...BH(t,e.projectDir,e.cwd,e.configFile),...a,...n.map(e=>e.path),...[...r,...i].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))],whole:a})}function V5(e){return e.filter(Boolean).join(`
|
|
486
|
+
`)||null}const H5=e=>e instanceof Error?e.message:String(e);function U5(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function W5(e){let{loaded:t,chain:n}=e;return k5({cwd:e.cwd,chain:{layers:n.layers,home:n.home,repo:n.repo,locs:n.locs},loaded:{layers:t.layers.map(e=>({path:e.path,raw:e.raw,config:e.config,plugins:U5(e.plugins),source:null,warnings:null})),base:t.base,installed:{...U5(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 G5(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 K5(e,t,n){let r=[];try{let i=AG(t.locs,t.layers,nK,{warned:e=>r.push(...e)},{repo:t.repo,cwd:e}),a={cwd:e,chain:t,loaded:i,sources:G5(i.config,n)};return{kind:`resolved`,...a,key:W5(a),warnings:r}}catch(e){return e instanceof ib&&r.push(...e.warnings),{kind:`failed`,cause:e,warnings:r}}}function q5(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??nK,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new $C(t.clock),m=new Aj(t.launcher,p,o.globals.default_empty_value??``,t.sessionState,null,t.ledger,t.fileEvents,t.watchers,t.env),h;try{h=W4(o,m,n,t.compile??U4(t.signer),Q5),f.push(...h.loadWarnings);let r=m.view();f.push(...q4(o,r,n,$5)),r.dispose(),t.gates.state.gateFor(o),t.gates.config.gateFor(o);for(let n of new Set(e.sources.values()))m.own(t.storage.watch(n))}catch(e){return m.dispose(),e instanceof ib&&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:eX(o),authoredRoots:z5(l,u),fileHeldSettings:NK(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>O5(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 J5(e,t,n,r,i){let a={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:Math.round(i.monotonic()-e.started)},o=t=>V5([...e.advisories,...n,...t]);switch(r.kind){case`built`:case`kept`:return{...a,kind:r.kind,warning:o(r.state.buildWarnings),state:r.state,error:null};case`failed`:return{...a,kind:`failed`,warning:o(r.warnings),state:null,error:H5(r.cause),cause:r.cause}}}function Y5(e,t,n,r,i=null){let a=K5(t,n,r.storage);if(a.kind===`failed`)return J5(e,n,[],a,r.clock);let o=i?.loadKey===a.key?{kind:`kept`,state:i}:q5(a,r);return J5(e,n,a.warnings,o,r.clock)}function X5(e,t,n,r,i=null){let a=r.clock.monotonic(),o=WH(r.locations,OU(r.stateDir).read(),e,t,n),{repos:s}=o,c={layers:o.kind===`chain`?o.layers:[],home:o.home,repo:s.plugins,locs:r.locations};return Y5({repos:s,advisories:[ZH(r.locations,e,t),YH(o),LH(s)],started:a},t,c,r,i)}function Z5(e,t,n){let r=K5(e,{layers:[],home:``,repo:t,locs:n.locations},n.storage),i=r.kind===`failed`?r:q5(r,n);if(i.kind===`failed`)throw Error(`bundled default failed to load: ${H5(i.cause)}`,{cause:i.cause});return i.state}const Q5=new Set([`directory`]),$5=new Set([`view`]);function e7(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new A5;q4(e.config,l,t,$5);let d=()=>uK(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)}`),dX(L(`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()});_4(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 t7=class{entries=new Map;answersWatch;stopSweep=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??{},l.mkdirSync(EU(e.stateDir),{recursive:!0});let{dir:n,name:r}=xC(DU(e.stateDir));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)??Y4(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=R5(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`,N5(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??Z5(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=${mr(this.accountedBytes())}/${mr(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=io();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(R5(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=e7(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.stopSweep===null&&(this.stopSweep=this.deps.clock.every(15e4,()=>this.releaseIdle(),{unref:!0}))}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.stopSweep!==null&&(this.stopSweep(),this.stopSweep=null)}close(){if(this.closed)return;this.closed=!0,this.stopSweep?.(),this.stopSweep=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 X5(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=${mr(this.accountedBytes())}/${mr(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`,L5(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`,N5(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=B5(e,this.deps.locations),{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 n7=e=>!aJ(e)&&!sI(e)&&e!==`update.dismissed`&&e!==yi;var r7=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:eJ(e,n7,(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 Z(`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 i7(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>dK(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return xX({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...PK(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 a7=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,o7=`#{session_id} #{client_control_mode} #{pane_id}`;function s7(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 c7(e,t){let n=new Set;for(let r of e.split(`
|
|
488
488
|
`)){let[e,i,a,o,s,c]=r.trim().split(` `);e===void 0||e===``||i===void 0||Number(a)>0&&(o===`1`||t.has(i))&&(s!==`1`||c===`1`)&&n.add(e)}return n}function l7(e,t){let n=new Map;for(let t of e.split(`
|
|
489
489
|
`)){let[e,r]=t.trim().split(` `);e!==void 0&&e!==``&&r!==void 0&&n.set(e,r)}let r=new Map;for(let e of t.split(`
|
|
490
|
-
`)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var u7=class{servers=new Map;loop={kind:`idle`};constructor(e){this.deps=e}follow(){switch(this.loop.kind){case`idle`:this.deps.log(`info`,`visibility following`),this.ask();break;case`asking`:this.loop.following=!0;break;case`due`:break}return()=>this.stop()}stop(){switch(this.loop.kind){case`due`:this.loop.clear(),this.end();return;case`asking`:this.loop.following=!1;return;case`idle`:return}}ask(){let e={kind:`asking`,following:!0};this.loop=e,Promise.resolve().then(()=>this.refresh(this.deps.sockets())).catch(e=>this.deps.log(`error`,`visibility refresh threw: ${C(e)}`)).then(()=>{if(e.following){this.loop={kind:`due`,clear:this.deps.clock.after(this.deps.intervalMs,()=>this.ask(),{unref:!0})};return}this.end()})}end(){this.deps.log(`info`,`visibility stopped forgot=${this.servers.size}`),this.loop={kind:`idle`},this.servers.clear()}shown(e){if(e==null)return!0;let t=this.servers.get(e.socket);return t?.kind!==`asked`||t.shown.has(e.pane)}async refresh(e){for(let t of this.servers.keys())e.has(t)||this.servers.delete(t);let t=await Promise.all([...e].map(async e=>{let[t,n]=await Promise.all([this.deps.listPanes(e),this.deps.listClients(e)]);return[e,t.kind===`ok`?n.kind===`ok`?{kind:`asked`,shown:c7(t.stdout,s7(n.stdout)),status:l7(t.stdout,n.stdout)}:{kind:`unasked`,reason:n.reason}:{kind:`unasked`,reason:t.reason}]})),n=new Set;for(let[e,r]of t){let t=this.servers.get(e);this.servers.set(e,r),!d7(t,r)&&(n.add(e),this.deps.log(r.kind===`asked`?`info`:`warn`,r.kind===`asked`?`visibility socket=${JSON.stringify(e)} shown=${[...r.shown].join(`,`)||`-`}`:`visibility socket=${JSON.stringify(e)} unasked: ${r.reason} — its panes count as shown`))}for(let[e,n]of t)n.kind===`asked`&&this.deps.onAnswer(e,n.status);n.size>0&&this.deps.onChange(n)}};function d7(e,t){return e===void 0||e.kind!==t.kind?!1:e.kind===`unasked`||t.kind===`unasked`?!0:e.shown.size===t.shown.size&&[...e.shown].every(e=>t.shown.has(e))}function f7(e){return`ccb`+oe(`sha256`).update(e).digest(`hex`).slice(0,12)}const p7=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function m7(e){if(e===void 0)return`terminal`;let t=H.parse(e);if(t.isDefault)return`terminal`;switch(t.type){case V.STANDARD:{let e=t.number===void 0?void 0:p7[t.number];if(e!==void 0)return e;break}case V.EIGHT_BIT:if(t.number!==void 0)return`colour${t.number}`;break;case V.TRUECOLOR:{let e=t.fixedValue;if(e!==void 0)return e.hex;break}case V.DEFAULT:case V.WINDOWS:break}throw Error(`frames: no tmux colour for ${t.name}`)}const h7={bold:`bold`,dim:`dim`,italic:`italics`,underline:`underscore`,strike:`strikethrough`,reverse:`reverse`,blink:`blink`,conceal:`hidden`,underline2:`double-underscore`,overline:`overline`,blink2:null,frame:null,encircle:null};function g7(e){return e.replaceAll(`#`,`##`)}function _7({fg:e,bg:t,attrs:n=[]}){let r=n.map(e=>{let t=h7[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${m7(e)}`,`bg=${m7(t)}`,...r].join(`,`)}]`}function v7(e){let t={},n=e=>{let n=_7(e)+g7(e.text);if(e.link===void 0)return n;let r=f7(e.link);return t[r]=e.link,`#[range=user|${r}]${n}#[norange]`};return{rows:e.rows.map(e=>OP(e).map(n).join(``)),links:t}}function y7(e){return _P(v7,e)}const b7=Bb.tmuxStatus.rows,x7=`@cc-candybar-status-prior`,S7=`@cc-candybar-status-wrote`,C7=`@cc-candybar-binding-prior`,w7=[`-T`,`root`,`MouseDown1Status`],T7=Array.from({length:b7},(e,t)=>t),E7=e=>`@cc-candybar-row-${e}`,
|
|
491
|
-
`).map(e=>e.split(` `)[0]??``),a={};for(let e of T7)i.includes(D7(e))&&(a[e]=r[e]??``);let o=i.includes(`status-format`)||Object.keys(a).length>0;return{status:i.includes(`status`)?n:null,formats:o?a:null}}function z7(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,D7(Number(t)),k7(n)])]}const
|
|
492
|
-
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=B7(i,a,this.deps.owner);o.kind===`ours`?t.layouts.set(n,{prior:o.prior,rows:[],status:o.status}):this.leave(e,t,n,o.why)}let r=(await this.ask(e,[I7(`@cc-candybar-binding-prior`)]))?.[0]??``;if(r!==``)try{let e=JSON.parse(r);e.owner===this.deps.owner&&(t.binding={kind:`adopted`,prior:e.prior})}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${C7} does not read (${String(t)}), left as it is`)}(t.layouts.size>0||t.binding.kind===`adopted`)&&this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)||`-`} binding=${t.binding.kind}`)}leave(e,t,n,r){t.left.set(n,r),this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} session ${n} left as it is: ${r}`)}async install(e,t,n){let r=await this.ask(e,Nte(n));if(r===null||this.closed)return null;let i=Pte(n,r,this.deps.owner);if(i.kind===`theirs`)return this.leave(e,t,n,i.why),null;let a={prior:i.prior,rows:[],status:i.kind===`ours`?i.status:i.prior.base};return t.layouts.set(n,a),i.kind===`lay-out`&&await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} session ${n} base=${i.prior.base} own=${[i.prior.status===null?[]:[`status`],i.prior.formats===null?[]:[`status-format`]].flat().join(`,`)||`-`}`),a}async draw(e,t,n,r){let i=n.prior.base+r.length,a=[];if(r.forEach((e,r)=>{n.rows[r]!==e&&a.push([`set-option`,`-t`,t,E7(r),e])}),i!==n.status){let e=Ate(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,S7,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,Mte(a)]]))&&(n.rows=r,n.status=i)}async restore(e,t,n){let r=t.layouts.get(n);if(r===void 0)return;t.layouts.delete(n);let i=await this.ask(e,V7(n));if(i===null)return;let a=H7(n,r.prior,i);await this.write(e,a.commands),this.saidRestored(e,n,a.kept)}saidRestored(e,t,n){this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} restored session ${t} kept=${n.join(`,`)||`-`}`)}async installBinding(e,t){let n=t.binding;if(n.kind===`ours`||n.kind===`left`)return;let r=await this.ask(e,U7);if(r===null||this.closed)return;let i=W7(r[0]??``);if(n.kind===`none`&&K7(i)){t.binding={kind:`left`,why:`another cc-candybar daemon's status-line clicks are bound to MouseDown1Status; left as it is, so this daemon's are off`},this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.binding.why}`);return}let a=n.kind===`adopted`&&K7(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...w7,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${j7(`${this.deps.handler} ${Ite(e)}`)}`,...a===null?[]:[a.command]],[`set-option`,`-g`,`@cc-candybar-binding-prior`,JSON.stringify(o)]])){t.binding=n;return}this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} bound MouseDown1Status (was ${a===null?`unbound`:JSON.stringify(a.line)})`)}async restoreBinding(e,t){let n=t.binding;if(t.binding={kind:`none`},n.kind!==`ours`&&n.kind!==`adopted`)return;let r=await this.ask(e,U7);if(r===null)return;let i=q7(n.prior,r[0]??``);for(let t of i.steps)await this.write(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.said}`)}writeBindingRestoreSync(e,t,n,r){let i=q7(n,r);for(let n of i.steps)this.writeSync(e,t,[n.command],n.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(t)} ${i.said}`)}counted(e,t){let n=this.serverOf(e);return t.kind===`ok`?(n.lastFailure=null,t):(this.failedWrites++,n.lastFailure!==t.reason&&this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.reason}`),n.lastFailure=t.reason,t)}async run(e,t,n){return this.counted(e,await this.deps.edge.run(e,t,n))}async ask(e,t){let n=await this.run(e,N7(t));return n.kind===`ok`?P7(n.stdout,t.length):null}askSync(e,t,n){let r=this.counted(t,e(t,N7(n)));return r.kind===`ok`?P7(r.stdout,n.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,A7(t),n)).kind===`ok`)}writeSync(e,t,n,r){n.length!==0&&(this.writes++,this.counted(t,e(t,A7(n),r)))}};function Rte(e){try{return Qi(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),J7=e=>({arity:e,keep:!1}),zte={"--add-dir":$(`variadic`),"--agent":$(`one`),"--agents":$(`one`),"--allow-dangerously-skip-permissions":$(`none`),"--allowedTools":$(`variadic`),"--allowed-tools":$(`variadic`),"--append-system-prompt":$(`one`),"--autocompact":$(`one`),"--ax-screen-reader":$(`none`),"--bg":J7(`none`),"--background":J7(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":J7(`optional`),"-c":J7(`none`),"--continue":J7(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":J7(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":J7(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":J7(`none`),"--forward-subagent-text":$(`none`),"--from-pr":J7(`optional`),"-h":J7(`none`),"--help":J7(`none`),"--ide":$(`none`),"--include-hook-events":$(`none`),"--include-partial-messages":$(`none`),"--input-format":$(`one`),"--json-schema":$(`one`),"--max-budget-usd":$(`one`),"--mcp-config":$(`variadic`),"--model":$(`one`),"-n":$(`one`),"--name":$(`one`),"--no-chrome":$(`none`),"--no-session-persistence":$(`none`),"--output-format":$(`one`),"--permission-mode":$(`one`),"--permission-prompts":$(`one`),"--plugin-dir":$(`one`),"--plugin-url":$(`one`),"-p":J7(`none`),"--print":J7(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":J7(`optional`),"--resume":J7(`optional`),"--safe-mode":$(`none`),"--session-id":J7(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":J7(`optional`),"--tmux":J7(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":J7(`none`),"--version":J7(`none`),"-w":J7(`optional`),"--worktree":J7(`optional`)},Bte={resume:`--resume`,fresh:`--session-id`};function Vte(e){return[Bte[e.kind],e.sessionId]}const Y7=e=>e.startsWith(`-`)&&e!==`-`;function X7(e,t){let n=Z7(t);return n===null?{dir:e??t,args:[]}:e!==null&&Hte(e,n.top)?{dir:e,args:[]}:{dir:e===null||Z7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const Hte=(e,t)=>e===t||e.startsWith(t+E.sep);function Ute(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!Y7(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=zte[a];if(o===void 0)return{kind:`refused`,reason:`Claude Code was started with ${a}, which cc-candybar does not know how to carry to a restart`};let s=i===-1?o.arity===`one`?n.slice(r,r+1):o.arity===`optional`?n.slice(r,r+1).filter(e=>!Y7(e)):o.arity===`variadic`?Wte(n.slice(r),e=>!Y7(e)):[]:[];if(o.arity===`one`&&i===-1&&s.length===0)return{kind:`refused`,reason:`Claude Code was started with ${a} and no value after it`};r+=s.length,o.keep&&t.push(e,...s)}return{kind:`args`,args:t}}function Z7(e){let t=e.split(E.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(E.sep),repo:t.slice(0,n-1).join(E.sep)||E.sep}}function Wte(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const Q7=`candybar-band@cc-candybar`,Gte=E.join(`bin`,`cc-candybar-native`),Kte=pI(`/reload-plugins`),$7=e=>({kind:`done`,said:e});function e9(e){let t=o$(e.hints.tmux);if(t.kind===`refused`)throw new Z(t.reason);return t.hint}const qte={band:{on:async(e,t,n)=>{let r=Lt(t.bundle);if(r===null)throw new Z(`${Bb.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=E.join(r,Gte);if(!n.fileExists(i))throw new Z(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${Q7} from ${r}`,finished:Jte(e,r,n)}},off:async()=>$7(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:async(e,t,n)=>{let r=e9(e),i=Ct(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new Z(`${Bb.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return{kind:`underway`,said:`restarting Claude Code in ${r.pane} under the attach launcher`,finished:Zte(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:async()=>$7(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>{let r=e9(e),i=await n.barPanes(r);return i.length>0?$7(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):$7(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:async(e,t,n)=>{let r=o$(e.hints.tmux);if(r.kind===`refused`)return $7(`no bar pane to close: ${r.reason}`);let i=r.hint,a=await n.barPanes(i);for(let e of a)await n.closePane(i,e);return $7(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:async e=>$7(`the daemon draws ${e9(e).pane}'s bar in its status line`),off:async()=>$7(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function Jte(e,t,n){let r={sessionId:e.sessionId,projectDir:e.origin.projectDir,claudeConfigDir:e.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,Q7],r);let i=await s$(n.claudeInput,e.hints.tmux,Kte);if(i.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${i.reason} — or type /reload-plugins yourself`);return`installed ${Q7} from ${t} and typed /reload-plugins into ${i.pane}`}const Yte=new Set([So,FN]);function Xte(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function Zte(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,wt(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${Bb.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);if((await r.paneClaude(t)).pid!==i.pid)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}), so it was not restarted under the attach launcher`);let o=nne(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${Bb.statusline.label} off and on again`);let s=Qte(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=Ute(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=Xte(i.env),u=l.get(`PATH`),d=r.launcherNode(u);if(d.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${d.why}`);let f=r.onPath(`claude`,u)===i.executable?`claude`:i.executable,p=[...l].filter(([e])=>Yte.has(e)),m=(e,t)=>Dt(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...Vte(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${15e3/1e3} s of SIGTERM, so it was not restarted under the attach launcher`);let h=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),g=$te(e,r.presence(e.transcript)),_=g.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:g,v;try{v=await r.paneDir(t,i.parent)}catch(e){throw h(`the directory it was started in could not be read (${e.message})`,m(X7(null,i.cwd),_))}let y=m(X7(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{await r.typeShellLine(t,y)}catch(e){throw h(`the line could not be typed into its pane (${e.message})`,y)}if(!await r.followed(e.sessionId,`statusline`,3e4))throw Error(`Claude Code in ${t.pane} did not come back attached within ${3e4/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${ene[g.kind](e.sessionId)}, and its statusline follows lane B`}function Qte(e,t){return typeof t==`object`?`whether session ${e.sessionId} has a conversation could not be seen (${t.error})`:t===`present`||e.answered===`no`?null:e.answered===`yes`?`session ${e.sessionId} has a conversation but no transcript to resume it from (is session persistence off?), so a restart would lose it`:`this Claude Code does not say whether session ${e.sessionId} has a conversation, and it has no transcript to resume one from`}function $te(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const ene={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},tne={"in-mode":`its pane is in tmux copy mode — leave it (q)`,stashed:`it holds a stashed prompt (ctrl+s), which ending it would lose — restore or send it`,"no-prompt":`it is not at its prompt (a dialog or picker is open) — close it`};function nne(e){let t=t$(e);return t.kind===`ready`?i$(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:n$(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:tne[t.kind]}var rne=class{owed=new Map;setups=new H6;constructor(e){this.deps=e}clicked(e,t,n,r){let i=Vb.filter(e=>n[e]!==r[e]),a=this.take(e);for(let e of i)a.has(e)||a.set(e,n[e]);let o=e=>i.includes(e)?`click`:`owed`;if(t!==null){this.settle(t,a,r,o);return}for(let[e,t]of a)t===r[e]&&a.delete(e);if(i.length>0){let t=[...a.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}a.size>0&&this.owed.set(e,a);for(let[e,t]of this.owed){if(this.owed.size<=1024)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t){this.settle(e,this.take(e.sessionId),t,()=>`owed`)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r){for(let[i,a]of t)n[i]===a?this.deps.log(`info`,`lane: ${i} ${a?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(i)} (session=${e.sessionId})`):this.start(e,i,n[i],r(i))}start(e,t,n,r){this.deps.defer(()=>void this.setups.run(e.sessionId,()=>this.sync(e,t,n,r)))}async sync(e,t,n,r){let i=`by=${r} (session=${e.sessionId})`,a=r=>{let a=`lane: ${t} ${n?`on`:`off`}: ${r instanceof Error?r.message:String(r)}`;this.deps.log(`warn`,`${a} ${i}`),Ks(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=await qte[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){a(e);return}this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`underway`&&await o.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${i}`),a)}};const ine=[`request`,`feed`],t9=new WeakMap;let ane=0;const n9=e=>{let t=t9.get(e);if(t!==void 0)return t;let n=ane++;return t9.set(e,n),n};var one=class{records=new Map;constructor(e=512){this.maxRecords=e}of(e,t){return this.records.get(r9(e,t))?.warnings??[]}ofSession(e,t,n){let r=n9(n.config),i=[];for(let n of ine){let a=this.records.get(r9(e,n)),o=n===t?this.of(e,t):a?.generation===r?a.warnings:[],s=i.map(e=>JSON.stringify(e));for(let e of o){let t=s.indexOf(JSON.stringify(e));t===-1?i.push(e):s.splice(t,1)}}return i}drawn(e,t,n,r){let i=this.of(e,t),a=r9(e,t);this.records.delete(a),this.records.set(a,{generation:n9(n.config),warnings:r});for(let e of this.records.keys()){if(this.records.size<=this.maxRecords)break;this.records.delete(e)}return JSON.stringify(i)!==JSON.stringify(r)}};const r9=(e,t)=>`${t}\0${e}`;var sne=class{queue=new H6;sessions=new H6;gathers=new H6;open=!0;inFlight=null;holder=null;queued=0;gathersInFlight=0;constructor(e){this.deps=e}take(e,{waited:t,gone:n},r){let i=this.deps.monotonic();return this.queued++,this.queue.run(`journals`,async()=>{if(this.queued--,this.refuseClosed(e),n())throw new QK(e);let a=this.deps.monotonic();t(Math.round(a-i)),this.holder={verb:e,since:a};try{return await r({holds:t=>{let n={verb:e,commit:t};return this.inFlight=n,()=>this.commit(n)},landed:t=>t.finally(()=>this.refuseClosed(e))})}finally{this.holder=null}})}click(e,t,{placed:n,waited:r,gone:i,gathered:a},o,s){let c=this.deps.monotonic(),l=async()=>{if(n(Math.round(this.deps.monotonic()-c)),this.refuseClosed(e),i())throw new QK(e);let t=this.deps.monotonic(),l=await o();a(Math.round(this.deps.monotonic()-t));let u=i();return this.take(e,{waited:r,gone:()=>!u&&i()},e=>s(l,e))};return t===null?l():this.sessions.run(t,l)}async gathering(e){this.gathersInFlight++;try{return await this.gathers.run(`gathers`,e)}finally{this.gathersInFlight--}}getStats(){let{holder:e,queued:t}=this;return{holder:e?.verb??null,heldMs:e===null?0:Math.round(this.deps.monotonic()-e.since),queued:t,gathers:this.gathersInFlight}}close(){this.open=!1,this.inFlight!==null&&(this.deps.log(`warn`,`journal: ${this.inFlight.verb} cut off by close, committing what landed`),this.commit(this.inFlight))}refuseClosed(e){if(!this.open)throw new ZK(e)}commit(e){return this.inFlight===e?(this.inFlight=null,e.commit(),!0):!1}},cne=class{sessions=new Map;pending=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}clickArrived(e){this.pending.set(e,(this.pending.get(e)??0)+1),this.sessions.has(e)&&this.settle(e)}clickSettled(e){let t=this.pending.get(e)-1;t===0?this.pending.delete(e):this.pending.set(e,t),this.sessions.has(e)&&this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown&&!this.pending.has(e)?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;let t=0;for(let e of this.pending.values())t+=e;return{sessions:this.sessions.size,armed:e,pending:t}}dispose(){this.disposed=!0;for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null,closing:!1};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=256)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown&&!t.closing&&!this.disposed&&!this.pending.has(e)?ex(t.since,t.timeoutS):null;t.timer?.at!==n&&(this.disarm(t),n!==null&&(t.timer={at:n,clear:this.deps.clock.after(Math.max(0,(n-this.deps.now())*1e3),()=>this.fire(e),{unref:!0})}))}disarm(e){e.timer?.clear(),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now(),r={idleS:n-t.since,timeoutS:t.timeoutS,stillIdle:()=>this.sessions.get(e)===t&&!this.pending.has(e),closed:()=>{t.since=n,t.shown=!1}};t.closing=!0,this.deps.close(e,r).catch(t=>{r.closed(),this.deps.failed(e,t)}).finally(()=>{t.closing=!1,this.sessions.get(e)===t&&this.settle(e)})}};function lne(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,paths:o,gates:s,host:c}=e,l=on(c),u=()=>LA(new Date(i.now())),d=new AbortController,f=!1,p=(t,n)=>e.daemonLog.log(t,f?`after close: ${n}`:n),m=new TQ(i),h=e.launcher({inherited:c.env,stats:m.launchStats,signal:d.signal,observeLifeline:e=>{p(e===null?`info`:`warn`,e===null?`launch lifeline running again`:`launch lifeline ${e}; the next launch starts another`),de.wakeWhere(`data`,()=>!0)}}),g=e.storage(p),_=new rJ(g.session),v=new uJ(_,p,g.history),y=Cr({...e.limits({startedAtMs:m.startedAt.getTime(),exit:a,launcher:h,log:p}),limitBytes:n}),b=new VQ,x=new $ee,S=e.doctorStores,w=new jC({clock:i,counters:m,logger:p}),ee=new dj(p),T=new Tc({watchers:w,logger:p,clock:i}),te=T5({launcher:h,host:c,watchers:w,fileEvents:T,clock:i,logger:p,ledger:ee}),{gitProvider:E,usageStore:ne,tmuxService:D,hostService:re,managedStorage:ie}=te,O=new r7,ae=new eP,oe=new cne({clock:i,now:u,close:(e,t)=>P1(e,t,be),failed:(e,t)=>p(t instanceof ZK?`info`:`error`,`menu-idle: close failed (session=${e}): ${C(t)}`)}),se=e.linkSigner,ce=new $s({supersede:(e,t)=>ie.supersede(e,t),launch:h.launch,state:_,log:p,now:u,clock:i}),le=new rne({edge:e.laneEdge(h,e=>de.following(e),d.signal),host:{bundle:t.path,node:t.node,socket:o.socket,preload:Yo(t.path,c)},state:_,log:p,now:u,defer:e=>void i.defer(e)}),ue=new Lte({edge:{run:(e,t,n)=>Ws(h,{socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>de.subscribe(e,t),sessionInPane:(e,t)=>de.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${bt(o.socket)}`,...[...t.node,t.path].map(bt),`url-handle`].join(` `),owner:o.socket,log:p}),de=new p3({render:(e,t,n)=>C3(xe,e,t,n),watch:(e,t)=>(0,Y.reaction)(()=>_.revision(e),t),lanes:e=>T3(xe,e),pin:e=>{let t=he.pin(e);return()=>{he.stopDrawing(e,`feed`),t()}},shown:e=>fe.shown(e.hints.tmux),watching:()=>fe.follow(),refreshes:()=>ee.totals(),periods:s3,clock:i,instant:u,log:p}),fe=new u7({clock:i,listPanes:e=>Ws(h,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,a7]),listClients:e=>Ws(h,{socket:e},`frames.visibility`,[`list-clients`,`-F`,o7]),sockets:()=>new Set(de.watched().flatMap(({req:e})=>pe(e))),onAnswer:(e,t)=>ue.answered(e,t),onChange:e=>de.wakeWhere(`visibility`,t=>pe(t).some(t=>e.has(t))),intervalMs:1e3,log:p});function pe({hints:{tmux:e}}){return e==null?[]:[e.socket]}let me=new one,he=new t7({clock:i,launcher:h,stateDir:o.state,locations:l,env:c.env,sessionState:_,watchers:w,log:p,storage:ie,signer:se,gates:s,ledger:ee,fileEvents:T,declare:(e,t,n,r)=>mX(te,e,t,n,r),source:i7({providers:te,sessionState:_,history:e=>v.depth(e),navigation:(e,t)=>O.depth(e,_,s.state.gateFor(t))})},{budgetBytes:()=>j5(n),observers:{onReload:(e,t,n,r)=>{p(`info`,I5(e,n,r));for(let e of t)de.wake(e,`reload`)},onViewChanged:e=>de.wake(e,`data`)}});T.subscribe(e=>{switch(e.kind){case`period`:w.judge();return;case`caught-up`:he.reloadEvery({kind:`events-resumed`,since:e.since}),de.wakeWhere(`data`,()=>!0);return;case`moved`:de.wakeWhere(`data`,()=>!0);return}});let ge=60*1e3,_e=$6({clock:i,targets:t.targets,intervalMs:ge,stat:e.stat,held:()=>ve.running(),exit:()=>a(0),log:p}),ve=X6({clock:i,launcher:h,entryUrl:t.entryUrl,digest:t.digest,actsDir:T6(o.state,t.path),intervalMs:ge,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,gates:s,onApplied:()=>_e.checkNow(),log:p}),ye=new sne({log:p,monotonic:()=>i.monotonic()}),be={gates:s,sessionState:_,stateDir:o.state,locations:l,journalTurns:ye,clickLanded:e=>oe.clicked(e,u()),log:p,launcher:h,now:u,applyUpdate:()=>ve.act(),doctor:e.doctorEdge(h,e=>{let t=[e.projectDir,e.cwd,e.target.path];he.reload(...t,{kind:`doctor`});let n=he.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}},c),doctorStores:S,probes:b,clients:x,bundle:t.path,serving:()=>y.serving(),claudeInput:e.claudeInput(h),history:v,navigation:O,configFor:e=>he.getOrCreate(e.projectDir,e.cwd,e.target.path).state.config,reloadConfig:e=>he.reload(e.projectDir,e.cwd,e.target.path,{kind:`write`}),sourcesFor:e=>he.getOrCreate(e.projectDir,e.cwd,e.target.path).state.sources,links:se,runs:ce,lanes:{of:(e,t)=>E3(xe,e,t),clicked:(e,t,n)=>I3(xe,e,t,n)},views:{follow:(e,t)=>he.follow(e,t.projectDir,t.cwd,t.target.path)},diagnosticCopy:(e,t,n)=>he.drawnCopy(e,t,n)},xe={home:c.home,tmp:c.tmp,launcher:h,log:p,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:S,stats:m,handlerProbes:b,renderSightings:x,watcherRegistry:w,refreshLedger:ee,fileEvents:T,payloadProviders:te,sessionState:_,effectSessions:ae,menuIdle:oe,journalTurns:ye,linkSigner:se,runs:ce,laneSetups:le,tmuxStatusLines:ue,frameFeeds:de,renderWarnings:me,renderCache:he,updateWatch:ve,limits:y,verbCtx:be};return{stats:m,launcher:h,log:p,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(d.signal.throwIfAborted(),p6(xe,e,t,n,r)),reply:async(e,t,n,r)=>(d.signal.throwIfAborted(),m6(xe,e,t,n,r)),subscribe:(e,t)=>(d.signal.throwIfAborted(),de.subscribe(e,t)),reloadConfig:e=>{d.signal.throwIfAborted(),be.reloadConfig(e)},arm(){d.signal.throwIfAborted(),T.start(o.watchProbe),_e.arm(),ve.arm(),y.arm()},close(e){let t=[[`journalTurns close`,()=>ye.close()],[`tmuxStatusLines restore`,()=>ue.restoreAll(e)],[`launches abort`,()=>d.abort(Error(`the daemon closed`))],[`frameFeeds close`,()=>de.close()],[`menuIdle dispose`,()=>oe.dispose()],[`updateWatch close`,()=>ve.close()],[`binaryWatch close`,()=>_e.close()],[`limits disarm`,()=>y.disarm()],[`renderCache close`,()=>he.close()],[`gitService close`,()=>E.close()],[`usageStore close`,()=>ne.close()],[`tmuxService close`,()=>D.close()],[`hostService close`,()=>re.close()],[`runs close`,()=>ce.close()],[`managedStorage close`,()=>ie.close()],[`fileEvents close`,()=>T.close()],[`watcherRegistry close`,()=>w.closeAll()],[`sessionState close`,()=>_.close()]];for(let[e,n]of t)try{n()}catch(t){p(`warn`,`${e} failed: ${t.message}`)}return f=!0,h.settled()}}}function une(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e)){if(typeof t!=`object`||!t||Array.isArray(t))return!1;for(let e of Object.values(t))if(typeof e!=`string`)return!1}return!0}var dne=class{clearTimer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t,n=500,r=Pe){this.filePath=e,this.clock=t,this.debounceMs=n,this.logger=r,this.writingPath=`${e}.writing`}load(){let e;try{e=l.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return une(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,this.schedule()}schedule(){this.clearTimer!==null||this.writing||(this.clearTimer=this.clock.after(this.debounceMs,()=>{this.clearTimer=null,this.write()},{unref:!0}))}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=this.clock.monotonic(),r=JSON.stringify(e),i=this.writingPath;this.writing=!0;let a=this.clock.monotonic()-n;try{await l.promises.mkdir(E.dirname(this.filePath),{recursive:!0});let o=await l.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}let s=!1;if(t===this.generation)try{await l.promises.rename(i,this.filePath),s=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){s||await l.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${s} took=${Math.round(this.clock.monotonic()-n)}ms held=${Math.round(a)}ms`);return}this.saved(r,e,n,a),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.clearTimer?.(),this.clearTimer=null,this.pending===null)return;let e=this.pending,t=this.clock.monotonic();try{l.mkdirSync(E.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);l.writeFileSync(n,r,{mode:384}),l.chmodSync(n,384),l.rmSync(this.writingPath,{force:!0}),l.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,this.clock.monotonic()-t),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${Math.round(this.clock.monotonic()-n)}ms held=${Math.round(r)}ms`)}};function fne(e,t,n){return{session:new dne(e.sessionState,n,500,t),history:jJ(e.settingsHistory,t)}}function i9(e,t,n){for(let r of(t??``).split(E.delimiter)){if(!E.isAbsolute(r))continue;let t=E.join(r,e);if(n(t))return t}return null}function a9(e,t){try{return l.accessSync(e,t),l.statSync(e).isFile()}catch{return!1}}function pne(e){try{return l.realpathSync(e)}catch{return E.resolve(e)}}function mne(e,t,n){let r=i9(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:E.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const o9=2e3;async function s9(e,t,n,r){let i=await Ws(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function c9(e,t){if(t.ok)return t.stdout;let n=t.error??[t.reason,t.stderr.trim(),t.stdout.trim()].filter(e=>e!==``).join(`: `);throw Error(`${e} failed (${n})`)}function hne(e){try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`ok`in t&&t.ok===!1&&`reason`in t&&typeof t.reason==`string`)return`detail`in t&&typeof t.detail==`string`?`${t.reason}: ${t.detail}`:t.reason}catch{}return null}const gne=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function _ne(e,t){return e.split(`
|
|
493
|
-
`).flatMap(e=>{let[n,...r]=e.trim().split(` `);return
|
|
494
|
-
`);async function xne(e,t){if(process.platform===`linux`)return{executable:await l.promises.readlink(`/proc/${t}/exe`),argv:(await l.promises.readFile(`/proc/${t}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await l.promises.readFile(`/proc/${t}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let n=c9(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,bne,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function l9(e,t,n){return c9(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function u9(e,t){let n=await Ws(e,t,`lane.tmux`,[`display`,`-p`,`-t`,t.pane,`#{pane_pid} #{pane_current_path}`]);if(n.kind!==`ok`)throw Error(n.reason);let[r=``,i=``]=n.stdout.trimEnd().split(` `),a=(await l9(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function Sne(e,t){let{panePid:n,cwd:r,foreground:i}=await u9(e,t),a=await l9(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await xne(e,i),s=KJ(a).get(i)?.ppid;if(s===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);return{pid:i,executable:await l.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:s,fromShell:i!==n,attached:yne(a,i,n)}}function Cne(e,t,n,r){let i=e=>A(r,e,n);return{claudeInput:f$(e),barPanes:async t=>_ne(await s9(e,t,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_start_command}`]),t.pane),openBarPane:async(t,n,r)=>(await s9(e,t,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,t.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(r).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...n])).trim(),closePane:async(t,n)=>void await s9(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void c9(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:NJ(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>l.existsSync(e),presence:Tz,paneClaude:t=>Sne(e,t),paneDir:async(t,n)=>{let a=r.now()+o9;for(;;){let o=await u9(e,t);if(o.foreground===n){if(o.cwd===``)throw Error(`tmux read no directory for pane ${t.pane}`);return o.cwd}if(r.now()>a)throw Error(`the shell in pane ${t.pane} (pid ${n}) did not take its terminal back within ${o9/1e3} s`);await i(100)}},launcherNode:e=>mne(e,e=>a9(e,l.constants.X_OK),pne),onPath:(e,t)=>{let n=i9(e,t,e=>a9(e,l.constants.X_OK));return n===null?null:l.realpathSync(n)},followed:async(e,n,a)=>{let o=r.now()+a;for(;!t(e).has(n);){if(r.now()>o)return!1;await i(200)}return!0},moduleGraph:async(t,n,r)=>{let i=await e.launch({bin:t,args:[n,r],timeoutMs:2e4,category:`lane.process`}),a=!i.ok&&i.reason===`non-zero`?hne(i.stdout):null;return a===null?(c9(`reading ${r}'s module graph`,i),{ok:!0}):{ok:!1,reason:a}},terminate:e=>{n.throwIfAborted();try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=r.now()+t;for(;ws(e);){if(r.now()>n)return!1;await i(100)}return!0},typeShellLine:async(t,n)=>void await s9(e,t,u$(t.pane,`cc-candybar-lane`,[]),n)}}const wne=/^[0-9a-f]{64}$/;function d9(e,t){return se(`sha256`,e).update(JSON.stringify([t.sessionId,t.action,t.declaration,t.evaluated])).digest()}function Tne(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);return{sign:t=>d9(e,t).toString(`hex`),verify:(t,n)=>wne.test(n)?ue(Buffer.from(n,`hex`),d9(e,t)):!1}}function f9(e){return E.join(e,`link.key`)}function p9(e){let t,n=()=>t??=Ene(e);return{sign:e=>n().sign(e),verify:(e,t)=>n().verify(e,t)}}function Ene(e){let t;try{t=l.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;Dne(e),t=l.readFileSync(e)}if(t.length!==32)throw Error(`link key ${e} holds ${t.length} bytes, not 32: remove it and a new one is made (links drawn before then stop working)`);return Tne(t)}function Dne(e){l.mkdirSync(E.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${ce(6).toString(`hex`)}`;l.writeFileSync(t,ce(32),{mode:384,flag:`wx`});try{l.linkSync(t,e)}catch(e){if(e.code!==`EEXIST`)throw e}finally{l.unlinkSync(t)}}function One(e,t,n){return{daemonLog:t,launcher:e=>ft(e,n),storage:t=>fne(e,t,n),doctorStores:qZ(e.state),doctorEdge:aQ,claudeInput:f$,laneEdge:(e,t,r)=>Cne(e,t,r,n),linkSigner:p9(f9(e.state)),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>kr(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),fetch,stat:l.statSync}}const kne=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function m9(e){if(e===void 0)return;let t=H.parse(e);if(t.isDefault)return;let n=t.fixedValue;if(n!==void 0)return n.hex;let r=t.type===V.STANDARD&&t.number!==void 0?kne[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const Ane={bold:`bold`,dim:`dimColor`,italic:`italic`,underline:`underline`,strike:`strikethrough`,reverse:`inverse`,blink:null,blink2:null,conceal:null,underline2:null,frame:null,encircle:null,overline:null};function jne({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=m9(t),o=m9(n),s={};for(let e of r){let t=Ane[e];if(t===null)throw Error(`frames: the band cannot draw ${e} text`);s[t]=!0}return{text:e,...a!==void 0&&{color:a},...o!==void 0&&{backgroundColor:o},...s,...i!==void 0&&{href:i}}}function Mne(e){return{ok:!0,band:e.rows.map(e=>OP(e).map(jne))}}function Nne(e){return _P(Mne,e)}const Pne={band:e=>JSON.stringify(Nne(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:y7(e)})};function h9(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}function Fne(e,t){t.allowHalfOpen=!1;let n=e.clock.monotonic();e.stats.inFlight++;let r=!1,i=!0,a=()=>{i&&(i=!1,e.stats.inFlight--)},o=(n,i,a)=>{if(r){i!==null&&e.log(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}r=!0,c();let o=i===null?void 0:()=>e.exit(i);try{t.end(Mn(n),e=>{e??a(),o?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),o?.()}},s=!1,c=e.clock.after(200,()=>{s=!0,e.stats.requestsTimedOut++,o({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,b3)}),l=Pn(r=>{e.handle(r,()=>s,n,()=>t.destroyed).then(e=>e.kind===`reply`?o(e.resp,e.exitAfterFlush,e.delivered):u(e.sessionId,e.lane)).catch(t=>{e.log(`error`,`handler threw: ${C(t)}`),o(x3(t),null,b3)})},t=>{e.log(`warn`,`frame parse failed: ${t.message}`),o({ok:!1,error:t.message,code:`BAD_REQUEST`,daemonV:3},null,b3)}),u=(n,i)=>{if(r||t.destroyed)return;c(),a(),t.off(`data`,l);let o=h9(t),s=e.subscribe(n,{lane:i,frame:(e,t)=>o(Nn(Pne[i](e,t))),refused:e=>t.end(Mn(e)),drawing:()=>!0});r=!0,t.on(`close`,s)};t.on(`data`,l),t.on(`error`,t=>{e.log(`warn`,`socket error: ${t.message}`)}),t.on(`close`,()=>{c(),a()})}let g9=null,_9=null,v9=null,y9=null;function b9(){if(y9===null)throw Error(`runDaemon has not started`);return y9}function x9(e,t){b9().log.log(e,t)}function Ine(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:zt(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function Lne(e){let n=an(e.host);y9={world:e,paths:n,log:new Bs(n.log,e.clock)},t.on(`uncaughtException`,e=>{x9(`error`,`uncaughtException: ${e.stack||e.message}`),T9(1)}),t.on(`unhandledRejection`,e=>{x9(`error`,`unhandledRejection: ${String(e)}`),T9(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{x9(`info`,`received ${e}, shutting down`),T9(0)});Rne().catch(S9)}function S9(e){x9(`error`,`refusing to boot: ${C(e)}`),T9(1)}async function Rne(){let{world:e,paths:n,log:r}=b9(),{host:i}=e,a=hr(i.env);g9=await bs(t.pid,t=>vs(t,e.launcher.launch));let o=await As(Ms(e,g9,n.registry));if(!o.decision.allow){x9(`warn`,`fork-bomb breaker: ${o.decision.reason}; refusing to boot`),T9(1);return}_9=o.registryPath,l.mkdirSync(n.state,{recursive:!0}),Jt(n.socket);let s=lne({...One(n,r,e.clock),bundle:Ine(),host:i,paths:n,memoryLimitBytes:a,registryUrl:i.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:wz(),exit:T9});v9=s,Cs({clock:e.clock,anchor:Ss(i.env),isAlive:ws,onOrphaned:e=>{x9(`info`,`parent watchdog: ${e}; shutting down`),T9(0)}}),C9(s,de.createServer(e=>Fne(s,e)),n.socket,!1)}function C9(e,n,r,i){n.removeAllListeners(`error`),n.removeAllListeners(`listening`),n.once(`error`,a=>{if(a.code!==`EADDRINUSE`){x9(`error`,`server error: ${a.message}`),T9(1);return}if(i){x9(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}zne(e,n,r).catch(S9)}),n.listen(r,()=>Bne(e,r))}async function zne(e,n,r){let i=await ms(hs(Yt(r)),(t,n)=>ys(t,n,{readStartTime:t=>vs(t,e.launcher.launch),pidAlive:ws}));if(i.kind===`attach-and-exit`){x9(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}x9(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{l.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){x9(`error`,`cannot unlink stale socket ${r}: ${e.message}`),T9(1);return}}C9(e,n,r,!0)}function Bne(e,n){let r=gs(n);if(r.kind!==`present`){x9(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),T9(0);return}Hne(n);try{l.chmodSync(n,384)}catch(e){x9(`warn`,`chmod socket failed: ${e.message}`)}x9(`info`,`daemon up: pid=${t.pid} v=3 sock=${n} heapCap=${mr(fe.getHeapStatistics().heap_size_limit)}MB memoryLimit=${mr(e.memoryLimitBytes)}MB`),Rr(b9().paths.spawnBackoff),e.arm(),Vne(n,r.identity)}function Vne(e,n){_s({bound:n,myPid:t.pid,readIdentity:()=>gs(e),readLease:()=>hs(Yt(e)),shutdown:e=>T9(e),log:x9,clock:b9().world.clock}).arm()}function Hne(e){let n=uee(Yt(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:g9});n!==null&&x9(`warn`,`lease write failed: ${n}`)}const Une=e=>(t,n,r)=>Us(e,{socket:t},`tmux-status`,n,r);let w9=!1;function T9(e){w9||(w9=!0,b9().world.clock.after(500,()=>t.kill(t.pid,`SIGKILL`)),v9?.close(Une(b9().world.launcher)),dee(b9().paths.lease,t.pid),_9!==null&&js(_9,t.pid,Os,e=>l.unlinkSync(e)),t.exit(e))}const Wne={connectMs:200,budgetMs:500};async function Gne(e,t,n){return Kne(t,await qne(e,t),n.includes(`--json`))}function Kne(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
|
|
495
|
-
`:
|
|
496
|
-
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${
|
|
490
|
+
`)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var u7=class{servers=new Map;loop={kind:`idle`};constructor(e){this.deps=e}follow(){switch(this.loop.kind){case`idle`:this.deps.log(`info`,`visibility following`),this.ask();break;case`asking`:this.loop.following=!0;break;case`due`:break}return()=>this.stop()}stop(){switch(this.loop.kind){case`due`:this.loop.clear(),this.end();return;case`asking`:this.loop.following=!1;return;case`idle`:return}}ask(){let e={kind:`asking`,following:!0};this.loop=e,Promise.resolve().then(()=>this.refresh(this.deps.sockets())).catch(e=>this.deps.log(`error`,`visibility refresh threw: ${C(e)}`)).then(()=>{if(e.following){this.loop={kind:`due`,clear:this.deps.clock.after(this.deps.intervalMs,()=>this.ask(),{unref:!0})};return}this.end()})}end(){this.deps.log(`info`,`visibility stopped forgot=${this.servers.size}`),this.loop={kind:`idle`},this.servers.clear()}shown(e){if(e==null)return!0;let t=this.servers.get(e.socket);return t?.kind!==`asked`||t.shown.has(e.pane)}async refresh(e){for(let t of this.servers.keys())e.has(t)||this.servers.delete(t);let t=await Promise.all([...e].map(async e=>{let[t,n]=await Promise.all([this.deps.listPanes(e),this.deps.listClients(e)]);return[e,t.kind===`ok`?n.kind===`ok`?{kind:`asked`,shown:c7(t.stdout,s7(n.stdout)),status:l7(t.stdout,n.stdout)}:{kind:`unasked`,reason:n.reason}:{kind:`unasked`,reason:t.reason}]})),n=new Set;for(let[e,r]of t){let t=this.servers.get(e);this.servers.set(e,r),!d7(t,r)&&(n.add(e),this.deps.log(r.kind===`asked`?`info`:`warn`,r.kind===`asked`?`visibility socket=${JSON.stringify(e)} shown=${[...r.shown].join(`,`)||`-`}`:`visibility socket=${JSON.stringify(e)} unasked: ${r.reason} — its panes count as shown`))}for(let[e,n]of t)n.kind===`asked`&&this.deps.onAnswer(e,n.status);n.size>0&&this.deps.onChange(n)}};function d7(e,t){return e===void 0||e.kind!==t.kind?!1:e.kind===`unasked`||t.kind===`unasked`?!0:e.shown.size===t.shown.size&&[...e.shown].every(e=>t.shown.has(e))}function f7(e){return`ccb`+oe(`sha256`).update(e).digest(`hex`).slice(0,12)}const p7=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function m7(e){if(e===void 0)return`terminal`;let t=H.parse(e);if(t.isDefault)return`terminal`;switch(t.type){case V.STANDARD:{let e=t.number===void 0?void 0:p7[t.number];if(e!==void 0)return e;break}case V.EIGHT_BIT:if(t.number!==void 0)return`colour${t.number}`;break;case V.TRUECOLOR:{let e=t.fixedValue;if(e!==void 0)return e.hex;break}case V.DEFAULT:case V.WINDOWS:break}throw Error(`frames: no tmux colour for ${t.name}`)}const h7={bold:`bold`,dim:`dim`,italic:`italics`,underline:`underscore`,strike:`strikethrough`,reverse:`reverse`,blink:`blink`,conceal:`hidden`,underline2:`double-underscore`,overline:`overline`,blink2:null,frame:null,encircle:null};function g7(e){return e.replaceAll(`#`,`##`)}function _7({fg:e,bg:t,attrs:n=[]}){let r=n.map(e=>{let t=h7[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${m7(e)}`,`bg=${m7(t)}`,...r].join(`,`)}]`}function v7(e){let t={},n=e=>{let n=_7(e)+g7(e.text);if(e.link===void 0)return n;let r=f7(e.link);return t[r]=e.link,`#[range=user|${r}]${n}#[norange]`};return{rows:e.rows.map(e=>OP(e).map(n).join(``)),links:t}}function y7(e){return _P(v7,e)}const b7=Bb.tmuxStatus.rows,x7=`@cc-candybar-status-prior`,S7=`@cc-candybar-status-wrote`,C7=`@cc-candybar-binding-prior`,w7=[`-T`,`root`,`MouseDown1Status`],T7=Array.from({length:b7},(e,t)=>t),E7=e=>`@cc-candybar-row-${e}`,Ate=e=>`#[fill=terminal]#{${E7(e)}}`,D7=e=>`status-format[${e}]`;function jte(e){return e===0?`off`:e===1?`on`:String(e)}function O7(e){let t=e===`off`?0:e===`on`?1:/^[2-5]$/.test(e)?+e:NaN;if(Number.isNaN(t))throw Error(`tmux status is ${JSON.stringify(e)}`);return t}function Mte(e,t){if(e===null)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>e[Number(n)]===t[Number(n)])}function k7(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function A7(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function j7(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function Nte(e){return e.map(e=>e.map(j7).join(` `)).join(` ; `)}const M7=`ccb:separator`;function N7(e){return A7(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,M7],e]))}function P7(e,t){let n=e.split(`${M7}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const F7=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],I7=e=>[`show-options`,`-g`,`-q`,`-v`,e],L7=e=>[[`show-options`,`-t`,e],F7(e,`status`),...T7.map(t=>F7(e,D7(t)))];function R7(e){let[t=``,n=``,...r]=e,i=t.split(`
|
|
491
|
+
`).map(e=>e.split(` `)[0]??``),a={};for(let e of T7)i.includes(D7(e))&&(a[e]=r[e]??``);let o=i.includes(`status-format`)||Object.keys(a).length>0;return{status:i.includes(`status`)?n:null,formats:o?a:null}}function z7(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,D7(Number(t)),k7(n)])]}const Pte=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...L7(e),...T7.map(e=>I7(D7(e))),F7(e,x7),F7(e,S7)];function B7(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:O7(t)}catch(e){return{kind:`theirs`,why:`${x7} does not read (${String(e)})`}}return r.owner===n?{kind:`ours`,prior:r,status:i}:{kind:`theirs`,why:`the daemon at ${JSON.stringify(r.owner)} draws it`}}function Fte(e,t,n){let[r=``,...i]=t,a=R7(i.slice(0,2+b7)),o=i.slice(2+b7,2+2*b7),[s=``,c=``]=i.slice(2+2*b7);if(s!==``)return B7(s,c,n);let l=O7(r),u={};for(let e=0;e<l;e++){let t=a.formats===null?o[e]:a.formats[e];t!==void 0&&t!==``&&(u[e]=t)}let d={...u,...Object.fromEntries(Array.from({length:b7-l},(e,t)=>[l+t,Ate(t)]))},f={owner:n,base:l,status:a.status,formats:a.formats,wrote:d};return{kind:`lay-out`,prior:f,commands:[[`set-option`,`-t`,e,x7,JSON.stringify(f)],...z7(e,d)]}}const V7=e=>[...L7(e),F7(e,S7)];function H7(e,t,n){let r=R7(n.slice(0,2+b7)),i=n[2+b7]??``,a=[],o=[];if(Mte(r.formats,t.wrote))a.push(...z7(e,t.formats));else{o.push(`status-format`);for(let[n,i]of Object.entries(r.formats??{}))Number(n)>=t.base&&i===t.wrote[Number(n)]&&a.push([`set-option`,`-u`,`-t`,e,D7(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,k7(t.status)]):o.push(`status`)),a.push(...T7.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,E7(t)]),[`set-option`,`-q`,`-u`,`-t`,e,x7],[`set-option`,`-q`,`-u`,`-t`,e,S7]),{commands:a,kept:o}}const Ite=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,U7=[[`list-keys`,`-T`,`root`]];function W7(e){let t=Ite.exec(e);return t===null?null:{line:t[0],command:t[1]}}const G7=`cc-candybar://tmux-status-click/`,Lte=e=>`${G7}${Zi([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,K7=e=>e?.command.includes(G7)??!1;function q7(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,C7]};return K7(W7(t))?{steps:[e===null?{command:[`unbind-key`,...w7]}:{command:[`source-file`,`-`],stdin:`${e.line}\n`},n],said:`restored MouseDown1Status to ${e===null?`unbound`:JSON.stringify(e.line)}`}:{steps:[n],said:`left MouseDown1Status as it is: bound again since`}}var Rte=class{held=new Map;servers=new Map;closed=!1;writes=0;failedWrites=0;constructor(e){this.deps=e}observe(e,t,n){if(this.closed)return;let r=this.held.get(e),i=n&&t!=null?t:null;if(r!==void 0&&(i===null||r.socket!==i.socket||r.pane!==i.pane)&&this.release(r,`switched off or moved`),i===null||this.held.has(e))return;let a={sessionId:e,socket:i.socket,pane:i.pane,unsubscribe:null,frame:null};this.held.set(e,a),this.serverOf(i.socket),this.deps.log(`info`,`tmux-status: holding sid=${JSON.stringify(e)} pane=${i.pane} socket=${JSON.stringify(i.socket)}`),a.unsubscribe=this.deps.subscribe(e,{lane:`tmuxStatus`,frame:e=>{a.frame=y7(e),this.reconcile(a.socket)},refused:t=>{this.held.get(e)===a&&this.release(a,`refused: ${t.error}`)},drawing:()=>this.draws(a)})}answered(e,t){if(this.closed)return;let n=this.serverOf(e);n.view=t;for(let n of[...this.held.values()])if(n.socket===e)if(!t.sessionOf.has(n.pane))this.release(n,`pane gone`);else{let t=this.deps.sessionInPane(e,n.pane);t!==null&&t!==n.sessionId&&this.release(n,`pane taken by sid=${JSON.stringify(t)}`)}this.reconcile(e)}draws(e){let t=this.servers.get(e.socket),n=t?.view?.sessionOf.get(e.pane);return n!==void 0&&t.layouts.has(n)&&t.view.shownBy.get(n)===e.pane}restoreAll(e){this.closed=!0;for(let e of this.held.values())e.unsubscribe?.();this.held.clear();for(let[t,n]of this.servers){for(let[r,i]of[...n.layouts]){n.layouts.delete(r);let a=this.askSync(e,t,V7(r));if(a===null)continue;let o=H7(r,i.prior,a);this.writeSync(e,t,o.commands),this.saidRestored(t,r,o.kept)}let r=n.binding;if(n.binding={kind:`none`},r.kind===`ours`||r.kind===`adopted`){let n=this.askSync(e,t,U7);if(n===null)continue;this.writeBindingRestoreSync(e,t,r.prior,n[0]??``)}}}linkAt(e){let t=zte(e),[n,r,i,...a]=t??[];if(t===null||n===void 0||r===void 0||i===void 0||a.length>0)return{kind:`refused`,reason:`tmux-status-click needs <socket>/<pane>/<range>, got ${JSON.stringify(e)}`};let o=[...this.held.values()].find(e=>e.socket===n&&e.pane===`%${r}`)?.frame?.links[i];return o===void 0?{kind:`refused`,reason:`pane %${r}'s status line draws no link ${i} now`}:{kind:`link`,url:o}}stats(){return{sessions:this.held.size,layouts:[...this.servers.values()].reduce((e,t)=>e+t.layouts.size,0),writes:this.writes,failedWrites:this.failedWrites}}async settled(){for(let e of this.servers.values())await e.running}serverOf(e){let t=this.servers.get(e);if(t!==void 0)return t;let n={view:null,adopted:!1,layouts:new Map,left:new Map,binding:{kind:`none`},running:null,again:!1,lastFailure:null};return this.servers.set(e,n),n}release(e,t){e.unsubscribe?.(),this.held.delete(e.sessionId),this.deps.log(`info`,`tmux-status: released sid=${JSON.stringify(e.sessionId)} pane=${e.pane} — ${t}`),this.reconcile(e.socket)}reconcile(e){let t=this.servers.get(e);if(!(t===void 0||this.closed)){if(t.running!==null){t.again=!0;return}t.running=(async()=>{try{do t.again=!1,await this.step(e,t);while(t.again&&!this.closed)}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} reconcile threw: ${String(t)}`)}finally{t.running=null}})()}}async step(e,t){let n=t.view;if(n===null)return;t.adopted||(t.adopted=!0,await this.adopt(e,t));let r=new Map;for(let t of this.held.values()){if(t.socket!==e)continue;let i=n.sessionOf.get(t.pane);i!==void 0&&r.set(i,[...r.get(i)??[],t])}for(let i of new Set([...t.layouts.keys(),...t.left.keys(),...r.keys()])){if(this.closed)return;let a=r.get(i)??[],o=t.layouts.get(i);if(a.length===0){t.left.delete(i),o!==void 0&&await this.restore(e,t,i);continue}if(t.left.has(i))continue;let s=o??await this.install(e,t,i);if(s===null)continue;let c=a.find(e=>e.pane===n.shownBy.get(i))?.frame?.rows.slice(0,b7-s.prior.base)??[];await this.draw(e,i,s,c)}this.closed||(t.layouts.size>0?await this.installBinding(e,t):await this.restoreBinding(e,t))}async adopt(e,t){let n=await this.run(e,[`list-sessions`,`-F`,`#{session_id}\t#{${x7}}\t#{${S7}}`]);if(n.kind===`ok`)for(let r of n.stdout.split(`
|
|
492
|
+
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=B7(i,a,this.deps.owner);o.kind===`ours`?t.layouts.set(n,{prior:o.prior,rows:[],status:o.status}):this.leave(e,t,n,o.why)}let r=(await this.ask(e,[I7(`@cc-candybar-binding-prior`)]))?.[0]??``;if(r!==``)try{let e=JSON.parse(r);e.owner===this.deps.owner&&(t.binding={kind:`adopted`,prior:e.prior})}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${C7} does not read (${String(t)}), left as it is`)}(t.layouts.size>0||t.binding.kind===`adopted`)&&this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)||`-`} binding=${t.binding.kind}`)}leave(e,t,n,r){t.left.set(n,r),this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} session ${n} left as it is: ${r}`)}async install(e,t,n){let r=await this.ask(e,Pte(n));if(r===null||this.closed)return null;let i=Fte(n,r,this.deps.owner);if(i.kind===`theirs`)return this.leave(e,t,n,i.why),null;let a={prior:i.prior,rows:[],status:i.kind===`ours`?i.status:i.prior.base};return t.layouts.set(n,a),i.kind===`lay-out`&&await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} session ${n} base=${i.prior.base} own=${[i.prior.status===null?[]:[`status`],i.prior.formats===null?[]:[`status-format`]].flat().join(`,`)||`-`}`),a}async draw(e,t,n,r){let i=n.prior.base+r.length,a=[];if(r.forEach((e,r)=>{n.rows[r]!==e&&a.push([`set-option`,`-t`,t,E7(r),e])}),i!==n.status){let e=jte(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,S7,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,Nte(a)]]))&&(n.rows=r,n.status=i)}async restore(e,t,n){let r=t.layouts.get(n);if(r===void 0)return;t.layouts.delete(n);let i=await this.ask(e,V7(n));if(i===null)return;let a=H7(n,r.prior,i);await this.write(e,a.commands),this.saidRestored(e,n,a.kept)}saidRestored(e,t,n){this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} restored session ${t} kept=${n.join(`,`)||`-`}`)}async installBinding(e,t){let n=t.binding;if(n.kind===`ours`||n.kind===`left`)return;let r=await this.ask(e,U7);if(r===null||this.closed)return;let i=W7(r[0]??``);if(n.kind===`none`&&K7(i)){t.binding={kind:`left`,why:`another cc-candybar daemon's status-line clicks are bound to MouseDown1Status; left as it is, so this daemon's are off`},this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.binding.why}`);return}let a=n.kind===`adopted`&&K7(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...w7,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${j7(`${this.deps.handler} ${Lte(e)}`)}`,...a===null?[]:[a.command]],[`set-option`,`-g`,`@cc-candybar-binding-prior`,JSON.stringify(o)]])){t.binding=n;return}this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} bound MouseDown1Status (was ${a===null?`unbound`:JSON.stringify(a.line)})`)}async restoreBinding(e,t){let n=t.binding;if(t.binding={kind:`none`},n.kind!==`ours`&&n.kind!==`adopted`)return;let r=await this.ask(e,U7);if(r===null)return;let i=q7(n.prior,r[0]??``);for(let t of i.steps)await this.write(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.said}`)}writeBindingRestoreSync(e,t,n,r){let i=q7(n,r);for(let n of i.steps)this.writeSync(e,t,[n.command],n.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(t)} ${i.said}`)}counted(e,t){let n=this.serverOf(e);return t.kind===`ok`?(n.lastFailure=null,t):(this.failedWrites++,n.lastFailure!==t.reason&&this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.reason}`),n.lastFailure=t.reason,t)}async run(e,t,n){return this.counted(e,await this.deps.edge.run(e,t,n))}async ask(e,t){let n=await this.run(e,N7(t));return n.kind===`ok`?P7(n.stdout,t.length):null}askSync(e,t,n){let r=this.counted(t,e(t,N7(n)));return r.kind===`ok`?P7(r.stdout,n.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,A7(t),n)).kind===`ok`)}writeSync(e,t,n,r){n.length!==0&&(this.writes++,this.counted(t,e(t,A7(n),r)))}};function zte(e){try{return Qi(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),J7=e=>({arity:e,keep:!1}),Bte={"--add-dir":$(`variadic`),"--agent":$(`one`),"--agents":$(`one`),"--allow-dangerously-skip-permissions":$(`none`),"--allowedTools":$(`variadic`),"--allowed-tools":$(`variadic`),"--append-system-prompt":$(`one`),"--autocompact":$(`one`),"--ax-screen-reader":$(`none`),"--bg":J7(`none`),"--background":J7(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":J7(`optional`),"-c":J7(`none`),"--continue":J7(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":J7(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":J7(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":J7(`none`),"--forward-subagent-text":$(`none`),"--from-pr":J7(`optional`),"-h":J7(`none`),"--help":J7(`none`),"--ide":$(`none`),"--include-hook-events":$(`none`),"--include-partial-messages":$(`none`),"--input-format":$(`one`),"--json-schema":$(`one`),"--max-budget-usd":$(`one`),"--mcp-config":$(`variadic`),"--model":$(`one`),"-n":$(`one`),"--name":$(`one`),"--no-chrome":$(`none`),"--no-session-persistence":$(`none`),"--output-format":$(`one`),"--permission-mode":$(`one`),"--permission-prompts":$(`one`),"--plugin-dir":$(`one`),"--plugin-url":$(`one`),"-p":J7(`none`),"--print":J7(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":J7(`optional`),"--resume":J7(`optional`),"--safe-mode":$(`none`),"--session-id":J7(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":J7(`optional`),"--tmux":J7(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":J7(`none`),"--version":J7(`none`),"-w":J7(`optional`),"--worktree":J7(`optional`)},Vte={resume:`--resume`,fresh:`--session-id`};function Hte(e){return[Vte[e.kind],e.sessionId]}const Y7=e=>e.startsWith(`-`)&&e!==`-`;function X7(e,t){let n=Z7(t);return n===null?{dir:e??t,args:[]}:e!==null&&Ute(e,n.top)?{dir:e,args:[]}:{dir:e===null||Z7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const Ute=(e,t)=>e===t||e.startsWith(t+E.sep);function Wte(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!Y7(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=Bte[a];if(o===void 0)return{kind:`refused`,reason:`Claude Code was started with ${a}, which cc-candybar does not know how to carry to a restart`};let s=i===-1?o.arity===`one`?n.slice(r,r+1):o.arity===`optional`?n.slice(r,r+1).filter(e=>!Y7(e)):o.arity===`variadic`?Gte(n.slice(r),e=>!Y7(e)):[]:[];if(o.arity===`one`&&i===-1&&s.length===0)return{kind:`refused`,reason:`Claude Code was started with ${a} and no value after it`};r+=s.length,o.keep&&t.push(e,...s)}return{kind:`args`,args:t}}function Z7(e){let t=e.split(E.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(E.sep),repo:t.slice(0,n-1).join(E.sep)||E.sep}}function Gte(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const Q7=`candybar-band@cc-candybar`,Kte=E.join(`bin`,`cc-candybar-native`),qte=fI(`/reload-plugins`),$7=e=>({kind:`done`,said:e});function e9(e){let t=a$(e.hints.tmux);if(t.kind===`refused`)throw new Z(t.reason);return t.hint}const Jte={band:{on:async(e,t,n)=>{let r=Lt(t.bundle);if(r===null)throw new Z(`${Bb.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=E.join(r,Kte);if(!n.fileExists(i))throw new Z(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${Q7} from ${r}`,finished:Yte(e,r,n)}},off:async()=>$7(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:async(e,t,n)=>{let r=e9(e),i=Ct(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new Z(`${Bb.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return{kind:`underway`,said:`restarting Claude Code in ${r.pane} under the attach launcher`,finished:Qte(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:async()=>$7(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>{let r=e9(e),i=await n.barPanes(r);return i.length>0?$7(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):$7(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:async(e,t,n)=>{let r=a$(e.hints.tmux);if(r.kind===`refused`)return $7(`no bar pane to close: ${r.reason}`);let i=r.hint,a=await n.barPanes(i);for(let e of a)await n.closePane(i,e);return $7(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:async e=>$7(`the daemon draws ${e9(e).pane}'s bar in its status line`),off:async()=>$7(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function Yte(e,t,n){let r={sessionId:e.sessionId,projectDir:e.origin.projectDir,claudeConfigDir:e.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,Q7],r);let i=await o$(n.claudeInput,e.hints.tmux,qte);if(i.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${i.reason} — or type /reload-plugins yourself`);return`installed ${Q7} from ${t} and typed /reload-plugins into ${i.pane}`}const Xte=new Set([So,FN]);function Zte(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function Qte(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,wt(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${Bb.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);if((await r.paneClaude(t)).pid!==i.pid)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}), so it was not restarted under the attach launcher`);let o=rne(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${Bb.statusline.label} off and on again`);let s=$te(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=Wte(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=Zte(i.env),u=l.get(`PATH`),d=r.launcherNode(u);if(d.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${d.why}`);let f=r.onPath(`claude`,u)===i.executable?`claude`:i.executable,p=[...l].filter(([e])=>Xte.has(e)),m=(e,t)=>Dt(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...Hte(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${15e3/1e3} s of SIGTERM, so it was not restarted under the attach launcher`);let h=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),g=ene(e,r.presence(e.transcript)),_=g.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:g,v;try{v=await r.paneDir(t,i.parent)}catch(e){throw h(`the directory it was started in could not be read (${e.message})`,m(X7(null,i.cwd),_))}let y=m(X7(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{await r.typeShellLine(t,y)}catch(e){throw h(`the line could not be typed into its pane (${e.message})`,y)}if(!await r.followed(e.sessionId,`statusline`,3e4))throw Error(`Claude Code in ${t.pane} did not come back attached within ${3e4/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${tne[g.kind](e.sessionId)}, and its statusline follows lane B`}function $te(e,t){return typeof t==`object`?`whether session ${e.sessionId} has a conversation could not be seen (${t.error})`:t===`present`||e.answered===`no`?null:e.answered===`yes`?`session ${e.sessionId} has a conversation but no transcript to resume it from (is session persistence off?), so a restart would lose it`:`this Claude Code does not say whether session ${e.sessionId} has a conversation, and it has no transcript to resume one from`}function ene(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const tne={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},nne={"in-mode":`its pane is in tmux copy mode — leave it (q)`,stashed:`it holds a stashed prompt (ctrl+s), which ending it would lose — restore or send it`,"no-prompt":`it is not at its prompt (a dialog or picker is open) — close it`};function rne(e){let t=e$(e);return t.kind===`ready`?r$(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:t$(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:nne[t.kind]}var ine=class{owed=new Map;setups=new V6;constructor(e){this.deps=e}clicked(e,t,n,r){let i=Vb.filter(e=>n[e]!==r[e]),a=this.take(e);for(let e of i)a.has(e)||a.set(e,n[e]);let o=e=>i.includes(e)?`click`:`owed`;if(t!==null){this.settle(t,a,r,o);return}for(let[e,t]of a)t===r[e]&&a.delete(e);if(i.length>0){let t=[...a.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}a.size>0&&this.owed.set(e,a);for(let[e,t]of this.owed){if(this.owed.size<=1024)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t){this.settle(e,this.take(e.sessionId),t,()=>`owed`)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r){for(let[i,a]of t)n[i]===a?this.deps.log(`info`,`lane: ${i} ${a?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(i)} (session=${e.sessionId})`):this.start(e,i,n[i],r(i))}start(e,t,n,r){this.deps.defer(()=>void this.setups.run(e.sessionId,()=>this.sync(e,t,n,r)))}async sync(e,t,n,r){let i=`by=${r} (session=${e.sessionId})`,a=r=>{let a=`lane: ${t} ${n?`on`:`off`}: ${r instanceof Error?r.message:String(r)}`;this.deps.log(`warn`,`${a} ${i}`),Ks(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=await Jte[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){a(e);return}this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`underway`&&await o.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${i}`),a)}};const ane=[`request`,`feed`],t9=new WeakMap;let one=0;const n9=e=>{let t=t9.get(e);if(t!==void 0)return t;let n=one++;return t9.set(e,n),n};var sne=class{records=new Map;constructor(e=512){this.maxRecords=e}of(e,t){return this.records.get(r9(e,t))?.warnings??[]}ofSession(e,t,n){let r=n9(n.config),i=[];for(let n of ane){let a=this.records.get(r9(e,n)),o=n===t?this.of(e,t):a?.generation===r?a.warnings:[],s=i.map(e=>JSON.stringify(e));for(let e of o){let t=s.indexOf(JSON.stringify(e));t===-1?i.push(e):s.splice(t,1)}}return i}drawn(e,t,n,r){let i=this.of(e,t),a=r9(e,t);this.records.delete(a),this.records.set(a,{generation:n9(n.config),warnings:r});for(let e of this.records.keys()){if(this.records.size<=this.maxRecords)break;this.records.delete(e)}return JSON.stringify(i)!==JSON.stringify(r)}};const r9=(e,t)=>`${t}\0${e}`;var cne=class{queue=new V6;sessions=new V6;gathers=new V6;open=!0;inFlight=null;holder=null;queued=0;gathersInFlight=0;constructor(e){this.deps=e}take(e,{waited:t,gone:n},r){let i=this.deps.monotonic();return this.queued++,this.queue.run(`journals`,async()=>{if(this.queued--,this.refuseClosed(e),n())throw new ZK(e);let a=this.deps.monotonic();t(Math.round(a-i)),this.holder={verb:e,since:a};try{return await r({holds:t=>{let n={verb:e,commit:t};return this.inFlight=n,()=>this.commit(n)},landed:t=>t.finally(()=>this.refuseClosed(e))})}finally{this.holder=null}})}click(e,t,{placed:n,waited:r,gone:i,gathered:a},o,s){let c=this.deps.monotonic(),l=async()=>{if(n(Math.round(this.deps.monotonic()-c)),this.refuseClosed(e),i())throw new ZK(e);let t=this.deps.monotonic(),l=await o();a(Math.round(this.deps.monotonic()-t));let u=i();return this.take(e,{waited:r,gone:()=>!u&&i()},e=>s(l,e))};return t===null?l():this.sessions.run(t,l)}async gathering(e){this.gathersInFlight++;try{return await this.gathers.run(`gathers`,e)}finally{this.gathersInFlight--}}getStats(){let{holder:e,queued:t}=this;return{holder:e?.verb??null,heldMs:e===null?0:Math.round(this.deps.monotonic()-e.since),queued:t,gathers:this.gathersInFlight}}close(){this.open=!1,this.inFlight!==null&&(this.deps.log(`warn`,`journal: ${this.inFlight.verb} cut off by close, committing what landed`),this.commit(this.inFlight))}refuseClosed(e){if(!this.open)throw new XK(e)}commit(e){return this.inFlight===e?(this.inFlight=null,e.commit(),!0):!1}},lne=class{sessions=new Map;pending=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}clickArrived(e){this.pending.set(e,(this.pending.get(e)??0)+1),this.sessions.has(e)&&this.settle(e)}clickSettled(e){let t=this.pending.get(e)-1;t===0?this.pending.delete(e):this.pending.set(e,t),this.sessions.has(e)&&this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown&&!this.pending.has(e)?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;let t=0;for(let e of this.pending.values())t+=e;return{sessions:this.sessions.size,armed:e,pending:t}}dispose(){this.disposed=!0;for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null,closing:!1};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=256)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown&&!t.closing&&!this.disposed&&!this.pending.has(e)?ex(t.since,t.timeoutS):null;t.timer?.at!==n&&(this.disarm(t),n!==null&&(t.timer={at:n,clear:this.deps.clock.after(Math.max(0,(n-this.deps.now())*1e3),()=>this.fire(e),{unref:!0})}))}disarm(e){e.timer?.clear(),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now(),r={idleS:n-t.since,timeoutS:t.timeoutS,stillIdle:()=>this.sessions.get(e)===t&&!this.pending.has(e),closed:()=>{t.since=n,t.shown=!1}};t.closing=!0,this.deps.close(e,r).catch(t=>{r.closed(),this.deps.failed(e,t)}).finally(()=>{t.closing=!1,this.sessions.get(e)===t&&this.settle(e)})}};function une(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,paths:o,gates:s,host:c}=e,l=on(c),u=()=>LA(new Date(i.now())),d=new AbortController,f=!1,p=(t,n)=>e.daemonLog.log(t,f?`after close: ${n}`:n),m=new wQ(i),h=e.launcher({inherited:c.env,stats:m.launchStats,signal:d.signal,observeLifeline:e=>{p(e===null?`info`:`warn`,e===null?`launch lifeline running again`:`launch lifeline ${e}; the next launch starts another`),de.wakeWhere(`data`,()=>!0)}}),g=e.storage(p),_=new nJ(g.session),v=new lJ(_,p,g.history),y=Cr({...e.limits({startedAtMs:m.startedAt.getTime(),exit:a,launcher:h,log:p}),limitBytes:n}),b=new BQ,x=new ete,S=e.doctorStores,w=new jC({clock:i,counters:m,logger:p}),ee=new dj(p),T=new Tc({watchers:w,logger:p,clock:i}),te=T5({launcher:h,host:c,watchers:w,fileEvents:T,clock:i,logger:p,ledger:ee}),{gitProvider:E,usageStore:ne,tmuxService:D,hostService:re,managedStorage:ie}=te,O=new r7,ae=new eP,oe=new lne({clock:i,now:u,close:(e,t)=>N1(e,t,be),failed:(e,t)=>p(t instanceof XK?`info`:`error`,`menu-idle: close failed (session=${e}): ${C(t)}`)}),se=e.linkSigner,ce=new $s({supersede:(e,t)=>ie.supersede(e,t),launch:h.launch,state:_,log:p,now:u,clock:i}),le=new ine({edge:e.laneEdge(h,e=>de.following(e),d.signal),host:{bundle:t.path,node:t.node,socket:o.socket,preload:Yo(t.path,c)},state:_,log:p,now:u,defer:e=>void i.defer(e)}),ue=new Rte({edge:{run:(e,t,n)=>Ws(h,{socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>de.subscribe(e,t),sessionInPane:(e,t)=>de.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${bt(o.socket)}`,...[...t.node,t.path].map(bt),`url-handle`].join(` `),owner:o.socket,log:p}),de=new f3({render:(e,t,n)=>S3(xe,e,t,n),watch:(e,t)=>(0,Y.reaction)(()=>_.revision(e),t),lanes:e=>w3(xe,e),pin:e=>{let t=he.pin(e);return()=>{he.stopDrawing(e,`feed`),t()}},shown:e=>fe.shown(e.hints.tmux),watching:()=>fe.follow(),refreshes:()=>ee.totals(),periods:o3,clock:i,instant:u,log:p}),fe=new u7({clock:i,listPanes:e=>Ws(h,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,a7]),listClients:e=>Ws(h,{socket:e},`frames.visibility`,[`list-clients`,`-F`,o7]),sockets:()=>new Set(de.watched().flatMap(({req:e})=>pe(e))),onAnswer:(e,t)=>ue.answered(e,t),onChange:e=>de.wakeWhere(`visibility`,t=>pe(t).some(t=>e.has(t))),intervalMs:1e3,log:p});function pe({hints:{tmux:e}}){return e==null?[]:[e.socket]}let me=new sne,he=new t7({clock:i,launcher:h,stateDir:o.state,locations:l,env:c.env,sessionState:_,watchers:w,log:p,storage:ie,signer:se,gates:s,ledger:ee,fileEvents:T,declare:(e,t,n,r)=>pX(te,e,t,n,r),source:i7({providers:te,sessionState:_,history:e=>v.depth(e),navigation:(e,t)=>O.depth(e,_,s.state.gateFor(t))})},{budgetBytes:()=>j5(n),observers:{onReload:(e,t,n,r)=>{p(`info`,I5(e,n,r));for(let e of t)de.wake(e,`reload`)},onViewChanged:e=>de.wake(e,`data`)}});T.subscribe(e=>{switch(e.kind){case`period`:w.judge();return;case`caught-up`:he.reloadEvery({kind:`events-resumed`,since:e.since}),de.wakeWhere(`data`,()=>!0);return;case`moved`:de.wakeWhere(`data`,()=>!0);return}});let ge=60*1e3,_e=Q6({clock:i,targets:t.targets,intervalMs:ge,stat:e.stat,held:()=>ve.running(),exit:()=>a(0),log:p}),ve=Y6({clock:i,launcher:h,entryUrl:t.entryUrl,digest:t.digest,actsDir:w6(o.state,t.path),intervalMs:ge,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,gates:s,onApplied:()=>_e.checkNow(),log:p}),ye=new cne({log:p,monotonic:()=>i.monotonic()}),be={gates:s,sessionState:_,stateDir:o.state,locations:l,journalTurns:ye,clickLanded:e=>oe.clicked(e,u()),log:p,launcher:h,now:u,applyUpdate:()=>ve.act(),doctor:e.doctorEdge(h,e=>{let t=[e.projectDir,e.cwd,e.target.path];he.reload(...t,{kind:`doctor`});let n=he.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}},c),doctorStores:S,probes:b,clients:x,bundle:t.path,serving:()=>y.serving(),claudeInput:e.claudeInput(h),history:v,navigation:O,configFor:e=>he.getOrCreate(e.projectDir,e.cwd,e.target.path).state.config,reloadConfig:e=>he.reload(e.projectDir,e.cwd,e.target.path,{kind:`write`}),sourcesFor:e=>he.getOrCreate(e.projectDir,e.cwd,e.target.path).state.sources,links:se,runs:ce,lanes:{of:(e,t)=>T3(xe,e,t),clicked:(e,t,n)=>F3(xe,e,t,n)},views:{follow:(e,t)=>he.follow(e,t.projectDir,t.cwd,t.target.path)},diagnosticCopy:(e,t,n)=>he.drawnCopy(e,t,n)},xe={home:c.home,tmp:c.tmp,launcher:h,log:p,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:S,stats:m,handlerProbes:b,renderSightings:x,watcherRegistry:w,refreshLedger:ee,fileEvents:T,payloadProviders:te,sessionState:_,effectSessions:ae,menuIdle:oe,journalTurns:ye,linkSigner:se,runs:ce,laneSetups:le,tmuxStatusLines:ue,frameFeeds:de,renderWarnings:me,renderCache:he,updateWatch:ve,limits:y,verbCtx:be};return{stats:m,launcher:h,log:p,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(d.signal.throwIfAborted(),f6(xe,e,t,n,r)),reply:async(e,t,n,r)=>(d.signal.throwIfAborted(),p6(xe,e,t,n,r)),subscribe:(e,t)=>(d.signal.throwIfAborted(),de.subscribe(e,t)),reloadConfig:e=>{d.signal.throwIfAborted(),be.reloadConfig(e)},arm(){d.signal.throwIfAborted(),T.start(o.watchProbe),_e.arm(),ve.arm(),y.arm()},close(e){let t=[[`journalTurns close`,()=>ye.close()],[`tmuxStatusLines restore`,()=>ue.restoreAll(e)],[`launches abort`,()=>d.abort(Error(`the daemon closed`))],[`frameFeeds close`,()=>de.close()],[`menuIdle dispose`,()=>oe.dispose()],[`updateWatch close`,()=>ve.close()],[`binaryWatch close`,()=>_e.close()],[`limits disarm`,()=>y.disarm()],[`renderCache close`,()=>he.close()],[`gitService close`,()=>E.close()],[`usageStore close`,()=>ne.close()],[`tmuxService close`,()=>D.close()],[`hostService close`,()=>re.close()],[`runs close`,()=>ce.close()],[`managedStorage close`,()=>ie.close()],[`fileEvents close`,()=>T.close()],[`watcherRegistry close`,()=>w.closeAll()],[`sessionState close`,()=>_.close()]];for(let[e,n]of t)try{n()}catch(t){p(`warn`,`${e} failed: ${t.message}`)}return f=!0,h.settled()}}}function dne(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e)){if(typeof t!=`object`||!t||Array.isArray(t))return!1;for(let e of Object.values(t))if(typeof e!=`string`)return!1}return!0}var fne=class{clearTimer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t,n=500,r=Pe){this.filePath=e,this.clock=t,this.debounceMs=n,this.logger=r,this.writingPath=`${e}.writing`}load(){let e;try{e=l.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return dne(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,this.schedule()}schedule(){this.clearTimer!==null||this.writing||(this.clearTimer=this.clock.after(this.debounceMs,()=>{this.clearTimer=null,this.write()},{unref:!0}))}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=this.clock.monotonic(),r=JSON.stringify(e),i=this.writingPath;this.writing=!0;let a=this.clock.monotonic()-n;try{await l.promises.mkdir(E.dirname(this.filePath),{recursive:!0});let o=await l.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}let s=!1;if(t===this.generation)try{await l.promises.rename(i,this.filePath),s=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){s||await l.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${s} took=${Math.round(this.clock.monotonic()-n)}ms held=${Math.round(a)}ms`);return}this.saved(r,e,n,a),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.clearTimer?.(),this.clearTimer=null,this.pending===null)return;let e=this.pending,t=this.clock.monotonic();try{l.mkdirSync(E.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);l.writeFileSync(n,r,{mode:384}),l.chmodSync(n,384),l.rmSync(this.writingPath,{force:!0}),l.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,this.clock.monotonic()-t),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${Math.round(this.clock.monotonic()-n)}ms held=${Math.round(r)}ms`)}};function pne(e,t,n){return{session:new fne(e.sessionState,n,500,t),history:AJ(e.settingsHistory,t)}}function i9(e,t,n){for(let r of(t??``).split(E.delimiter)){if(!E.isAbsolute(r))continue;let t=E.join(r,e);if(n(t))return t}return null}function a9(e,t){try{return l.accessSync(e,t),l.statSync(e).isFile()}catch{return!1}}function mne(e){try{return l.realpathSync(e)}catch{return E.resolve(e)}}function hne(e,t,n){let r=i9(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:E.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const o9=2e3;async function s9(e,t,n,r){let i=await Ws(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function c9(e,t){if(t.ok)return t.stdout;let n=t.error??[t.reason,t.stderr.trim(),t.stdout.trim()].filter(e=>e!==``).join(`: `);throw Error(`${e} failed (${n})`)}function gne(e){try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`ok`in t&&t.ok===!1&&`reason`in t&&typeof t.reason==`string`)return`detail`in t&&typeof t.detail==`string`?`${t.reason}: ${t.detail}`:t.reason}catch{}return null}const _ne=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function vne(e,t){return e.split(`
|
|
493
|
+
`).flatMap(e=>{let[n,...r]=e.trim().split(` `);return _ne.exec(r.join(` `))?.[1]===t?[n]:[]})}const yne=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function bne(e,t,n){for(let r of KJ(GJ(e),t)){if(r.command.split(` `).some(e=>yne.test(e)))return!0;if(r.pid===n)return!1}return!1}const xne=[`import ctypes, json, struct, sys`,`libc = ctypes.CDLL(None)`,`mib = (ctypes.c_int * 3)(1, 49, int(sys.argv[1]))`,`size = ctypes.c_size_t(0)`,`if libc.sysctl(mib, 3, None, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`buf = ctypes.create_string_buffer(size.value)`,`if libc.sysctl(mib, 3, buf, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`raw = buf.raw[:size.value]`,`argc = struct.unpack_from('i', raw)[0]`,`rest = raw[4:]`,`end = rest.index(b'\\0')`,`exe = rest[:end].decode('utf-8', 'surrogateescape')`,`rest = rest[end:].lstrip(b'\\0')`,`words = [w.decode('utf-8', 'surrogateescape') for w in rest.split(b'\\0')]`,`end = words.index('', argc) if '' in words[argc:] else len(words)`,`print(json.dumps({'executable': exe, 'argv': words[:argc], 'env': words[argc:end]}))`].join(`
|
|
494
|
+
`);async function Sne(e,t){if(process.platform===`linux`)return{executable:await l.promises.readlink(`/proc/${t}/exe`),argv:(await l.promises.readFile(`/proc/${t}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await l.promises.readFile(`/proc/${t}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let n=c9(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,xne,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function l9(e,t,n){return c9(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function u9(e,t){let n=await Ws(e,t,`lane.tmux`,[`display`,`-p`,`-t`,t.pane,`#{pane_pid} #{pane_current_path}`]);if(n.kind!==`ok`)throw Error(n.reason);let[r=``,i=``]=n.stdout.trimEnd().split(` `),a=(await l9(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function Cne(e,t){let{panePid:n,cwd:r,foreground:i}=await u9(e,t),a=await l9(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await Sne(e,i),s=GJ(a).get(i)?.ppid;if(s===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);return{pid:i,executable:await l.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:s,fromShell:i!==n,attached:bne(a,i,n)}}function wne(e,t,n,r){let i=e=>A(r,e,n);return{claudeInput:d$(e),barPanes:async t=>vne(await s9(e,t,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_start_command}`]),t.pane),openBarPane:async(t,n,r)=>(await s9(e,t,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,t.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(r).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...n])).trim(),closePane:async(t,n)=>void await s9(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void c9(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:MJ(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>l.existsSync(e),presence:wz,paneClaude:t=>Cne(e,t),paneDir:async(t,n)=>{let a=r.now()+o9;for(;;){let o=await u9(e,t);if(o.foreground===n){if(o.cwd===``)throw Error(`tmux read no directory for pane ${t.pane}`);return o.cwd}if(r.now()>a)throw Error(`the shell in pane ${t.pane} (pid ${n}) did not take its terminal back within ${o9/1e3} s`);await i(100)}},launcherNode:e=>hne(e,e=>a9(e,l.constants.X_OK),mne),onPath:(e,t)=>{let n=i9(e,t,e=>a9(e,l.constants.X_OK));return n===null?null:l.realpathSync(n)},followed:async(e,n,a)=>{let o=r.now()+a;for(;!t(e).has(n);){if(r.now()>o)return!1;await i(200)}return!0},moduleGraph:async(t,n,r)=>{let i=await e.launch({bin:t,args:[n,r],timeoutMs:2e4,category:`lane.process`}),a=!i.ok&&i.reason===`non-zero`?gne(i.stdout):null;return a===null?(c9(`reading ${r}'s module graph`,i),{ok:!0}):{ok:!1,reason:a}},terminate:e=>{n.throwIfAborted();try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=r.now()+t;for(;ws(e);){if(r.now()>n)return!1;await i(100)}return!0},typeShellLine:async(t,n)=>void await s9(e,t,l$(t.pane,`cc-candybar-lane`,[]),n)}}const Tne=/^[0-9a-f]{64}$/;function d9(e,t){return se(`sha256`,e).update(JSON.stringify([t.sessionId,t.action,t.declaration,t.evaluated])).digest()}function Ene(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);return{sign:t=>d9(e,t).toString(`hex`),verify:(t,n)=>Tne.test(n)?ue(Buffer.from(n,`hex`),d9(e,t)):!1}}function f9(e){return E.join(e,`link.key`)}function p9(e){let t,n=()=>t??=Dne(e);return{sign:e=>n().sign(e),verify:(e,t)=>n().verify(e,t)}}function Dne(e){let t;try{t=l.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;One(e),t=l.readFileSync(e)}if(t.length!==32)throw Error(`link key ${e} holds ${t.length} bytes, not 32: remove it and a new one is made (links drawn before then stop working)`);return Ene(t)}function One(e){l.mkdirSync(E.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${ce(6).toString(`hex`)}`;l.writeFileSync(t,ce(32),{mode:384,flag:`wx`});try{l.linkSync(t,e)}catch(e){if(e.code!==`EEXIST`)throw e}finally{l.unlinkSync(t)}}function kne(e,t,n){return{daemonLog:t,launcher:e=>ft(e,n),storage:t=>pne(e,t,n),doctorStores:KZ(e.state),doctorEdge:iQ,claudeInput:d$,laneEdge:(e,t,r)=>wne(e,t,r,n),linkSigner:p9(f9(e.state)),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>kr(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),fetch,stat:l.statSync}}const Ane=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function m9(e){if(e===void 0)return;let t=H.parse(e);if(t.isDefault)return;let n=t.fixedValue;if(n!==void 0)return n.hex;let r=t.type===V.STANDARD&&t.number!==void 0?Ane[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const jne={bold:`bold`,dim:`dimColor`,italic:`italic`,underline:`underline`,strike:`strikethrough`,reverse:`inverse`,blink:null,blink2:null,conceal:null,underline2:null,frame:null,encircle:null,overline:null};function Mne({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=m9(t),o=m9(n),s={};for(let e of r){let t=jne[e];if(t===null)throw Error(`frames: the band cannot draw ${e} text`);s[t]=!0}return{text:e,...a!==void 0&&{color:a},...o!==void 0&&{backgroundColor:o},...s,...i!==void 0&&{href:i}}}function Nne(e){return{ok:!0,band:e.rows.map(e=>OP(e).map(Mne))}}function Pne(e){return _P(Nne,e)}const Fne={band:e=>JSON.stringify(Pne(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:y7(e)})};function h9(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}function Ine(e,t){t.allowHalfOpen=!1;let n=e.clock.monotonic();e.stats.inFlight++;let r=!1,i=!0,a=()=>{i&&(i=!1,e.stats.inFlight--)},o=(n,i,a)=>{if(r){i!==null&&e.log(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}r=!0,c();let o=i===null?void 0:()=>e.exit(i);try{t.end(Mn(n),e=>{e??a(),o?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),o?.()}},s=!1,c=e.clock.after(200,()=>{s=!0,e.stats.requestsTimedOut++,o({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,y3)}),l=Pn(r=>{e.handle(r,()=>s,n,()=>t.destroyed).then(e=>e.kind===`reply`?o(e.resp,e.exitAfterFlush,e.delivered):u(e.sessionId,e.lane)).catch(t=>{e.log(`error`,`handler threw: ${C(t)}`),o(b3(t),null,y3)})},t=>{e.log(`warn`,`frame parse failed: ${t.message}`),o({ok:!1,error:t.message,code:`BAD_REQUEST`,daemonV:3},null,y3)}),u=(n,i)=>{if(r||t.destroyed)return;c(),a(),t.off(`data`,l);let o=h9(t),s=e.subscribe(n,{lane:i,frame:(e,t)=>o(Nn(Fne[i](e,t))),refused:e=>t.end(Mn(e)),drawing:()=>!0});r=!0,t.on(`close`,s)};t.on(`data`,l),t.on(`error`,t=>{e.log(`warn`,`socket error: ${t.message}`)}),t.on(`close`,()=>{c(),a()})}let g9=null,_9=null,v9=null,y9=null;function b9(){if(y9===null)throw Error(`runDaemon has not started`);return y9}function x9(e,t){b9().log.log(e,t)}function Lne(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:zt(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function Rne(e){let n=an(e.host);y9={world:e,paths:n,log:new Bs(n.log,e.clock)},t.on(`uncaughtException`,e=>{x9(`error`,`uncaughtException: ${e.stack||e.message}`),T9(1)}),t.on(`unhandledRejection`,e=>{x9(`error`,`unhandledRejection: ${String(e)}`),T9(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{x9(`info`,`received ${e}, shutting down`),T9(0)});zne().catch(S9)}function S9(e){x9(`error`,`refusing to boot: ${C(e)}`),T9(1)}async function zne(){let{world:e,paths:n,log:r}=b9(),{host:i}=e,a=hr(i.env);g9=await bs(t.pid,t=>vs(t,e.launcher.launch));let o=await As(Ms(e,g9,n.registry));if(!o.decision.allow){x9(`warn`,`fork-bomb breaker: ${o.decision.reason}; refusing to boot`),T9(1);return}_9=o.registryPath,l.mkdirSync(n.state,{recursive:!0}),Jt(n.socket);let s=une({...kne(n,r,e.clock),bundle:Lne(),host:i,paths:n,memoryLimitBytes:a,registryUrl:i.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:Cz(),exit:T9});v9=s,Cs({clock:e.clock,anchor:Ss(i.env),isAlive:ws,onOrphaned:e=>{x9(`info`,`parent watchdog: ${e}; shutting down`),T9(0)}}),C9(s,de.createServer(e=>Ine(s,e)),n.socket,!1)}function C9(e,n,r,i){n.removeAllListeners(`error`),n.removeAllListeners(`listening`),n.once(`error`,a=>{if(a.code!==`EADDRINUSE`){x9(`error`,`server error: ${a.message}`),T9(1);return}if(i){x9(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}Bne(e,n,r).catch(S9)}),n.listen(r,()=>Vne(e,r))}async function Bne(e,n,r){let i=await ms(hs(Yt(r)),(t,n)=>ys(t,n,{readStartTime:t=>vs(t,e.launcher.launch),pidAlive:ws}));if(i.kind===`attach-and-exit`){x9(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}x9(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{l.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){x9(`error`,`cannot unlink stale socket ${r}: ${e.message}`),T9(1);return}}C9(e,n,r,!0)}function Vne(e,n){let r=gs(n);if(r.kind!==`present`){x9(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),T9(0);return}Une(n);try{l.chmodSync(n,384)}catch(e){x9(`warn`,`chmod socket failed: ${e.message}`)}x9(`info`,`daemon up: pid=${t.pid} v=3 sock=${n} heapCap=${mr(fe.getHeapStatistics().heap_size_limit)}MB memoryLimit=${mr(e.memoryLimitBytes)}MB`),Rr(b9().paths.spawnBackoff),e.arm(),Hne(n,r.identity)}function Hne(e,n){_s({bound:n,myPid:t.pid,readIdentity:()=>gs(e),readLease:()=>hs(Yt(e)),shutdown:e=>T9(e),log:x9,clock:b9().world.clock}).arm()}function Une(e){let n=uee(Yt(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:g9});n!==null&&x9(`warn`,`lease write failed: ${n}`)}const Wne=e=>(t,n,r)=>Us(e,{socket:t},`tmux-status`,n,r);let w9=!1;function T9(e){w9||(w9=!0,b9().world.clock.after(500,()=>t.kill(t.pid,`SIGKILL`)),v9?.close(Wne(b9().world.launcher)),dee(b9().paths.lease,t.pid),_9!==null&&js(_9,t.pid,Os,e=>l.unlinkSync(e)),t.exit(e))}const Gne={connectMs:200,budgetMs:500};async function Kne(e,t,n){return qne(t,await Jne(e,t),n.includes(`--json`))}function qne(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
|
|
495
|
+
`:Yne(t.value),stderr:``,code:0}:{stdout:``,stderr:`${e}: ${Wn(t)}\n`,code:1}}function Jne(e,t){return Ln(e,()=>({kind:`debug`,what:t}),Gne,e=>`debug`in e?e.debug:void 0)}function Yne(e){switch(e.what){case`vars`:return Xne(e.vars);case`segments`:return Zne(e.segments);case`config`:return Qne(e.config);default:return e}}function Xne(e){if(e.length===0)return`no variables (DSL not active)
|
|
496
|
+
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${ere(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${$ne(a.value)}${e}${o}`)}return t.join(`
|
|
497
497
|
`)+`
|
|
498
|
-
`}function
|
|
498
|
+
`}function Zne(e){if(e.length===0)return`no segments (DSL not active)
|
|
499
499
|
`;let t=[`segments (${e.length})`,``];for(let n of e){t.push(` ${n.name}`),n.description!==null&&t.push(` shows ${n.description}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`);for(let{id:e,lastRender:r}of n.placements)r!==null&&t.push(` last ${e}: ${r}`)}return t.join(`
|
|
500
500
|
`)+`
|
|
501
|
-
`}function
|
|
501
|
+
`}function Qne(e){return e===null?`config: DSL not active
|
|
502
502
|
`:JSON.stringify(e,null,2)+`
|
|
503
|
-
`}function
|
|
503
|
+
`}function $ne(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function ere(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function tre(){let e=rre();return e===null?null:l.readFileSync(e,`utf-8`)}function nre(){let e;try{e=tre()}catch(e){return{stdout:``,stderr:`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`,code:2}}return e===null?{stdout:``,stderr:"schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n",code:2}:{stdout:e,stderr:``,code:0}}function rre(){let e=E.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let r=E.dirname(E.resolve(n));for(;;){let t=E.join(r,e);if(l.existsSync(t))return t;let n=E.dirname(r);if(n===r)return null;r=n}}const E9=5e3;function ire(e,t){return{ms:t,signal:gt(e,t)}}function are(e,t){return t.length===0?[]:[`source${t.length===1?``:`s`} still running after ${e.ms} ms, drawn as pending: ${t.join(`, `)}`]}function D9({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=VY(a,o);return{drawn:i3(n,r,i,{...ore(t,a,e.at(-1)??null,s),today:sre},c,a),opts:c}}function ore(e,t,n,r){let i=`/home/tester`,a=Math.floor(r),o=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,s={current_dir:`${i}/code/cc-candybar/src`,project_dir:`${i}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:o,version:`1.15.0`,home:i,cwd:`${i}/code/cc-candybar/src`,transcript_path:`${i}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:s,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,tracking:`tracked`,stash:1,status:`dirty`,operation:`rebase`,committedAt:a-780},session:{cost:.39,tokens:241400},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:a+2*3600},weekly:{percentage:21,resetsAt:a+5*86400},cache:{expiresAt:a+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:bI(4e5,1e6),...HY(t),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:zx(()=>!0),themeDefault:t.theme.kind===`decided`?{differs:!0,theme:t.theme.name}:{differs:!1},resumeCommand:BY(s,o,void 0),configPath:n??`${i}/.config/cc-candybar/config.json5`,...vX(Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]),()=>I)}}const sre={cost:12.5,tokens:34e5};function cre(e,t){let n=YH(e);return n!==null&&t.push(n),e.kind===`chain`?e.layers:[]}async function lre(e,n,r,i=t.cwd(),a=E9){let o=[],s=PN(i,r,e.host.home)??null,c=on(e.host),u=WH(c,OU(Ut(e.host)).read(),i,i,s??void 0);o.push(...RH(u.repos));let d=s===null?cre(u,o):[UH(s)];if(s!==null){let e;try{e=l.statSync(s,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:s,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:s,message:`not a file`}}let f=ZH(c,i,i);f!==null&&o.push(f);try{return{kind:`clean`,layers:d,warnings:o,rendered:await fre(e,n,d,{repo:u.repos.plugins},i,o,a)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&d.some(e=>e.path===t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof ib&&o.push(...e.warnings),{kind:`fatal`,layers:d,message:e instanceof ib||e instanceof Error?e.message:String(e),warnings:o})}}async function ure(e,t,n,r,i,a,o=E9){let s=t.map(e=>e.path),c=AG(on(e.host),t,nK,{warned:e=>i.push(...e)},{...n,cwd:r});LG(c.dropped);let{config:l}=c,u=new $C(e.clock),d=new Aj(e.launcher,u,l.globals.default_empty_value??``,new nJ,null,void 0,void 0,void 0,e.host.env);try{let t=H4(l,d,{cwd:r,signer:p9(f9(Ut(e.host)))});i.push(...t.loadWarnings);let n=dK(l,()=>null,()=>!1),f=ire(e.clock,o);return D9({layers:s,config:l,compiled:t,store:u,registry:d},n,200,a),await d.inFlight(f.signal),{settle:f,layers:s,droppedPlugins:[...c.installed.dropped,...c.layers.flatMap(e=>e.plugins.dropped)],config:l,compiled:t,store:u,registry:d}}catch(e){throw d.dispose(),e}}async function dre(e,t,n,r){let i=new Map,a=new Set,o=e=>{switch(e.kind){case`rule`:i.set(`${e.slot} rule`,e.message);return;case`when`:i.set(e.where,e.error);return;case`refresh`:i.set(`variable "${e.variable}"`,`cannot refresh: ${e.error}`);return;default:}},{config:s,compiled:c,store:l,registry:u,settle:d}=e,{drawn:f,opts:p}=D9(e,t,n,r);for(let e of are(d,await u.inFlight(d.signal)))a.add(e);let{frame:m}=a3(s,c,l,u,f,r,p,{onSegmentError:(e,t)=>i.set(`segment "${e}"`,t),onRenderWarning:o},t);return{rendered:m,failures:i,advisories:a}}async function fre(e,t,n,r,i,a,o){let s=LA(new Date(e.clock.now())),c=await ure(e,n,r,i,a,s,o),{config:l}=c;try{t.state.gateFor(l),t.config.gateFor(l);let e=hS(null,l.globals.preset,l.presets),n=async(e,t)=>{let n=dK(l,t=>t===`preset`?e:null,()=>t),r;try{r=await dre(c,n,200,s)}catch(e){r={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...r}},r=await n(e,!1),i=[r,await n(e,!0)];for(let t of mS(l.presets))t!==e&&i.push(await n(t,!1),await n(t,!0));let o=t=>{let n=new Map;for(let e of i)for(let r of t(e)){let t=n.get(r)??new Map;t.set(e.preset,(t.get(e.preset)??new Set).add(e.customized)),n.set(r,t)}return[...n].map(([t,n])=>n.get(e)?.has(!1)?t:`${t} (under ${[...n].map(([t,n])=>[...t===e?[]:[`preset "${t}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};a.push(...o(e=>e.advisories));let u=o(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=r.rendered,f=c.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
|
|
504
504
|
`)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
|
|
505
|
-
`));return d}finally{c.registry.dispose()}}function O9(e){return e.map(e=>`warning: ${e}\n`).join(``)}function
|
|
506
|
-
`))a[e]=void 0;i(a,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,t,r),i(a,`-C`,r,`sparse-checkout`,`set`,`--no-cone`,`/${
|
|
507
|
-
`));let c=o.map(e=>{let n=E.basename(e),r=E.join(t,n);return{folder:e,name:n,target:r,placed:
|
|
505
|
+
`));return d}finally{c.registry.dispose()}}function O9(e){return e.map(e=>`warning: ${e}\n`).join(``)}function pre(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${zN(e.layers.map(e=>e.path))}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${TP(e.rendered)}\n`:``),stderr:O9(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:O9(e.warnings)+`✗ ${zN(e.layers.map(e=>e.path),`<default>`)}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const k9=`--render`,A9=`Usage: cc-candybar check [${k9}] [config-file]\n`;function mre(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==k9);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${A9}`}:n.length>1?{kind:`usage`,message:`check: expected at most one path\n${A9}`}:{kind:`run`,target:n[0],render:t.includes(k9)}}async function j9(e,n){let r=mre(e),i=t.cwd();return r.kind===`usage`?{stdout:``,stderr:r.message,code:2}:pre(await lre(n,Cz(),RN(r.target,n.host,i).path,i),r.render)}const hre=/^[a-z][a-z0-9+.-]*:\/\//i,gre=/^[^@\s/]+@[^:\s/]+:/,_re=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function vre(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function yre(e,t,n,r){let i=NN(t,e,n);if(r(i))return{kind:`path`,dir:i};if(hre.test(e)||gre.test(e))return{kind:`git`,url:e,shown:vre(e)};let a=_re.exec(e);if(a){let e=`https://github.com/${a[1]}.git`;return{kind:`git`,url:e,shown:e}}return{error:`"${e}" is not a directory, a GitHub repo slug (owner/repo) or a git URL`}}function bre(e,t){let n=E.join(e,EH),r=OH(n);if(`error`in r)throw Error(`${t}: could not list ${EH}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${EH}/<name>/${UV}`);return r.folders.map(e=>E.join(n,e,UV))}function xre(e,t,n,r){let i=(r,...i)=>{let a=e.launchSync({bin:`git`,args:i,envOverlay:r,category:`plugin.git`});if(!a.ok)throw Error(`git ${i.map(e=>e===t?n:e).join(` `)} failed (${a.reason}): ${a.stderr.trim()||a.error||``}`);return a.stdout},a={GIT_TERMINAL_PROMPT:`0`};for(let e of i(a,`rev-parse`,`--local-env-vars`).split(`
|
|
506
|
+
`))a[e]=void 0;i(a,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,t,r),i(a,`-C`,r,`sparse-checkout`,`set`,`--no-cone`,`/${EH}/`)}function Sre({host:e,launcher:t},n,r){switch(n.kind){case`path`:return r(n.dir);case`git`:{let i=l.mkdtempSync(E.join(e.tmp,`cc-candybar-plugin-`));try{return xre(t,n.url,n.shown,E.join(i,`repo`)),r(E.join(i,`repo`))}finally{l.rmSync(i,{recursive:!0,force:!0})}}}}function Cre(e){let t;try{t=l.lstatSync(e)}catch(e){if(e.code===`ENOENT`)return`installed`;throw e}if(t.isDirectory())return`updated`;if(t.isSymbolicLink())return`replaced`;throw Error(`${e} is a file, not a plugin folder: move it, then install again`)}function wre(e,t,n,r){switch(r){case`updated`:l.renameSync(E.join(e,UV),E.join(t,UV));return;case`replaced`:l.renameSync(t,n),l.renameSync(e,t);return;case`installed`:l.renameSync(e,t);return}}function Tre(e,t,n,r){let i=bre(e,n);l.mkdirSync(t,{recursive:!0});let a=l.mkdtempSync(E.join(t,`.install-`));try{let o=i.map(e=>{let t=E.join(a,E.basename(E.dirname(e)));l.mkdirSync(t);try{l.copyFileSync(e,E.join(t,UV))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),s=OG(o.map(e=>GV(E.join(e,UV),`plugins`)),nK,{root:e,git:!1},r);if(s.length>0)throw Error(s.map(e=>`${n}: ${E.join(EH,E.relative(a,e.path))} would not load: ${e.reason.split(a).join(E.join(n,EH))}`).join(`
|
|
507
|
+
`));let c=o.map(e=>{let n=E.basename(e),r=E.join(t,n);return{folder:e,name:n,target:r,placed:Cre(r)}}),u=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)wre(e,n,E.join(a,`.replaced-${t}`),r),u.push(t)}catch(e){throw Error(`${e.message} (placed before it: ${u.join(`, `)||`none`})`)}return c.map(({target:e,placed:t})=>({path:E.join(e,UV),placed:t}))}finally{l.rmSync(a,{recursive:!0,force:!0})}}function Ere(e,t){let[n,r,...i]=e;if(n!==`install`||r===void 0||i.length>0)return console.error(`Usage: cc-candybar plugin install <path | owner/repo | git URL>`),2;let a=yre(r,process.cwd(),t.host.home,e=>SC(e)!==null);if(`error`in a)return console.error(`plugin install: ${a.error}`),2;try{let e=a.kind===`path`?a.dir:a.shown,n=Sre(t,a,n=>Tre(n,TH(on(t.host)),e,t.host.home));for(let{path:t,placed:r}of n)console.log(`${r} plugin ${E.basename(E.dirname(t))} → ${t} (from ${e})`);return 0}catch(e){return console.error(`plugin install: ${e.message}`),1}}function M9(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
|
|
508
508
|
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`busy`:return{output:`
|
|
509
|
-
`,kick:!1,debug:`daemon busy (${e.message}) — not kicking`};case`permanent`:return{output:fP(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function N9(e,t){if(e!==void 0&&/^\+?\d+$/.test(e)){let t=Number(e);if(t>0&&t<=4294967295)return t}if(t&&t>0)return t}const
|
|
510
|
-
`).join(` — `)};return{clients:e,rateLimits:e,transcripts:e,frames:e,widths:e,serving:e,stores:{marks:e,clicked:e,postMortemsRead:e}}}return{clients:
|
|
511
|
-
`)||null),warning:a.warning,unused:o.unused,config:o.config}}function
|
|
512
|
-
`;function
|
|
513
|
-
`);return{bytes:`\x1B[?2026h`+t.map((e,t)=>`\x1b[${t+1}H${e}[0m[K`).join(``)+`\x1B[J\x1B[?2026l`,rows:t.length}}const U9=5e3,W9=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function
|
|
514
|
-
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?c7(e,s7(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function G9(e,t,n){let[r,i]=await Promise.all([Ws(e.launcher,t,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${n}},#{==:#{pane_id},${t.pane}}}`,`-F`,a7]),Ws(e.launcher,t,`bar-pane.tmux`,[`list-clients`,`-F`,o7])]);return r.kind===`ok`?i.kind===`ok`?{kind:`ok`,placement:
|
|
509
|
+
`,kick:!1,debug:`daemon busy (${e.message}) — not kicking`};case`permanent`:return{output:fP(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function N9(e,t){if(e!==void 0&&/^\+?\d+$/.test(e)){let t=Number(e);if(t>0&&t<=4294967295)return t}if(t&&t>0)return t}const Dre=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function P9(e,t,n){let{env:r}=e;return{termCols:N9(r.COLUMNS,n.columns),termRows:N9(r.LINES,n.rows),ssh:Dre.some(e=>(r[e]??``)!==``),tmux:mc(r),configEnv:IN(e,t),claudeConfigDir:Co(r,t),terminalEnv:mn(r)}}function F9(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function Ore(e){let t=kQ(e,[`bundle`,`clients`]);if(t!==null)return{kind:`failed`,reason:t};if(typeof e.bundle!=`string`)return{kind:`failed`,reason:`the running daemon (${e.version}) reported its bundle as ${JSON.stringify(e.bundle)}`};let n=F9(e);return n.every(e=>typeof e.ago==`number`&&typeof e.sessionId==`string`)?{kind:`ok`,value:{bundle:e.bundle,clients:n.map(e=>({client:In(e.client)??null,sessionId:e.sessionId,ago:e.ago}))}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported clients without their age or session: ${JSON.stringify(e.clients)}`}}const kre=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},Are=e=>{let t=e??{};if(t.kind===`unmeasured`)return!0;let n=t.charge;return t.kind===`measured`&&typeof t.rss==`number`&&typeof t.heapTotal==`number`&&typeof n?.bytes==`number`&&(n.kind===`charged`&&(n.measure===`phys_footprint`||n.measure===`rss`)||n.kind===`stand-in`&&typeof n.unread==`string`&&Number.isFinite(n.gap))};function I9(e,t){let n=e;if(n?.kind===`failed`&&typeof n.reason==`string`)return{kind:`failed`,reason:n.reason};if(n?.kind!==`ok`)return{kind:`misshapen`,reason:`is not an answer`};let r=t(n.value);return r.kind===`ok`?r:{kind:`misshapen`,reason:r.reason}}function jre(e){let t=kQ(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=I9(n?.postMortems,e=>Array.isArray(e)&&e.every(kre)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&Are(n.memory)&&typeof n.limit==`number`&&r.kind!==`misshapen`?{kind:`ok`,value:{...n,postMortems:r}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported itself as ${JSON.stringify(e.daemon)}`}}function L9(e,t,n){let r=kQ(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=F9(e);return i.every(t)?{kind:`ok`,value:i}:{kind:`failed`,reason:`the running daemon (${e.version}) reported its renders without ${n} — restart it on this build: ${JSON.stringify(e.clients)}`}}const R9=e=>Xee.includes(e.role),Mre=e=>L9(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&Zee.includes(e.rateLimits),`the rate-limit windows they carried`),Nre=e=>L9(e,e=>{let t=e.transcript;return typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof t?.path==`string`&&typeof t.answered==`boolean`},`their transcripts`),Pre=e=>L9(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&R9(e)&&YP.includes(e.frame),`what they drew and from which project`),Fre=e=>L9(e,e=>typeof e.sessionId==`string`&&typeof e.ago==`number`&&R9(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function z9(e,t,n){let r=e.doctorStores?.[t],i=I9(r,n);return i.kind===`misshapen`?{kind:`failed`,reason:`the running daemon (${e.version}) reported its ${t} as ${JSON.stringify(r)}, which ${i.reason}`}:i}function Ire(e){let t=kQ(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:z9(e,`marks`,PJ),clicked:z9(e,`clicked`,LJ),postMortemsRead:z9(e,`postMortemsRead`,VZ)}}async function Lre(e){let t=await OQ(e);if(t.kind!==`ok`){let e={kind:`failed`,reason:Wn(t).split(`
|
|
510
|
+
`).join(` — `)};return{clients:e,rateLimits:e,transcripts:e,frames:e,widths:e,serving:e,stores:{marks:e,clicked:e,postMortemsRead:e}}}return{clients:Ore(t.value),rateLimits:Mre(t.value),transcripts:Nre(t.value),frames:Pre(t.value),widths:Fre(t.value),serving:jre(t.value),stores:Ire(t.value)}}const Rre=` (fix: click the settings menu (${Zr} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,zre=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${Zr} by default) › 🧰 tools › 🩺 doctor`;function Bre({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:Rre}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${zre}\n`)}function Vre({host:e,launcher:t,clock:n},r){let i={clock:n,launcher:t,locations:on(e),env:e.env,sessionState:new nJ,storage:M5,signer:p9(f9(Ut(e))),gates:Cz(),stateDir:Ut(e)},a=X5(r.projectDir,r.cwd,r.target.path,i),o=a.state??Z5(r.cwd,a.repos.plugins,i);return o.registry.dispose(),{layers:a.layers,error:a.error??(o.dropped.map(e=>e.message).join(`
|
|
511
|
+
`)||null),warning:a.warning,unused:o.unused,config:o.config}}function Hre(e,t,n){return n.kind===`failed`?n:GZ(e,n.value.bundle,HJ(t,n.value.clients).map(({client:e})=>e))}function Ure(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:HJ(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function Wre(e,t){return t.kind===`failed`?t:{kind:`ok`,value:HJ(e,t.value).map(e=>e.transcript)}}function Gre(e,t){return t.kind===`failed`?t:{kind:`ok`,value:WJ(e,t.value)}}function Kre(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:bQ(e.sessionId,HJ(e,t.value))}async function qre(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=P9({env:r,home:e.home},i,a()),u=VJ(r.CLAUDE_CODE_SESSION_ID);s={...await xQ(e,l,{projectDir:UJ(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,target:RN(o,{env:r,home:e.home},i)},()=>null,c.serving,Ure(u,c.rateLimits,wo(l.claudeConfigDir,e.home)),Wre(u,c.transcripts),u,Gre(u,c.frames),Kre(u,c.widths,l.termCols??null),c.stores),urlHandler:await GQ(t),install:Hre(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=RF(s);return{stdout:c.map(Bre).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function Jre(){if(t.stderr.isTTY)return t.stderr;let e;try{e=g(`/dev/tty`,`r+`)}catch{return{}}let n=new ve(e),{columns:r}=n;return n.destroy(),{columns:r}}const B9=`Usage: cc-candybar doctor [config-file]
|
|
512
|
+
`;function Yre(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`));return t.length>0?{kind:`usage`,message:`doctor: unknown option ${t.join(` `)}\n${B9}`}:n.length>1?{kind:`usage`,message:`doctor: expected at most one config file\n${B9}`}:{kind:`run`,configFile:n[0]}}async function Xre(e,n){let r=Yre(e);return r.kind===`usage`?{stdout:``,stderr:r.message,code:2}:await qre(iQ(n.launcher,e=>Vre(n,e),n.host),YQ(n.launcher,n),()=>Lre(n),n.host.env,t.cwd(),Jre,r.configFile)}function Zre(e){return!e.ok&&e.code!==`RENDER_FAILED`}function Qre(e,t,n,r,i){let a=null,o=e=>{a===null&&(a=e,s.destroy(),i(e))},s=de.createConnection({path:e}),c={v:3,kind:`subscribe`,sessionId:t,lane:n};return s.once(`connect`,()=>s.write(Mn(c))),s.on(`data`,Pn(e=>{let t=e;Zre(t)?o({kind:`refused`,resp:t}):r(t)},e=>o({kind:`failed`,error:e}))),s.on(`error`,e=>o({kind:`failed`,error:e})),s.on(`close`,()=>o({kind:`closed-there`})),{close:()=>o({kind:`closed-here`})}}function V9(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(2e3,e*2)}}function $re(e){switch(e.kind){case`failed`:return{kind:`reconnect`,reason:`stream failed (${e.error.message})`,kick:!0};case`closed-there`:return{kind:`reconnect`,reason:`daemon closed the stream`,kick:!1};case`refused`:return e.resp.code===`SWITCHED_OFF`?{kind:`off`,resp:e.resp}:e.resp.code===`TIMEOUT`?{kind:`reconnect`,reason:`the daemon was too busy to open the stream (${e.resp.error})`,kick:!1}:e.resp.code===`BAD_REQUEST`?{kind:`reconnect`,reason:`the daemon does not take subscribe (${e.resp.error}); it restarts on the new build`,kick:!1}:e.resp.code===`VERSION_MISMATCH`&&e.resp.daemonV!==void 0&&e.resp.daemonV<3?{kind:`reconnect`,reason:`the daemon is older than this client (${e.resp.error})`,kick:!0}:{kind:`exit`,reason:`the daemon refused the stream: ${e.resp.code}: ${e.resp.error}`}}}function H9(e,t,n,r,i){let a=null,o=null,s=!1,c=250,l=(t,n)=>{o=e.clock.after(t,()=>{o=null,((n?i.beforeReconnect?.():void 0)??Promise.resolve()).then(()=>{s||u()})})},u=()=>{a=Qre(t,n,r,e=>{c=V9(c,e.ok?`frame-ok`:`frame-failed`),i.frame(e)},t=>{if(t.kind===`closed-here`||s)return;let n=$re(t);switch(n.kind){case`exit`:i.exit(n.reason);return;case`off`:i.off(n.resp),l(5e3,!1);return;case`reconnect`:{i.fault(n.reason,c),n.kick&&Ar(e);let t=c;c=V9(c,`fault`),l(t,!0);return}}})};return u(),{close:()=>{s=!0,o?.(),a?.close()}}}function eie(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function tie(e,n,r){let{values:i,tokens:a}=w({args:e.slice(3),options:{config:{type:`string`},lane:{type:`string`}},strict:!0,tokens:!0}),o=[e[1],...a.flatMap(e=>e.kind===`option`&&e.name===`config`?[e.rawName,e.value]:[])],s=t.cwd(),c=e=>{t.stderr.write(`cc-candybar frames: ${e}\n`)},l=Yb(i.lane);l===null&&(c(`--lane needs one of ${Vb.join(`, `)}`),t.exit(2)),t.stdout.on(`error`,()=>t.exit(0));let u=h9(t.stdout),d=null,f=null,p=null,m={kind:`none`},h=(e,t)=>{eie(m,e)&&t(),m=e},g=async e=>{let i=await Zn(r,e,o,s,{...P9(r.host,s,t.stderr),client:gn(`frames`,n)});i.kind!==`ok`&&(c(Wn(i)),M9(i).kick&&Ar(r))},_=e=>{p?.close(),p=H9(r,Gt(r.host),e,l,{frame:e=>h({kind:`frame`},()=>u(`${JSON.stringify(e)}\n`)),off:e=>h({kind:`off`},()=>u(`${JSON.stringify(e)}\n`)),fault:(e,t)=>h({kind:`fault`,reason:e},()=>c(`${e}; reconnecting in ${t}ms`)),exit:e=>{c(e),t.exit(1)},beforeReconnect:()=>f===null?Promise.resolve():g(f)})};for await(let e of ye({input:t.stdin})){if(e.trim()===``)continue;let t;try{t=JSON.parse(e)}catch(e){c(`stdin line is not JSON: ${e.message}`);continue}if(typeof t.session_id!=`string`||t.session_id===``){c(`stdin line carries no session_id`);continue}f=t,await g(t),t.session_id!==d&&(d=t.session_id,_(d))}t.exit(0)}function nie(e){let t=e.replace(/\n+$/,``).split(`
|
|
513
|
+
`);return{bytes:`\x1B[?2026h`+t.map((e,t)=>`\x1b[${t+1}H${e}[0m[K`).join(``)+`\x1B[J\x1B[?2026l`,rows:t.length}}const U9=5e3,W9=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function rie(e,t,n,r){let i=e.split(`
|
|
514
|
+
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?c7(e,s7(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function G9(e,t,n){let[r,i]=await Promise.all([Ws(e.launcher,t,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${n}},#{==:#{pane_id},${t.pane}}}`,`-F`,a7]),Ws(e.launcher,t,`bar-pane.tmux`,[`list-clients`,`-F`,o7])]);return r.kind===`ok`?i.kind===`ok`?{kind:`ok`,placement:rie(r.stdout,i.stdout,n,t.pane)}:i:r}function K9(e){let t=e.now();return n=>{if(n.kind===`ok`)t=e.now();else if(e.now()-t>U9)throw Error(`tmux has not answered for ${U9/1e3} s: ${n.reason}`)}}function iie(e){let{positionals:t}=(()=>{try{return w({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${W9}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(W9);return{pane:n}}async function aie(e,n){try{return await oie(e,n),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function oie(e,n){let{pane:r}=iie(e),i=mc(n.host.env);if(i===null)throw Error(`cc-candybar bar-pane runs in a tmux pane`);if(!t.stdout.isTTY)throw Error(`cc-candybar bar-pane draws on its pane's terminal`);let a=await G9(n,i,r);if(a.kind!==`ok`)throw Error(a.reason);let o=a.placement;if(o.kind===`gone`)throw Error(`no pane ${r} on this tmux server (${i.socket})`);t.stdout.write(`\x1B[?25l\x1B[?7l`),t.on(`exit`,()=>t.stdout.write(`\x1B[?25h\x1B[?7h`));for(let[e,n]of[[`SIGINT`,130],[`SIGTERM`,143],[`SIGHUP`,129]])t.once(e,()=>t.exit(n));let s=e=>{t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),t.exit(1)},c=null,l=`waiting for pane ${r}'s bar`,u=()=>c?.said.latest??l,d=``,f=K9(n.clock),p=async()=>{if(o.kind!==`shown`)return;let e=nie(u());e.rows!==t.stdout.rows&&!o.zoomed&&f(await Ws(n.launcher,i,`bar-pane.tmux`,[`resize-pane`,`-t`,i.pane,`-y`,String(e.rows)])),e.bytes!==d&&t.stdout.write(e.bytes),d=e.bytes},m=null,h=!1,g=()=>{h=!0,m??=(async()=>{try{for(;h;)h=!1,await p()}finally{m=null}})(),m.catch(s)};t.stdout.on(`resize`,()=>{d=``,g()});let _=e=>{if(c?.sessionId===e)return;if(c?.follower.close(),e===null){c=null;return}let t={latest:null},r=e=>{t.latest=e,g()};c={sessionId:e,said:t,follower:H9(n,Gt(n.host),e,`pane`,{frame:e=>r(M9(Xn(e)).output),off:e=>r(e.error),fault:r,exit:e=>s(Error(e))})}},v=K9(n.clock);for(;o.kind!==`gone`;){if(o.kind===`hidden`)_(null);else{let e=await Qn(n,i.socket,r);e.kind===`ok`?(_(e.value),l=e.value===null?`waiting for pane ${r}'s statusline to render on ${Gt(n.host)}`:`waiting for pane ${r}'s bar`):(e.kind===`transient`&&(Ar(n),d=``),l=Wn(e))}g(),await A(n.clock,500);let e=await G9(n,i,r);v(e),e.kind===`ok`&&(o=e.placement)}_(null),t.stderr.write(`cc-candybar bar-pane: pane ${r} closed\n`)}const sie=(e,t)=>new Promise((n,r)=>{let i=t=>{t?t.code===`EPIPE`?n():r(t):(e.off(`error`,i),n())};e.once(`error`,i),e.write(t,i)});async function q9(e){let n=Me(()=>`delivered stdout=${Buffer.byteLength(e.stdout)} stderr=${Buffer.byteLength(e.stderr)} code=${e.code}`),r=[];for(let[i,a]of[[t.stdout,e.stdout],[t.stderr,e.stderr+n]])await sie(i,a).catch(e=>r.push(e));if(r.length>0)throw r[0];t.exit(e.code)}const J9=i(import.meta.url),Y9=_t(),{host:X9}=Y9;je(!!X9.env.CC_CANDYBAR_DEBUG);const Z9=e=>e.some(e=>t.argv.includes(e));function Q9(){console.log(AN);let e=Yo(J9,X9),t=l.existsSync(e)?``:" (nothing is there yet: run `cc-candybar install` first — in a checkout, `pnpm build`)\n";console.log(`Starting Claude Code on ${Bb.statusline.label} yourself (a Bun-compiled Claude Code):\n ${Dt(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const $9={install:async e=>{await fs(e,J9,Y9),t.exit(0)},"install-url-handler":async()=>{os(J9,Y9),t.exit(0)},"url-handle":async e=>{await cs(e[0],Y9)},daemon:async()=>{Rne(Y9)},"daemon-stats":async e=>{await q9(await EQ(Y9,e))},frames:async()=>{await tie(t.argv,J9,Y9)},check:async e=>{await q9(await j9(e,Y9))},lint:async e=>{await q9(await j9(e,Y9))},plugin:async e=>{t.exit(Ere(e,Y9))},schema:async()=>{await q9(nre())},doctor:async e=>{await q9(await Xre(e,Y9))},"bar-pane":async e=>{t.exit(await aie(e,Y9))},...Object.fromEntries(a6.map(e=>[e,async t=>{await q9(await Kne(Y9,e,t))}]))};async function cie(){let e=t.argv[2],n=e!==void 0&&!e.startsWith(`-`)?e:null;try{if(n!==null&&!Object.hasOwn($9,n)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(n)} — see --help`),t.exit(2)),Z9(TN.help)&&(Q9(),t.exit(0)),Z9(TN.version)&&(console.log(`cc-candybar ${It}`),t.exit(0)),n!==null){await $9[n](t.argv.slice(3));return}t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
515
515
|
|
|
516
516
|
cc-candybar is designed to be used as a Claude Code statusLine command.
|
|
517
517
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -527,4 +527,4 @@ Add to ~/.claude/settings.json:
|
|
|
527
527
|
Run with --help for more options.
|
|
528
528
|
|
|
529
529
|
To test output manually:
|
|
530
|
-
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),k(`Working directory: ${t.cwd()}`),k(`Process args:`,t.argv);let e=await a(t.stdin);k(`Received hook data:`,JSON.stringify(e,null,2)),e||(console.error(`Error: No input data received from stdin`),Q9(),t.exit(1));let r=M9(await Zn(Y9,e,t.argv.slice(1),t.cwd(),{...P9(X9,t.cwd(),t.stderr),client:gn(`node`,J9)}));r.debug!==null&&k(r.debug),r.kick&&Ar(Y9),await q9({stdout:r.output,stderr:``,code:0})}catch(e){let t=e instanceof Error?e.message:String(e);await q9({stdout:``,stderr:`cc-candybar ${n??`statusline`}: ${t}\n`,code:1})}}
|
|
530
|
+
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),k(`Working directory: ${t.cwd()}`),k(`Process args:`,t.argv);let e=await a(t.stdin);k(`Received hook data:`,JSON.stringify(e,null,2)),e||(console.error(`Error: No input data received from stdin`),Q9(),t.exit(1));let r=M9(await Zn(Y9,e,t.argv.slice(1),t.cwd(),{...P9(X9,t.cwd(),t.stderr),client:gn(`node`,J9)}));r.debug!==null&&k(r.debug),r.kick&&Ar(Y9),await q9({stdout:r.output,stderr:``,code:0})}catch(e){let t=e instanceof Error?e.message:String(e);await q9({stdout:``,stderr:`cc-candybar ${n??`statusline`}: ${t}\n`,code:1})}}cie();export{};
|