@promptctl/cc-candybar 1.201.0 → 1.201.1

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.
Files changed (2) hide show
  1. package/dist/index.mjs +6 -6
  2. package/package.json +5 -5
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
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 s,{basename as c,dirname as l,isAbsolute as u,join as d,resolve as f,sep as p}from"node:path";import m,{appendFileSync as h,closeSync as g,constants as _,existsSync as v,fstatSync as y,linkSync as b,mkdtempSync as x,openSync as S,readFileSync as C,readSync as ee,rmSync as w,statSync as te,unlinkSync as ne,writeFileSync as T}from"node:fs";import{StringDecoder as re}from"node:string_decoder";import{inspect as E,parseArgs as D,types as ie}from"node:util";import{clearImmediate as O,setImmediate as ae}from"node:timers";import{spawn as oe,spawnSync as se}from"node:child_process";import ce,{createHash as le,createHmac as ue,randomBytes as de,randomUUID as fe,timingSafeEqual as pe}from"node:crypto";import me from"node:net";import he from"node:v8";import{open as ge,readFile as _e,readdir as ve,stat as ye}from"node:fs/promises";import{get as be}from"node:https";import{WriteStream as xe}from"node:tty";import{createInterface as Se}from"node:readline";var Ce=Object.create,we=Object.defineProperty,Te=Object.getOwnPropertyDescriptor,Ee=Object.getOwnPropertyNames,De=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty,ke=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ae=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ee(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Oe.call(e,s)&&s!==n&&we(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Te(t,s))||r.enumerable});return e},je=(e,t,n)=>(n=e==null?{}:Ce(De(e)),Ae(t||!e||!e.__esModule?we(n,`default`,{value:e,enumerable:!0}):n,e));let Me=!1;const Ne=()=>Me;function Pe(e){Me=e}function Fe(e){return Ne()?`[DEBUG] ${e()}\n`:``}function k(e,...t){Ne()&&console.error(`[DEBUG] ${e}`,...t)}function Ie(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const Le=(e,t)=>k(t),Re=`main`,ze=`CC_CANDYBAR_HOME`,Be=`CC_CANDYBAR_NAME`,Ve=`CC_CANDYBAR_RUNTIME_DIR`,He=/^[a-z0-9][a-z0-9-]*$/;function Ue(e,t){if(!He.test(e))throw Error(`${t} must be lowercase letters, digits and dashes, starting with a letter or digit, got ${JSON.stringify(e)}`);if(e.length>32)throw Error(`${t} must be at most 32 characters, got ${e.length}: ${JSON.stringify(e)}`);return e}function We(e){let t=Ue(e,Be);if(t===`main`)throw Error(`${Be} may not be ${JSON.stringify(Re)}: that is the main renderer's name, which is what an unset ${ze} and ${Be} mean`);return t}function Ge(e){return e===`main`?Re:Ue(e,`a link's renderer name`)}function Ke(e){return e===`main`?`socket`:`${e}.sock`}function qe(e,t){let n=e[t];return n&&n.length>0?n:void 0}function Je(){let e=process.getuid();return s.join(`/tmp`,`cc-candybar-${e}`)}function Ye(e){let t=qe(e.env,Ve);if(t===void 0)return Je();if(!s.isAbsolute(t))throw Error(`${Ve} must be an absolute path, got ${JSON.stringify(t)}`);return t}function Xe(e){let{env:t}=e,n=qe(t,ze),r=qe(t,Be),i=qe(t,`CC_CANDYBAR_SOCKET`)??null,a=Ye(e);if(n!==void 0&&r!==void 0){if(!s.isAbsolute(n))throw Error(`${ze} must be an absolute path, got ${JSON.stringify(n)}`);if(i!==null)throw Error(`CC_CANDYBAR_SOCKET is set beside ${ze} and ${Be}: a named renderer's socket is its name's, so unset it`);return{kind:`named`,name:We(r),runtime:a,root:n}}if(n!==void 0||r!==void 0){let[e,t]=n===void 0?[Be,ze]:[ze,Be];throw Error(`${e} is set without ${t}: a renderer's home is both, or neither for the main renderer`)}return{kind:`main`,name:Re,runtime:a,roots:{state:qe(t,`XDG_STATE_HOME`)??s.join(e.home,`.local`,`state`),cache:qe(t,`XDG_CACHE_HOME`)??s.join(e.home,`.cache`),config:qe(t,`XDG_CONFIG_HOME`)??s.join(e.home,`.config`)},legacySocket:i}}function Ze(e,t){return e+t}function Qe(e,t){return Math.round(t-e)}function A(e,t){return Qe(t,e.monotonic())}const $e={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=ae(e);return()=>O(t)}};function et(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 tt(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 nt(e,t,n,r){return n<e.at+t?`held`:r===`request`&&!e.answered?`owed`:`over`}function rt(e,t){return!e.answered&&e.at===t.at&&e.text===t.text}const it=e=>e.getTime()/1e3,at=e=>Math.round(e*1e3),ot=e=>new Date(at(e)),st=e=>it(new Date(e.now()));function ct(e,t){return ie.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!v(t)?`working directory does not exist: ${t}`:e.message:String(e)}const lt={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function ut(e,t,n){let r=lt[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 dt(e,t){return{...e.inherited,...t.envOverlay}}function ft(e){switch(e.reason){case`non-zero`:return`exited with code ${e.exitCode}`;case`signal`:return`killed by ${e.signal??`a signal`}`;case`timeout`:case`output-limit`:case`rate-limited`:case`pipe-error`:case`spawn-error`:return e.error??e.reason;default:return e.error===void 0?e.reason:`${e.reason}: ${e.error}`}}const pt=e=>{let t=[];for(let n of e){if(t.length===200)return`${t.join(``)}…`;t.push(n)}return e};function mt(e,t){if(e.reason===`output-limit`||e.reason===`pipe-error`)return``;let n=t.trim(),r=n.search(/[\r\n]/);if(r===-1)return pt(n);let i=Math.max(n.lastIndexOf(`
3
3
  `),n.lastIndexOf(`\r`))+1;return`${pt(n.slice(0,r).trim())} … ${pt(n.slice(i).trim())}`}function j(e,t=``){let n=mt(e,e.stderr);return`${ft(e)}${t}${n===``?``:`: ${n}`}`}const ht=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function gt(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 ${Math.round(n)}ms ago`}}function _t(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function vt(e,t,n){let r=yt(e,t,n);return r===null?(e.lastStartAt.set(t,e.scope.clock.monotonic()),null):(e.scope.stats?.onRefused(t),r)}function yt(e,t,n){if(e.scope.signal.aborted)return ht(e.scope.signal);if(n?.aborted)return ht(n);let r=ut(e.lastStartAt,t,e.scope.clock.monotonic());return r.allowed?null:gt(t,r.minIntervalMs,r.sinceLastMs)}const bt=`\$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 xt(e,t){t!==e.fault&&(e.fault=t,e.scope.observeWarnings({kind:`lifeline`,fault:t}))}function St(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),xt(e,n))}const Ct=e=>`programs launched now would outlive their launcher if it died: its launch lifeline ${e}, and the next launch starts another`,wt=e=>e===`cut`?`output cut at the ${Nt}-byte bound, so the program holding it now fails its writes`:`output failed to read`,Tt=`a launched program's pipe outlived its launch: `;function Et(e,t,n){let r=e.pipeEvent,i=new Map(r===null||r.answered?[]:r.counts),a=`${t}\0${n}`;i.set(a,(i.get(a)??0)+1),e.pipeEvent={text:`${Tt}${[...i].map(([e,t])=>{let[n,r]=e.split(`\0`);return`${t}× ${r} ${wt(n)}`}).join(`; `)}`,at:e.scope.now(),answered:!1,counts:i},e.scope.observeWarnings({kind:`launch-pipes`,text:`${Tt}${n} ${wt(t)}`})}function Dt(e,t){let n=e.pipeEvent;n===null||!rt(n,t)||(e.pipeEvent={...n,answered:!0})}function Ot(e,t,n){let r=e.pipeEvent,i=r===null?`over`:nt(r,60,t,n);return[...e.fault===null?[]:[{kind:`lifeline`,message:Ct(e.fault)}],...r===null||i===`over`?[]:[{kind:`launch-pipes`,message:r.text,event:r,hold:i}]]}function kt(e){let{stats:t,clock:n}=e.scope;t?.onStart(`lifeline`);let r=n.monotonic(),i;try{i=e.spawner.spawn(`awk`,[bt],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(i){return t?.onEnd(`lifeline`,A(n,r)),xt(e,`did not start: ${ct(i,void 0)}`),null}t?.onEnd(`lifeline`,A(n,r));let a=i.stdin;if(a==null)return i.once(`error`,t=>xt(e,`did not start: ${t.message}`)),null;i.once(`spawn`,()=>{e.lifeline?.process===i&&xt(e,null)}),i.once(`error`,t=>St(e,i,`failed: ${t.message}`)),i.once(`exit`,(t,n)=>St(e,i,`exited ${n??t}`)),a.on(`error`,t=>St(e,i,`pipe failed: ${t.message}`)),_t(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 At(e,t){e.liveGroups.add(t),e.lifeline??=kt(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function jt(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function Mt(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}const Nt=16*1024*1024,Pt=`output exceeded ${Nt} bytes`,Ft=e=>`timed out after ${e/1e3} s`;function It(e,t,n,r){let{stats:i}=e.scope,a=new re(`utf8`),o=``,s=0,c=0,l=r,u=`closed`;return n?.on(`error`,n=>{i?.onPipeError(t),l===null?Et(e,`read-error`,t):l.failed(n)}),n?.on(`data`,r=>{if(l===null){if(c+=r.length,i?.onDrainRead(t,r.length),c<=16777216)return;u=`cut`,n.destroy(),Et(e,`cut`,t);return}let d=Math.max(0,Nt-s);o+=a.write(r.subarray(0,d)),s+=r.length,s>16777216&&l.full()}),{take:()=>{if(l===null)return``;l=null;let e=o+a.end();return o=``,e},drain:()=>{n===null||n.destroyed||n.readableEnded||Lt(e,t,n,()=>u)}}}function Lt(e,t,n,r){let{stats:i}=e.scope;if(e.scope.signal.aborted){n.destroy();return}n.once(`close`,()=>{e.drains.delete(n),i?.onDrainClose(t,r())}),n.unref(),e.drains.add(n),i?.onDrainOpen(t)}const Rt=()=>`closed`;function zt(e,t){e.on(`error`,()=>{}),e.end(t)}async function Bt(e,t){let{stats:n,clock:r}=e.scope,i=vt(e,t.category,t.signal);if(i!==null)return i;let a=r.monotonic();return n?.onStart(t.category),new Promise(i=>{let{spawner:o}=e,s;try{s=o.spawn(t.bin,t.args??[],{cwd:t.cwd,env:dt(e.scope,t),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(e){n?.onEnd(t.category,A(r,a)),i({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:ct(e,t.cwd)});return}let c=s.pid;c!==void 0&&At(e,c);let l=new Promise(e=>s.once(`exit`,e)),u=s.stdin;s.stdin=null;let d=null,f={full:()=>ne(`output-limit`),failed:e=>{d??=e.message,ne(`pipe-error`)}},p=It(e,t.category,s.stdout,f),m=It(e,t.category,s.stderr,f),h=()=>({stdout:p.take(),stderr:m.take()}),g=!1,_=null,v=null,y=null,b=null,x=()=>ne(`aborted`),S=()=>{t.signal?.removeEventListener(`abort`,x),e.inFlight.delete(x)},C=i=>{g||(g=!0,_?.(),v?.(),y?.(),S(),c!==void 0&&jt(e,c),n?.onEnd(t.category,A(r,a)),s.off(`close`,re),s.off(`error`,T),p.drain(),m.drain(),u!==null&&!u.destroyed&&!u.writableFinished&&Lt(e,t.category,u,Rt),i())},ee=e=>C(()=>i(e)),w=(n,r)=>{try{o.signalGroup(n,r)}catch(n){e.unreaped.set(s,t.category),l.then(()=>e.unreaped.delete(s)),ee({ok:!1,reason:`signal-refused`,...h(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},te=()=>re(s.exitCode,s.signalCode);if(c!==void 0){let e=t=>{if(!g){if(o.groupGone(c)){r.defer(te);return}y=r.after(t,()=>e(Math.min(t*2,1e3)))}};l.then(()=>r.defer(()=>e(25)))}let ne=e=>{if(b!==null)return;if((s.exitCode!==null||s.signalCode!==null)&&c!==void 0&&o.groupGone(c)){b=e===`timeout`?null:e,r.defer(te);return}b=e,_?.(),S();let t=s.pid;t!==void 0&&(v=r.after(250,()=>{w(t,`SIGKILL`),l.then(()=>r.defer(te))}),w(t,`SIGTERM`))},T=e=>{ee({ok:!1,reason:`spawn-error`,...h(),exitCode:null,signal:null,error:ct(e,t.cwd)})};s.on(`error`,T);let re=(e,n)=>{if(b!==null){ee({ok:!1,reason:b,...h(),exitCode:e,signal:n,...b===`timeout`?{error:Ft(t.timeoutMs??0)}:b===`output-limit`?{error:Pt}:b===`pipe-error`?{error:`a pipe failed to read: ${d}`}:{}});return}if(e===0){ee({ok:!0,...h(),exitCode:e});return}ee({ok:!1,reason:n?`signal`:`non-zero`,...h(),exitCode:e,signal:n})};s.on(`close`,re),t.timeoutMs&&t.timeoutMs>0&&(_=r.after(t.timeoutMs,()=>ne(`timeout`))),t.signal?.addEventListener(`abort`,x,{once:!0}),e.inFlight.add(x),u!==null&&zt(u,t.stdinInput)})}function Vt(e,t){let{stats:n,clock:r}=e.scope,i=vt(e,t.category);if(i!==null)return i;let a=r.monotonic();n?.onStart(t.category);try{let i=e.spawner.spawnSync(t.bin,t.args??[],{cwd:t.cwd,env:dt(e.scope,t),input:t.stdinInput,timeout:t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:void 0,stdio:[`pipe`,`pipe`,`pipe`],encoding:`utf8`});n?.onEnd(t.category,A(r,a));let o=typeof i.stdout==`string`?i.stdout:``,s=typeof i.stderr==`string`?i.stderr:``,c=i.error?.code;if(i.error&&c!==`EPIPE`&&c!==`ECONNRESET`){let e=c===`ETIMEDOUT`?`timeout`:`spawn-error`;return{ok:!1,reason:e,stdout:o,stderr:s,exitCode:null,signal:i.signal??null,error:e===`timeout`?Ft(t.timeoutMs??0):ct(i.error,t.cwd)}}return i.status===0?{ok:!0,stdout:o,stderr:s,exitCode:i.status}:{ok:!1,reason:i.signal?`signal`:`non-zero`,stdout:o,stderr:s,exitCode:i.status,signal:i.signal??null}}catch(e){return n?.onEnd(t.category,A(r,a)),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:ct(e,t.cwd)}}}function Ht(e,t){let{stats:n,clock:r}=e.scope,i=vt(e,t.category);if(i!==null)return i;let a=r.monotonic();n?.onStart(t.category);let o=M(e,t);return n?.onEnd(t.category,A(r,a)),o}function M(e,t){let n;try{n=e.spawner.spawn(t.bin,t.args??[],{cwd:t.cwd,env:dt(e.scope,t),detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:ct(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 Ut=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`;function Wt(e,t,n){let{stats:r,clock:i}=e.scope,a=vt(e,t.category);if(a!==null)return{ok:!1,reason:a.reason,error:a.error};let o=i.monotonic();r?.onStart(t.category);let s;try{s=e.spawner.spawn(`/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:dt(e.scope,t),detached:!0,stdio:[`pipe`,`ignore`,`ignore`]})}catch(e){return r?.onEnd(t.category,A(i,o)),{ok:!1,reason:`spawn-error`,error:ct(e,t.cwd)}}r?.onEnd(t.category,A(i,o)),s.once(`error`,()=>{});let c=s.pid,l=s.stdin;return l.on(`error`,()=>{}),c===void 0?(l.destroy(),{ok:!1,reason:`spawn-error`,error:`spawn(/bin/sh): no pid (shell not found or unexecutable)`}):(s.unref(),l.unref(),{ok:!0,pid:c,release:()=>l.end(`go
4
- `),withdraw:()=>l.end()})}function Gt(e){let t;try{t=C(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 Kt(e,t,n,r,i){let a=`${r}.${process.pid}`;try{T(a,`${Ut(i)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let o=!0;try{b(a,r)}catch(e){if(e.code!==`EEXIST`)throw e;o=!1}finally{w(a,{force:!0})}let s=e.signalJob(n,`SIGTERM`);return s&&t.after(250,()=>e.signalJob(n,`SIGKILL`),{unref:!0}),{stands:o,signalled:s}}function qt(e,t,n){return N(e,t,n).launcher}function Jt(e,t,n){let{launcher:r,state:i}=N(e,t,n);return{...r,launchSync:e=>Vt(i,e)}}function N(e,t,n){let r={clock:t,launch:e=>_t(i,Bt(i,e)),launchDetachedSync:e=>Ht(i,e),launchJobSync:(e,t)=>Wt(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>Kt(n,t,e,r,i),launcherWarnings:(e,t)=>Ot(i,e,t),answeredPipeEvent:e=>Dt(i,e),settled:async()=>(await Promise.all(i.ending),{unreaped:[...i.unreaped.values()]}),__lifelineForTest:()=>{let e=i.lifeline;return{pid:e?.process.pid,cut:()=>{e?.pipe.end(),e&&St(i,e.process,`cut by a test`)}}}},i={spawner:n,scope:{stats:null,observeWarnings:e=>{let t=e.kind===`launch-pipes`?e.text:e.fault===null?null:Ct(e.fault);t!==null&&process.emitWarning(t)},signal:new AbortController().signal,now:()=>it(new Date(t.now())),...e,clock:t},lastStartAt:new Map,inFlight:new Set,liveGroups:new Set,lifeline:null,fault:null,pipeEvent:null,ending:new Set,unreaped:new Map,drains:new Set};return i.scope.signal.addEventListener(`abort`,()=>{i.inFlight.forEach(e=>e()),i.drains.forEach(e=>e.destroy()),Mt(i)},{once:!0}),{launcher:r,state:i}}function Yt(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const Xt={spawn:(e,t,n)=>oe(e,t,n),spawnSync:(e,t,n)=>se(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!Yt(e)))throw t}},groupGone:e=>{try{return process.kill(-e,0),!1}catch(e){return e.code===`ESRCH`}},signalJob:(e,t)=>{try{return process.kill(-e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}},Zt=(e,t)=>qt(e,t,Xt),Qt=(e,t)=>Jt(e,t,Xt);function $t(){let e={env:process.env,home:o.homedir(),tmp:o.tmpdir()},t=$e;return{host:e,home:en(e),launcher:Qt({inherited:process.env},t),clock:t}}function en(e){try{return Xe(e)}catch(e){process.stderr.write(`cc-candybar: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}}const tn=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function nn(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function rn(e){return tn.test(e)?e:nn(e)}function an(e){return`${e.dir===void 0?``:`cd ${rn(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${rn(t)} `).join(``)}${[e.program,...e.args].map(rn).join(` `)}`}const on=`cc-extra`;function sn(e){return s.join(s.dirname(e),on,`src`,`bun-attach.js`)}function cn(e){return s.join(s.dirname(e),`bun-graph.js`)}const ln=`attach-preload.cjs`;function un(e){return s.join(s.dirname(e),ln)}function dn(e,t){return an({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const fn=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function pn(e,t){return t.isSymbolicLink()?Buffer.from(m.readlinkSync(e)):m.readFileSync(e)}function mn(e,t,n=fn){return m.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=m.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?mn(e,r):[[s.relative(e,r).split(s.sep).join(`/`),pn(r,i)]]})}function hn(e){let t=ce.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function gn(e){return hn(mn(e,e))}const _n=[`Cargo.toml`,`Cargo.lock`,`src`];function vn(e){return hn(mn(e,e,e=>_n.includes(e)))}const yn=e=>e.slice(0,7),bn=`1.201.0`;function xn(e){let t=s.dirname(s.dirname(e));return m.existsSync(s.join(t,`src`))?t:null}function Sn(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:bn,digest:e}}function Cn(){return`ce8ccef5e1b85c62d67cb6d05588f4c3f949fe31a6541d4fd8adc4e196ae4d02`}function wn(e){let t=JSON.parse(m.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function P(e,t){try{let n=xn(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=gn(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:wn(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function Tn(e){try{return m.statSync(e).isDirectory()?m.realpathSync.native(e):null}catch{return null}}function En(e){let t=Tn(e),n=s.dirname(e);if(t!==null||n===e)return{dir:t??e,rest:[]};let r=En(n);return{dir:r.dir,rest:[...r.rest,s.basename(e)]}}function Dn(e){let{dir:t,rest:n}=En(e);return s.join(t,...n)}function On(e){return e.kind===`main`?s.join(e.roots.state,`cc-candybar`):s.join(e.root,`state`)}function kn(e){return e.kind===`main`?s.join(e.roots.cache,`cc-candybar`):s.join(e.root,`cache`)}function An(e){return e.kind===`main`?s.join(e.roots.config,`cc-candybar`):s.join(e.root,`config`)}function jn(e){return Mn(e.kind===`main`?An(e):e.root)}function Mn(e){return{dir:e,onDisk:Dn}}function Nn(e){return e.kind===`main`&&e.legacySocket!==null?e.legacySocket:s.join(e.runtime,Ke(e.name))}function Pn(e){return s.join(Je(),Ke(e))}function Fn(e){return e.kind===`main`?{[ze]:``,[Be]:``,[Ve]:e.runtime,XDG_STATE_HOME:e.roots.state,XDG_CACHE_HOME:e.roots.cache,XDG_CONFIG_HOME:e.roots.config,CC_CANDYBAR_SOCKET:e.legacySocket??``}:{[ze]:e.root,[Be]:e.name,[Ve]:e.runtime,CC_CANDYBAR_SOCKET:``}}function In(e){m.mkdirSync(e,{recursive:!0,mode:448});let t=m.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=process.getuid();if(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 Ln(e){In(s.dirname(e));for(let t of[e,Rn(e)])try{if(m.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Rn(e){return`${e}.lease`}function zn(e){return Rn(Nn(e))}function Bn(e){return s.join(On(e),`session-state.json`)}function Vn(e){return s.join(On(e),`settings-history.json`)}function Hn(e){return e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR||s.join(Je(),`daemons`)}function Un(e){return s.join(On(e),`spawn.lock`)}function Wn(e){return s.join(On(e),`spawn.cooldown`)}function Gn(e){return s.join(On(e),`spawn.backoff`)}function Kn(e){return s.join(On(e),`watch-probe`)}function qn(e){return s.join(On(e),`daemon.log`)}function Jn(e){return{socket:Nn(e),lease:zn(e),state:On(e),log:qn(e),sessionState:Bn(e),settingsHistory:Vn(e),storedRoot:jn(e),watchProbe:Kn(e),spawnBackoff:Gn(e)}}function Yn(e){return qe(e.env,`XDG_DATA_HOME`)??s.join(e.home,`.local`,`share`)}function Xn(e,t){let{env:n}=e,r=`/usr/local/share:/usr/share`,i=process.platform===`darwin`?`${s.join(qe(n,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${r}`:r;return{homeDir:e.home,configDir:An(t),dataHome:Yn(e),dataDirs:(qe(n,`XDG_DATA_DIRS`)??i).split(`:`).filter(e=>e!==``)}}function Zn(e,t,n){let r=Qn(e);m.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??m.statSync(r,{throwIfNoEntry:!1})?.mode;try{m.writeFileSync(i,t,a===void 0?{}:{mode:a}),m.renameSync(i,r)}catch(e){throw m.rmSync(i,{force:!0}),e}}function Qn(e){return $n(e).at(-1)}function $n(e){let{hops:t,stopped:n}=er(e);if(n!==null)throw n;return t}function er(e){let t=[e];try{for(let e=0;e<nr;e++){let e=tr(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${nr} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function tr(e){try{return m.lstatSync(e).isSymbolicLink()?s.resolve(m.realpathSync(s.dirname(e)),m.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const nr=40,rr=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function ir(e){return Object.fromEntries(rr.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const ar=[`native`,`node`,`frames`];function or(e,t){return{kind:e,bundle:t,source:null}}const sr=[`ansi`,`frame`],cr=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function lr(e){let t=vr(e.termCols),n=vr(e.termRows),r=yr(e.ssh),i=gr(e.tmux),a=hr(e.configEnv),o=hr(e.claudeConfigDir),s=mr(e.terminalEnv),c=Ar(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 ur(e,t){return cr.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function dr(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 fr={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function pr(e){let t=Object.keys(fr).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[fr[t](n.join(`, `))]});return t.length===0?null:t.join(`
4
+ `),withdraw:()=>l.end()})}function Gt(e){let t;try{t=C(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 Kt(e,t,n,r,i){let a=`${r}.${process.pid}`;try{T(a,`${Ut(i)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let o=!0;try{b(a,r)}catch(e){if(e.code!==`EEXIST`)throw e;o=!1}finally{w(a,{force:!0})}let s=e.signalJob(n,`SIGTERM`);return s&&t.after(250,()=>e.signalJob(n,`SIGKILL`),{unref:!0}),{stands:o,signalled:s}}function qt(e,t,n){return N(e,t,n).launcher}function Jt(e,t,n){let{launcher:r,state:i}=N(e,t,n);return{...r,launchSync:e=>Vt(i,e)}}function N(e,t,n){let r={clock:t,launch:e=>_t(i,Bt(i,e)),launchDetachedSync:e=>Ht(i,e),launchJobSync:(e,t)=>Wt(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>Kt(n,t,e,r,i),launcherWarnings:(e,t)=>Ot(i,e,t),answeredPipeEvent:e=>Dt(i,e),settled:async()=>(await Promise.all(i.ending),{unreaped:[...i.unreaped.values()]}),__lifelineForTest:()=>{let e=i.lifeline;return{pid:e?.process.pid,cut:()=>{e?.pipe.end(),e&&St(i,e.process,`cut by a test`)}}}},i={spawner:n,scope:{stats:null,observeWarnings:e=>{let t=e.kind===`launch-pipes`?e.text:e.fault===null?null:Ct(e.fault);t!==null&&process.emitWarning(t)},signal:new AbortController().signal,now:()=>it(new Date(t.now())),...e,clock:t},lastStartAt:new Map,inFlight:new Set,liveGroups:new Set,lifeline:null,fault:null,pipeEvent:null,ending:new Set,unreaped:new Map,drains:new Set};return i.scope.signal.addEventListener(`abort`,()=>{i.inFlight.forEach(e=>e()),i.drains.forEach(e=>e.destroy()),Mt(i)},{once:!0}),{launcher:r,state:i}}function Yt(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const Xt={spawn:(e,t,n)=>oe(e,t,n),spawnSync:(e,t,n)=>se(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!Yt(e)))throw t}},groupGone:e=>{try{return process.kill(-e,0),!1}catch(e){return e.code===`ESRCH`}},signalJob:(e,t)=>{try{return process.kill(-e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}},Zt=(e,t)=>qt(e,t,Xt),Qt=(e,t)=>Jt(e,t,Xt);function $t(){let e={env:process.env,home:o.homedir(),tmp:o.tmpdir()},t=$e;return{host:e,home:en(e),launcher:Qt({inherited:process.env},t),clock:t}}function en(e){try{return Xe(e)}catch(e){process.stderr.write(`cc-candybar: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}}const tn=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function nn(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function rn(e){return tn.test(e)?e:nn(e)}function an(e){return`${e.dir===void 0?``:`cd ${rn(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${rn(t)} `).join(``)}${[e.program,...e.args].map(rn).join(` `)}`}const on=`cc-extra`;function sn(e){return s.join(s.dirname(e),on,`src`,`bun-attach.js`)}function cn(e){return s.join(s.dirname(e),`bun-graph.js`)}const ln=`attach-preload.cjs`;function un(e){return s.join(s.dirname(e),ln)}function dn(e,t){return an({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const fn=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function pn(e,t){return t.isSymbolicLink()?Buffer.from(m.readlinkSync(e)):m.readFileSync(e)}function mn(e,t,n=fn){return m.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=m.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?mn(e,r):[[s.relative(e,r).split(s.sep).join(`/`),pn(r,i)]]})}function hn(e){let t=ce.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function gn(e){return hn(mn(e,e))}const _n=[`Cargo.toml`,`Cargo.lock`,`src`];function vn(e){return hn(mn(e,e,e=>_n.includes(e)))}const yn=e=>e.slice(0,7),bn=`1.201.1`;function xn(e){let t=s.dirname(s.dirname(e));return m.existsSync(s.join(t,`src`))?t:null}function Sn(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:bn,digest:e}}function Cn(){return`9d558fdc410239b16f95b6714fe115856bd2ac480c2cf966800c4b5104534f86`}function wn(e){let t=JSON.parse(m.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function P(e,t){try{let n=xn(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=gn(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:wn(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function Tn(e){try{return m.statSync(e).isDirectory()?m.realpathSync.native(e):null}catch{return null}}function En(e){let t=Tn(e),n=s.dirname(e);if(t!==null||n===e)return{dir:t??e,rest:[]};let r=En(n);return{dir:r.dir,rest:[...r.rest,s.basename(e)]}}function Dn(e){let{dir:t,rest:n}=En(e);return s.join(t,...n)}function On(e){return e.kind===`main`?s.join(e.roots.state,`cc-candybar`):s.join(e.root,`state`)}function kn(e){return e.kind===`main`?s.join(e.roots.cache,`cc-candybar`):s.join(e.root,`cache`)}function An(e){return e.kind===`main`?s.join(e.roots.config,`cc-candybar`):s.join(e.root,`config`)}function jn(e){return Mn(e.kind===`main`?An(e):e.root)}function Mn(e){return{dir:e,onDisk:Dn}}function Nn(e){return e.kind===`main`&&e.legacySocket!==null?e.legacySocket:s.join(e.runtime,Ke(e.name))}function Pn(e){return s.join(Je(),Ke(e))}function Fn(e){return e.kind===`main`?{[ze]:``,[Be]:``,[Ve]:e.runtime,XDG_STATE_HOME:e.roots.state,XDG_CACHE_HOME:e.roots.cache,XDG_CONFIG_HOME:e.roots.config,CC_CANDYBAR_SOCKET:e.legacySocket??``}:{[ze]:e.root,[Be]:e.name,[Ve]:e.runtime,CC_CANDYBAR_SOCKET:``}}function In(e){m.mkdirSync(e,{recursive:!0,mode:448});let t=m.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=process.getuid();if(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 Ln(e){In(s.dirname(e));for(let t of[e,Rn(e)])try{if(m.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Rn(e){return`${e}.lease`}function zn(e){return Rn(Nn(e))}function Bn(e){return s.join(On(e),`session-state.json`)}function Vn(e){return s.join(On(e),`settings-history.json`)}function Hn(e){return e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR||s.join(Je(),`daemons`)}function Un(e){return s.join(On(e),`spawn.lock`)}function Wn(e){return s.join(On(e),`spawn.cooldown`)}function Gn(e){return s.join(On(e),`spawn.backoff`)}function Kn(e){return s.join(On(e),`watch-probe`)}function qn(e){return s.join(On(e),`daemon.log`)}function Jn(e){return{socket:Nn(e),lease:zn(e),state:On(e),log:qn(e),sessionState:Bn(e),settingsHistory:Vn(e),storedRoot:jn(e),watchProbe:Kn(e),spawnBackoff:Gn(e)}}function Yn(e){return qe(e.env,`XDG_DATA_HOME`)??s.join(e.home,`.local`,`share`)}function Xn(e,t){let{env:n}=e,r=`/usr/local/share:/usr/share`,i=process.platform===`darwin`?`${s.join(qe(n,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${r}`:r;return{homeDir:e.home,configDir:An(t),dataHome:Yn(e),dataDirs:(qe(n,`XDG_DATA_DIRS`)??i).split(`:`).filter(e=>e!==``)}}function Zn(e,t,n){let r=Qn(e);m.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??m.statSync(r,{throwIfNoEntry:!1})?.mode;try{m.writeFileSync(i,t,a===void 0?{}:{mode:a}),m.renameSync(i,r)}catch(e){throw m.rmSync(i,{force:!0}),e}}function Qn(e){return $n(e).at(-1)}function $n(e){let{hops:t,stopped:n}=er(e);if(n!==null)throw n;return t}function er(e){let t=[e];try{for(let e=0;e<nr;e++){let e=tr(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${nr} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function tr(e){try{return m.lstatSync(e).isSymbolicLink()?s.resolve(m.realpathSync(s.dirname(e)),m.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const nr=40,rr=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function ir(e){return Object.fromEntries(rr.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const ar=[`native`,`node`,`frames`];function or(e,t){return{kind:e,bundle:t,source:null}}const sr=[`ansi`,`frame`],cr=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function lr(e){let t=vr(e.termCols),n=vr(e.termRows),r=yr(e.ssh),i=gr(e.tmux),a=hr(e.configEnv),o=hr(e.claudeConfigDir),s=mr(e.terminalEnv),c=Ar(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 ur(e,t){return cr.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function dr(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 fr={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function pr(e){let t=Object.keys(fr).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[fr[t](n.join(`, `))]});return t.length===0?null:t.join(`
5
5
  `)}function mr(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=rr.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 hr(e){return typeof e==`string`&&s.isAbsolute(e)?e:void 0}function gr(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 _r=1e4;function vr(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>_r?_r:t}function yr(e){return typeof e==`boolean`?e:void 0}const br=new Set([...[],1]);function xr(e){return typeof e==`object`&&e&&e.kind===`url`?{kind:`url`,frame:e}:{kind:`request`,req:e}}const Sr=Math.floor((2**31-1)/1e3)-60;function Cr(e){return typeof e==`number`&&e>0&&e<=Sr?{ok:!0,seconds:e}:{ok:!1,problem:`is not a span of seconds above 0 and at most ${Sr}`}}var wr=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}},Tr=class extends Error{constructor(e){super(e===`connect`?`CONNECT_TIMEOUT`:`TIMEOUT`),this.phase=e,this.name=`ClientTimeoutError`}};function Er(e){return Dr(JSON.stringify(e))}function Dr(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function Or(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 wr(`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 wr(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function kr(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 Tr(`deadline`))})}),l=Or(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(Er(t))})}function Ar(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=hr(n);return ar.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function jr(e,t,n,r){let i;try{i=await Lr(Nn(e.home),n.connectMs,e.clock)}catch(e){return Ir(e)}return Mr(i,e.clock,t,n,r)}async function Mr(e,t,n,r,i){try{let a=t.now()+r.budgetMs,o=n(a),s=await kr(e,{v:3,...o},a,t);return Fr(o.kind,s,i)}catch(e){return Ir(e)}finally{e.destroy()}}function Nr(e,t){return typeof e==`string`?e:t}function Pr(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function Fr(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=Nr(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:Pr(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 Ir(e){if(e instanceof wr||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 Tr?{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 Lr(e,t,n){return new Promise((r,i)=>{let a=me.createConnection({path:e}),o=n.after(t,()=>{a.destroy(),i(new Tr(`connect`))});a.once(`connect`,()=>{o(),r(a)}),a.once(`error`,e=>{o(),i(e)})})}function Rr(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 zr(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 Br(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 Vr={connectMs:50,budgetMs:150},Hr={connectMs:50,budgetMs:350};function Ur(e){let t=e.output;return typeof t==`string`?t:void 0}function Wr(e){return Fr(`render`,e,Ur)}function Gr(e,t,n,r,i,a=Vr){return jr(e,e=>({kind:`render`,hookData:t,args:n,cwd:r,deadline:e,...i}),a,Ur)}function Kr(e,t,n){return jr(e,()=>({kind:`pane-session`,socket:t,pane:n}),Hr,e=>`paneSession`in e?e.paneSession:void 0)}function qr(e,t){return jr(e,()=>({kind:`click`,url:t}),Hr,Ur)}const Jr=5e3;async function Yr(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(`
6
6
  `)}const Xr=`/usr/bin/footprint`;function Zr(e,t,n){return t===`darwin`?[ti(e,Xr,[`-p`,String(n)]),ti(e,`/usr/bin/vmmap`,[`--summary`,String(n)])]:t===`linux`?[ni(`/proc/self/smaps_rollup`),ni(`/proc/self/status`)]:[]}function Qr(e,t,n){return t===`darwin`?$r(n,t=>e.launch({bin:Xr,args:t,timeoutMs:Jr,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function $r(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 ${j(r)}`};let i=ei(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 ei(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function ti(e,t,n){return{name:`${t} ${n.join(` `)}`,read:async()=>{let r=await e.launch({bin:t,args:[...n],timeoutMs:Jr,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:j(r)}}}}function ni(e){return{name:e,read:async()=>{try{let t=m.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}}}}}const ri=`CC_CANDYBAR_RSS_LIMIT_MB`;function ii(e){let t=e[ri];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${ri} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function ai(e){return ii(e)*2}const oi=1024*1024,F=e=>Math.round(e/oi);function si(e){return ii(e)*oi}const ci={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function li(e,t){return e>t}function ui(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 di=.75;function fi(e,t){return e>t*di}function pi(e,t,n){let{prefix:r,suffix:i}=ci[t];return s.join(e,`${r}${n}${i}`)}function mi(e){for(let t of Object.keys(ci)){let{prefix:n,suffix:r}=ci[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function hi(e){let t=e.limitBytes??1024*oi,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=ui(await e.memoryCharge(a),i),l={kind:`measured`,charge:c,rss:a,heapTotal:s};if(i=l,e.log(`info`,`memory ${vi(l,t)}`),o||c.bytes<=t)return!1;r=!0,e.log(`warn`,`${gi(c)} > limit ${F(t)} MB (rss ${F(a)} MB, v8 heap ${F(s)} MB); recording memory then shutting down`);let u=`${new Date(e.clock.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return await yi(e.log,`memory report`,async()=>{let t=pi(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 yi(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=pi(e.snapshotDir,`heapSnapshot`,u);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),await yi(e.log,`artifact rotation`,async()=>{for(let{artifacts:t}of bi(e.listArtifacts()).slice(n))for(let n of Object.values(t))await yi(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0)}function u(){return i.kind===`measured`&&fi(i.charge.bytes,t)?`${gi(i.charge)} approaching limit ${F(t)} MB (v8 heap ${F(i.heapTotal)} MB)`:null}function d(){let n;try{n={kind:`ok`,value:bi(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 gi(e){return e.kind===`charged`?`${e.measure} ${F(e.bytes)} MB`:`rss ${F(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${F(e.gap)} MB gap`} (standing in: ${e.unread})`}function _i(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function vi({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${F(e.gap)}MB`:``;return`measure=${_i(e)} charge=${F(e.bytes)}MB rss=${F(t)}MB heap=${F(n)}MB limit=${F(r)}MB${i}`}async function yi(e,t,n){try{await n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function bi(e){let t=new Map;for(let n of e){let e=s.basename(n),r=mi(e);if(r===null)continue;let{prefix:i,suffix:a}=ci[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(ci);return[...t].sort(([e],[t])=>li(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function xi(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:Qr(n.launcher,process.platform,process.pid),captureMemoryReport:()=>Yr(Zr(n.launcher,process.platform,process.pid)),writeMemoryReport:(e,t)=>m.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>he.writeHeapSnapshot(e),writeLogNow:n.writeLogNow,listArtifacts:()=>{let e;try{e=m.readdirSync(i)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>mi(e)!==null).map(e=>s.join(i,e))},removeFile:e=>m.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}function Si(e,n={}){let{home:r,clock:i}=e;if(Ri(r)!==null)return;let a=n.spawn??(()=>Bi(e)),o=Fi(r,i);if(o.kind===`contended`){let e=wi(r,i);e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),Ci(r,i,a));return}if(o.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${o.reason}) — spawning unlocked\n`),Ci(r,i,a);return}try{Ci(r,i,a)}finally{Li()}}function Ci(e,t,n){ji(e,t)&&Ti(n)}function wi(e,t){try{let n=m.statSync(Un(e));return t.now()-n.mtimeMs}catch{return null}}function Ti(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
7
7
  `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function Ei(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function Di(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function Oi(e){try{let t=m.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function ki(e,n){try{m.mkdirSync(s.dirname(e),{recursive:!0}),m.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function Ai(e){try{m.unlinkSync(e)}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function ji(e,n){let r=Wn(e),i=Gn(e),a=Oi(i),o=Ei(Mi(r,n),Di(a));return o.kind===`deny`?!1:(o.kind===`allow-future-garbage`&&t.stderr.write(`cc-candybar: spawn.cooldown mtime is ${o.futureMs}ms in the future — ignoring and spawning\n`),Ni(r,n),ki(i,Math.min(a+1,5)),!0)}function Mi(e,t){try{return t.now()-m.statSync(e).mtimeMs}catch{return null}}function Ni(e,n){try{m.mkdirSync(s.dirname(e),{recursive:!0}),m.writeFileSync(e,`${t.pid} ${n.now()}\n`,{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}let Pi=null;function Fi(e,n){let r=Un(e);for(let e=0;e<2;e++){try{let e=m.openSync(r,`wx`,384);try{m.writeSync(e,JSON.stringify({pid:t.pid,ts:n.now()}))}catch{}return Pi={fd:e,path:r},{kind:`held`}}catch(e){let t=e.code;if(t!==`EEXIST`)return{kind:`error`,reason:`openSync(${r}): ${t??e.message}`}}if(!Ii(r,n))return{kind:`contended`};try{m.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function Ii(e,t){try{let n=m.statSync(e);return t.now()-n.mtimeMs>1e4}catch{return!0}}function Li(){if(!Pi)return;let{fd:e,path:t}=Pi;Pi=null;try{m.closeSync(e)}catch{}try{m.unlinkSync(t)}catch{}}function Ri(e){try{return m.mkdirSync(On(e),{recursive:!0}),null}catch(t){return`mkdir ${On(e)}: ${t.message}`}}function zi(e,t){return[`--max-old-space-size=${ai(t)}`,e,`daemon`]}function Bi({host:e,launcher:n}){let r=t.execPath,i=t.argv[1];return i?n.launchDetachedSync({bin:r,args:zi(i,e.env),category:`daemon-spawn`}).ok:!1}const Vi=`cc-candybar`,Hi=`CCCandybarURLHandler`,Ui=e=>e.startsWith(`${Vi}://`),Wi=`closed`,Gi=`open`,Ki=`🍫`;function qi(e,t,n){if(t===0)return`${e} needs a display (the clickable text)`;if(t!==1&&t!==n)return`${e} cycles ${n} members; bind one display per member (${n}) or one static display, got ${t}`}function Ji(e,t,n,r){let i=qi(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function Yi(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function Xi(e,t,n,r,i){return{kind:`segment`,name:e,opens:{ref:t,body:n,placement:r},...i!==void 0&&{when:i}}}function Zi(e,...t){return`{{ and ${[e,...t].map(Qi).join(` `)} }}`}function Qi(e){return`(eq .${e.variable} "${Yi(e.member)}")`}function $i(e,t,n){return`{{ ${ea(e,ta(t),ta(n))} }}`}function ea(e,t,n){return`action "${e}" ${t} ${n}`}function ta(e){return`"${Yi(e)}"`}function na(e,t){return{kind:`state`,key:e,default:t}}function ra(e,t){return{set:e,cycle:[Wi,t]}}function ia(e){if(!(`set`in e&&`cycle`in e))return;let[t,n,...r]=e.cycle;return t===`closed`&&n!==void 0&&r.length===0?{key:e.set,member:n}:void 0}var aa=ke(((e,t)=>{t.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,t.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,t.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/})),oa=ke(((e,t)=>{let n=aa();t.exports={isSpaceSeparator(e){return typeof e==`string`&&n.Space_Separator.test(e)},isIdStartChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`$`||e===`_`||n.ID_Start.test(e))},isIdContinueChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`$`||e===`_`||e===`‌`||e===`‍`||n.ID_Continue.test(e))},isDigit(e){return typeof e==`string`&&/[0-9]/.test(e)},isHexDigit(e){return typeof e==`string`&&/[0-9A-Fa-f]/.test(e)}}})),sa=ke(((e,t)=>{let n=oa(),r,i,a,o,s,c,l,u,d;t.exports=function(e,t){r=String(e),i=`start`,a=[],o=0,s=1,c=0,l=void 0,u=void 0,d=void 0;do l=v(),ne[i]();while(l.type!==`eof`);return typeof t==`function`?f({"":d},``,t):d};function f(e,t,n){let r=e[t];if(typeof r==`object`&&r)if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=String(e),i=f(r,t,n);i===void 0?delete r[t]:Object.defineProperty(r,t,{value:i,writable:!0,enumerable:!0,configurable:!0})}else for(let e in r){let t=f(r,e,n);t===void 0?delete r[e]:Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}return n.call(e,t,r)}let p,m,h,g,_;function v(){for(p=`default`,m=``,h=!1,g=1;;){_=y();let e=x[p]();if(e)return e}}function y(){if(r[o])return String.fromCodePoint(r.codePointAt(o))}function b(){let e=y();return e===`
@@ -204,9 +204,9 @@ Config tooling:
204
204
  New: { h: ["seg1", "seg2"] }`,line:J(e.source,[`root`])}),wJ;if(n.kind===`group`){let r=zy(e,GJ,t,n);return r===null?wJ:(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}),qJ(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:J(e.source,[`root`])}),wJ}if(a){let r=zy(e,NJ,t,n);return r===null?wJ:{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=zy(e,PJ,t,n);return r===null?wJ:{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=zy(e,FJ,t,n);return r===null?wJ:{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:J(e.source,[`root`])}),wJ};function LJ(){return{required:!0,json:{type:`object`,propertyNames:{pattern:xx.source},additionalProperties:{$ref:CJ}},parse:(e,t,n,r)=>{let i=r[n];if(!Bv(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${Ly(i)}`,line:J(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!xx.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:J(e.source,[...t.split(`.`),n,r])});continue}a[r]=IJ(e,`${t}.${n}.${r}`,o)}return a}}}const RJ={noun:`root key`,fields:{rows:LJ(),when:Xy(),distribution:AJ()}};function zJ(e,t,n){return Bv(n)&&`rows`in n?zy(e,RJ,t,n)??{rows:{}}:IJ(e,t,n)}const BJ={noun:`insert key`,fields:{seg:MJ(),id:iV(),before:Xy(),after:Xy()}};function VJ(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=zy(e,BJ,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:J(e.source,i.split(`.`))}),[];if(rS(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:J(e.source,[...i.split(`.`),`seg`])}),[];let s=o[0],c=a[s];return rS(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:J(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 ${Ly(t)}`,line:J(e.source,[`insert`])}),[])}function HJ(){return{required:!0,json:{type:`string`,pattern:xx.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!xx.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 "${Wi}", got ${Ry(i)}`,line:J(e.source,[`root`])});return}return i}}}function UJ(){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 ${Ry(i)}`,line:J(e.source,[`root`])});return}return i}}}}function WJ(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=My(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:J(e.source,[...t.split(`.`),n])});return}return i}}}}const GJ={noun:`layout-node key`,fields:{kind:TJ(`group`),name:HJ(),label:WJ(),open:Zy(),direction:ib(Uv),key:UJ(),bg:Xy(),fg:Xy(),when:Xy(),distribution:AJ(),children:OJ(Jy(()=>IJ))}};function KJ(e){return e.key??`groups.`+e.name}function qJ(e){let t=Zx+e.name;return Xi(t,{variable:t,key:KJ(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function JJ(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function YJ(e,t){iP(e,t,Zx,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&JJ(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}.`)&&KJ(t)===KJ(r)&&JJ(e,t.path,`group "${t.name}" shares key "${KJ(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=KJ(t);if(i.has(n)||i.set(n,Wi),t.open===!0){let r=i.get(n);r!==`closed`&&JJ(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=Zx+e.name,r=KJ(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=na(r,i.get(r)),o[t]=ra(r,e.name),s[t]={template:$i(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 XJ=`menu`,ZJ=`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`,QJ=e=>e.kind===`call`&&e.name===`dict`,$J=e=>e.kind===`literal`&&typeof e.value!=`object`,eY=e=>qi(``,e,2)===void 0;function tY(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&&QJ(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(QJ))return t(`whose options (dict …) is not its last argument — ${ZJ}`);if(i!==void 0&&a===void 0&&!$J(i)&&eY(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=qi(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${ZJ}`);let c=a===void 0?{}:YD(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=QM(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=rP(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 "${KM(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 nY(e){let t=iE({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===XJ).map(tY)}catch{return`parse-failed`}}function rY(e,t){let n=nY(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:GM(t,e.apply,e.options.key),member:WM(e.apply)}]:[])}function iY(e){let t=iE({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(XJ)}catch{return!1}}function aY(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function oY(e,t){iP(e,t,Qx,`{{ menu }} helpers`),iP(e,t,$x,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))iY(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:J(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`&&iY(i)&&aY(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??{}))iY(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:J(e.source,[`segments`,t,`partials`,n])})}if(t.root!==void 0)for(let n of Yv(Ex(t.root)))typeof n.when==`string`&&iY(n.when)&&aY(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||!iY(r))continue;let n=nY(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:sY(r.apply);n!==void 0&&aY(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function sY(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(WM(e)===`closed`)return`whose apply action is named "${Wi}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function cY(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 Fx(e.presets)){let a=new Map,s=new Map;for(let c of Yv(Rx(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,nY(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=Gv(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||sY(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=WM(i),f=GM(u,i,l.key),p=JM(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=qM(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]=ra(f,d),n[f]=na(f,Wi),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 lY(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const uY={noun:`style key`,fields:{hueShift:$y(),chromaScale:$y({min:0}),lightnessScale:$y(),lightnessShift:$y()}};function dY(e,t){if(!Bv(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${Ly(t)}`,line:J(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:J(e.source,[`styles`,r])});continue}if(Ov(r)){e.issues.push({path:`styles.${r}`,message:lY(`styles.${r}`,r,`globals.endcaps`),line:J(e.source,[`styles`,r])});continue}let t=zy(e,uY,`styles.${r}`,i);t!==null&&(n[r]={...Xl,...t})}return n}const fY={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:zJ(e,`${t}.${n}`,r[n])},globals:{required:!1,json:FN(),parse:(e,t,n,r)=>r[n]===void 0?void 0:PN(e,`${t}.${n}`,r[n])}}};function pY(e,t){if(!Bv(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${Ly(t)}`,line:J(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:J(e.source,[`presets`,r])});continue}let t=zy(e,fY,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function mY(e,t){let n=[...t].map(([e,t])=>[rC(e),t]);return t=>{if(pR(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=aC(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function hY(e){return e.kind===`plugin`||e.kind===`missing`}function gY(e,t,n){let r=new Map,i=(e,t)=>{r.set(e,[...r.get(e)??[],t])},a=e=>Cx(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 Yv(e))t.kind===`segment`&&i(Gv(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 _Y(e){let t=0,n=mY(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)?[Jv(e,i)]:[],o=e=>a(e)[0]??vY,s=e=>({...e,rows:Object.fromEntries(Object.entries(e.rows).map(([e,t])=>[e,o(t)]))}),c=e=>Cx(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 vY={kind:`container`,direction:`horizontal`,children:[]},yY={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 bY(e,t){let n=new Map;for(let e of Object.keys(t)){let t=UM(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:J(e.source,[`presets`])})}function xY(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 Dx(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const SY=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${nC(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${CY(nC(r.definition),n)}${wY(t,n)}`:`${e} entry "${t}" does not match any declared segment${wY(t,n)}`;function CY(e,t){let n=Object.keys(t).filter(rC(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 wY(e,t){return tB(e)+oC(e,e=>Object.hasOwn(t,e))}function TY(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||uv(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:Ov(r)?lY(i,r,a):`${i} "${r}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:J(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:J(e.source,[`globals`,`preset`])}),bY(e,t.presets);let a=VC(t);for(let t of a.names)t!==`settings`&&!t.startsWith(OY)||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:J(e.source,[`variables`,t])});let o=(t,n,i)=>{gR(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${iS}" ${gR(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}),_R(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${iS}" 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:yY[a](n),line:i});let o=new Map;for(let e of Yv(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=Gv(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=qv(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`||Wv[e.direction]===`cell`);return Wv[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:Wv[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,Xv(t,n)]):e.opens===void 0?[]:[[e.opens.body,Zv(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=Ex(n),s=Cx(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:yY[t](n),line:J(e.source,n.split(`.`))});for(let[o,s]of Dx(n,i)){let n=J(e.source,s.split(`.`));if(o.when!==void 0&&(WY(e,`${s}.when`,o.when,a,{line:n}),HY(e,`${s}.when`,o.when,n),UY(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if(pR(o.name)){(o.id!==void 0||o.settings!==void 0)&&e.issues.push({path:s,message:`${i} gives the global settings menu anchor "${iS}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${iS}"`,line:n});continue}let c=r(o.name);hY(c)&&(d.add(o.name),e.unplaced.push({path:s,message:SY(i,o.name,t.segments,c),line:n})),IY(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`,Tx(t.root)]]);for(let e of Fx(t.presets)){let{node:n,path:r}=Rx(t,e);p.set(r,n)}for(let[t,n]of p)o(n,t,J(e.source,t.split(`.`)));for(let[n,i]of p)for(let[a]of Qv(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);hY(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:SY(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:J(e.source,n.split(`.`))}))}QY(e,t,a,()=>!0)}const EY=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function DY(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=J(e.source,[`actions`,n,r]);if(!Fx(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Fx(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(`, `)})${tB(i)}`,line:c})},p=new Set(Kv(Rx(t,a).node)),m=(r,i)=>{!eB.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${tB(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 OY=`settings.`;function kY(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>OY+e)])}}function AY(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:J(e.source,[`segments`,t,`settings`,n])})},a=NY(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of py(n,MY(n)))i(e,`the defaults do not stand together: ${t}`)}function jY(e){return NY(e).length>0||py(e,MY(e)).length>0}function MY(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function NY(e){let t=t=>fy(PY(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||fy(PY(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${FY(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 PY(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function FY(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&fy(n)!==void 0).map(([e])=>e)}function IY(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=dy(a),s=`${r}: placement "${Gv(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(`, `)})`:my(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?tv(a):``}, but it must be ${vy(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])=>my(o[e],t))||jY(o)))for(let{message:t}of py(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function LY(e,t,n,r,i){for(let[a,o]of iy(n))WY(e,`${t}.${a}`,o,r,{segCtx:i})}function RY(e,t,n,r,i){if(!(!ny(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:J(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const zY=`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 BY(e,t,n,r){if(!ny(n))return;let i=n=>J(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=_q(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${zY}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=pq(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}: ${zY}`,line:i(`depends_on`)})})}}function VY(e,t){let n=new Map(RC(t)),r=QG(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=lv.find(e=>zM[e]===n||zM[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${zM[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=XG(e,a),s=o===void 0?void 0:BM(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 hq(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:J(e.source,[...n])})}}function HY(e,t,n,r){try{nP.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function UY(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 EC(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){KY(e,u,`Template references unknown action "${c}"${r}`,GY(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function WY(e,t,n,r,i){let a=(n,r)=>{if(r!==null){KY(e,r,n,GY(r,i?.segCtx===void 0?void 0:{name:i.segCtx,partials:i.partials}));return}e.issues.push({path:t,message:n,line:i?.line??J(e.source,t.split(`.`))})};for(let[e,t]of SC(n,r.helpers)){if(BC(e,r))continue;if(e.startsWith(OY)){let n=t===null?``:` through helper "${t}"`,r=e.slice(9);a(i?.segCtx===void 0||i.settings===void 0?`Template reads ".${e}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${e}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`,null);continue}let n=i?.segCtx!==void 0&&t===null?`${i.segCtx}.${e}`:void 0;a(`Template references unknown variable ".${e}"${n!==void 0&&BC(n,r)?` (segment-local vars are namespaced — write ".${n}")`:fB(e)}`,t)}for(let{literal:e,via:t}of DC(n,r.helpers))a(`Template spells a link in a grammar older than names, which names no renderer: "${e}". Bind an action instead ({{ action "name" … }}): its link names the renderer that draws it`,t)}function GY(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function KY(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:J(e.source,r)})}function qY(e,t,n,r,i){let a=n.set,o=vN(ix[r].configKey),s=`${a} takes ${tN(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:J(e.source,[`actions`,t,`min`])});return}let c=XY(n,i);if(c===YY){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:J(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!eN(o,e.value,i));if(l.length!==0){if(a===ix.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>Ov(e.value)))){let r=ix.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:lY(`actions.${t}.to`,n.to,`set: "${r}", to`),line:J(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:J(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<=JY?r.join(`, `):`${r.slice(0,JY).join(`, `)} and ${r.length-JY} 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:J(e.source,[`actions`,t,n])})}}}const JY=3,YY=Symbol(`any integer`);function XY(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?Gx(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)}]:YY}function ZY(e,t){return Object.entries(e).filter(([e])=>t(e))}function QY(e,t,n,r){let i=WR(t),a=Wx(i);for(let[n,o]of ZY(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 ${Kx(r,i)}`,line:J(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;cx.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:J(e.source,[`actions`,n,`set`])});let s=fx.get(o.set);s!==void 0&&qY(e,n,o,s,i)}for(let[n,i]of ZY(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&&vte(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:J(e.source,[`actions`,n,`do`])})});for(let[n,i]of ZY(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:J(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of ZY(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=ZN(r);if(o===null){let t=zN(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${BN().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:J(e.source,[`actions`,n,a])});continue}let s=EY.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:J(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){DY(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Fx(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: ${Fx(t.presets).join(`, `)})`,line:J(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${tv(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:J(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(`, `)})${tB(o.segment)}`,line:J(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:J(e.source,[`actions`,n,a])})}}for(let[i,a]of ZY(t.variables,r)){LY(e,`variables.${i}`,a,n);let t=dB(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:J(e.source,[`variables`,i])})}for(let[i,a]of ZY(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))LY(e,`segments.${i}.vars.${t}`,r,n,i);let r=dy(a);if(AY(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:J(e.source,[`segments`,i,`partials`,t])});let o=a.partials===void 0?n.helpers:{...n.helpers,...a.partials},s=kY({...n,helpers:o},r);for(let n of PH){let c=a[n];typeof c==`string`&&(WY(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),UY(e,t,`segments.${i}.${n}`,c,J(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of ZY(t.variables,r))RY(e,`variables.${i}`,a,n),BY(e,`variables.${i}`,a,t);VY(e,t);for(let[i,a]of ZY(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))RY(e,`segments.${i}.vars.${r}`,o,n,i),BY(e,`segments.${i}.vars.${r}`,o,t)}function $Y(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=eX(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:J(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function eX(e){let t=new Map,n=new Map,r=QG(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 tX(e,t,n){let r=new Map([...LC(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:J(e.source,[...d])})}}}function nX(e){return{...dX,config:Xz(dX.raw,e)}}function rX(e,t,n,r,i){let a=vX(e,t,i,(t,a)=>{let o=SH(xH(t,e,r.scope,r.home),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>lX(t,n,r,e,i)),s=EH(o,r.beneath.dropped);return{inherited:new Set([...oV(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=DH(Xz(a.raw,o.config),s,(a.raw.insert??[]).map(e=>e.seg));return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(fH)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const iX=new WeakMap;function aX(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e.path,e.scope,sX(e.path)])]),a=iX.get(n)??new Map;iX.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=SH(e,t,{config:n,rendering:new Map},(e,t,n)=>lX(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function oX(e,t,n,r){return SH(e,{repo:null,checkout:n,home:r},{config:t,rendering:new Map},(e,t,n)=>lX(e,t,n,`<plugin install>`,void 0)).dropped}function sX(e){try{let t=m.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function cX(e,t,n,r,i,a=e=>m.readFileSync(e,`utf-8`),o){let s={repo:i.repo,checkout:i.cwd===null?null:Ks(i.cwd),home:e.homeDir},c=QH(e,s.repo),l=aX(c.definitions,s,n,o),u={...l,dropped:[...l.dropped,...c.strays]};r.warned(c.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let d=u.config,f=[];for(let{path:e,scope:n}of t){let t=f.at(-1)?.plugins,i=rX(e,a(e),f.at(-1)?.config??d,{...s,scope:n,beneath:{dropped:[...u.dropped,...f.flatMap(e=>e.plugins.dropped)],rendering:t?.rendering??u.rendering}},o);r.warned(i.warnings),f.push({...i,path:e})}let p=new Set(f.flatMap(e=>[...e.plugins.reached])),h=e=>p.has(e.path),g=u.dropped.filter(h),_=u.dropped.filter(e=>!h(e));r.warned(g.map(fH));let v=f.at(-1)?.plugins.rendering??u.rendering,y={checkout:s.checkout,roots:c.roots,loaded:u.loaded,dropped:g,unreached:_,reached:p,rendering:v},b=f.at(-1),x=({warnings:e,...t})=>(r.warned(e),t);if(b===void 0)return{layers:f,base:d,installed:y,...x(fX(nX(d),v,`<default>`,o))};try{return{layers:f,base:d,installed:y,...x(fX(b,v,b.path,o,f.slice(0,-1).reverse()))}}catch(e){for(let[e,t]of f.slice(0,-1).entries())fX(t,t.plugins.rendering,t.path,o,f.slice(0,e).reverse());throw e}}function lX(e,t,n,r,i){if(n){fX(uX(e),new Map,r,i);return}let a=rC(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[],unplaced:[],inherited:[]};if(QY(s,e,VC(e),a),$Y(s,e,a),tX(s,e,{checked:a,authored:a}),o.length>0)throw new xy(r,o)}function uX(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const dX={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function fX(e,t,n=`<config>`,r=new Set(iv()),i=[]){let a=mY(e.config.segments,t),o=mX({...e,path:n},i,a),s=(t,s)=>{let c=hte(e.config,t,o.authored);return pX(e,n,r,i,c.config,a,o.dropped,[...c.notices,...s])};try{return s(o.cells,[])}catch(e){if(!(e instanceof xy)||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 xy))throw r;let i=r.issues.filter(e=>!n.has(e.message)).map(e=>e.message).join(`; `);return{...e,refused:[...e.refused,zx(t,`${t.relation} "${t.anchor}", but the bar refuses it there: ${i}`)]}}},{taken:[],refused:[]});return s(r,i)}}function pX({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 xy(n,[...l,...u.unplaced,...u.inherited],c)};TY(u,a,e,o),$Y(u,a),d();let f=gX(n,a.segments,u,o,i,s),p=cY(_Y(a),l);d();let m=fz(OR(p)),h=new Set([...LC({variables:e.variables??{},segments:e.segments??{}})].map(([e])=>e));return tX(u,m,{checked:()=>!0,authored:e=>h.has(e)}),d(),{config:m,dropped:f,placed:a,warnings:c}}function mX(e,t,n){let r=[...t].reverse().concat(e),i=gY(e.config,r.flatMap(e=>e.raw.insert??[]),n),a=e=>!i(e.anchor),o=e=>n(e.seg).kind===`declared`,s=e=>hY(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=wy(t.source);return(t.raw.insert??[]).filter(s).map(i=>({file:t.path,issue:{path:i.by.entry,message:SY(i.by.entry,i.seg,e.config.segments,n(i.seg)),line:r(i.by.entry.split(`.`))}}))})}}function hX(e){if(e.length>0)throw new Cy(e)}function gX(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=xY(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:SY(n.layoutKey,a,t,r(a)),line:J(n.layer.source,n.path.split(`.`))})}return[...o].map(([e,t])=>new Sy(e,t))}function _X(e,t,n=new Set(iv()),r=yX){return vX(e,t,n,()=>({inherited:r,layer:null})).raw}function vX(e,t,n,r){let i=bX(e,t),a=Ay(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(iv()),groups:[],unplaced:[],inherited:[]};if(!Bv(i))throw new xy(e,[{path:``,message:`Config root must be an object, got ${Ly(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:CX({...c,issues:[]},i.plugins)??[],Bv(i.segments)?Object.keys(i.segments):[]),d=xX(c,i,l,xV(e),e);if(s.length>0)throw new xy(e,s,o);return{raw:d,warnings:o,layer:u}}const yX=new Set;function bX(e,t){try{return la.default.parse(t)}catch(t){let n=t;throw new xy(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function xX(e,t,n,r,i){for(let n of Object.keys(t))SX.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...SX].join(`, `)}`,line:J(e.source,[n])});let a={};return t.globals!==void 0&&(a.globals=NN(e,`globals`,t.globals)),t.variables!==void 0&&(a.variables=yB(e,`variables`,t.variables)),t.segments!==void 0&&(a.segments=sV(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.
205
205
  Replace: layout: [["seg1", "seg2"], ["seg3"]]
206
206
  With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
207
- Single-row example: root: { h: ["seg1", "seg2"] }`,line:J(e.source,[`layout`])}),t.root!==void 0&&(a.root=zJ(e,`root`,t.root)),t.insert!==void 0&&(a.insert=VJ(e,t.insert,i)),t.actions!==void 0&&(a.actions=yV(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:J(e.source,[`looks`])}),t.styles!==void 0&&(a.styles=dY(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=MN(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=pY(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=IN(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=vV(e,t.helpers)),t.plugins!==void 0&&(a.plugins=CX(e,t.plugins)),YJ(e,a),oY(e,a),gP(e,a),iP(e,a,tS,`the global settings menu`),aP(e,a,n),a}const SX=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function CX(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 ${Ly(t)}`,line:J(e.source,[`plugins`])})}const wX={},TX=BI(`commands.`),EX=KI(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),DX=PI(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),OX=`{{ ${jP} }}`,kX={min:0,max:100,step:5},AX={warnAt:{label:`warning at %`,domain:kX,default:50},errorAt:{label:`error at %`,domain:{...kX,atLeast:`warnAt`},default:80}};function jX(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:kX,default:80}}}const MX={globals:{palette:`tokyo-night`},variables:{...TX.variables,...IM,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:`⊫`},...DX.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:OX},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 ${DX.armed} }}{{ if ne .git.branch "" }} {{ end }}${DX.template}{{ end }}`,fg:OX,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:OI(``).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:TX.template,when:TX.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:jX(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:jX(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:AX,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:AX,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) ${A_} }}`,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:EX.template,bg:EX.bg,when:EX.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:{...OI(``).actions,...TX.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...DX.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...EX.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:wX,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 ${A_} }}{{ \$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 (${jP}) 2 (readableOn (color "accent") (bgOf) ${A_})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${A_}) .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:qI(`.`),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 .)) }}`}},NX=new Set([MX.globals.palette,...Object.keys(MX.themeDefaults),...Object.values(MX.segments).map(e=>e.palette)].filter(e=>e!==void 0)),PX=Xz(_X(`<default>`,JSON.stringify(MX),NX),MX),FX=Fx(PX.presets);function IX(e){return FX.includes(e)}const LX={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0};function RX(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function zX(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function BX(e,t,n){return{[zX(ot(e))]:{...LX,cost:t,input:n}}}function VX(e,t){let n=zX(ot(t)),r=e.sums[n],i=e.own[n];if(r===void 0&&i===void 0)return L;let a={...LX};return r!==void 0&&RX(a,r),i!==void 0&&RX(a,i),I({cost:a.cost,tokens:a.input+a.output+a.cacheCreation+a.cacheRead,tokenBreakdown:{input:a.input,output:a.output,cacheCreation:a.cacheCreation,cacheRead:a.cacheRead},date:n})}function HX(e,t,n){return an({dir:e.project_dir,env:n===void 0?[]:[[bo,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}const UX=[`session`,`today`,`context`,`metrics`,`activity`,`cache`,`speed`,`autocompact`];var WX=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:R(n,`read`)}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)})}};function GX(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function KX(e){return{...Object.fromEntries(Yb.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:IX(e.preset)}}}const qX={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function JX(e){if(eo(e))return`pending`;let{prState:t,prError:n,prEarlier:r}=e??{};return eo(t)?`pending`:t===void 0?n===void 0?r===void 0?`-`:`earlier-${String(r)}`:`failed`:t}const YX=10*1e3;function XX(e,t){if(!(t<60))return e*3600/t}function ZX(e,t,n,r){let i=r-t;if(i<50||i>YX)return;let a=n-e;if(!(a<=0))return a*1e3/i}function QX(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=ZX(t.input,t.atMs,n.input,n.atMs),i=ZX(t.output,t.atMs,n.output,n.atMs),a=ZX(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 $X(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>YX)continue;let o=ZX(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function eZ(e){return Vq(e.termCols??120)}function tZ(e,t){return Co(So(e.claudeConfigDir,t))}function nZ(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function rZ(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=r.session_id,s=i.usageStore.request(o,r.transcript_path),c=async(e,t)=>{let r=i.clock.monotonic();n.set(e,null);let a=null;try{await t()}catch(t){i.log(`error`,`${e} lane threw: ${E(t)}`),a=`${e}: ${String(t)}`}n.set(e,A(i.clock,r)),i.faults.refreshed(o,e,a)};await Promise.all([c(`session`,()=>s.usage(r)),c(`today`,()=>s.today()),c(`context`,()=>i.contextProvider.getContextInfo(r)),c(`metrics`,()=>i.metricsProvider.getMetricsInfo(o,r)),c(`activity`,()=>i.activityProvider.getActivityInfo(o,r)),c(`cache`,()=>i.cacheExpiry.refresh(o,r.transcript_path)),c(`speed`,()=>s.speed(ot(t).getTime())),c(`autocompact`,async()=>i.autoCompact.window(tZ(a,i.home)))])}function iZ(e,t){let n=Xj(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}const aZ={showSha:!0,showWorkingTree:!0,showStashCount:!0,showUpstream:!0,showRepoName:!0,showRepoUrl:!0,showOperation:!0,showCommittedAt:!0,showPullRequest:!0};function oZ({cwd:e,hookData:t}){return[e??t.workspace?.current_dir,aZ,t.workspace?.project_dir]}function sZ(e,t,n,r){let i=n.hints.tmux??null,a=[],o=(e,t)=>{try{return t()}catch(t){return a.push(`${e}: ${E(t)}`),Xj(R(`${e}: ${String(t)}`,`read`))}};return{lanes:{git:o(`git`,()=>e.gitProvider.declare(t,...oZ(n))),tmux:i===null?Xj(L):o(`tmux`,()=>e.tmuxService.declare(t,i)),hostName:o(`host.name`,()=>e.hostService.declareName(t)),hostUser:o(`host.user`,()=>e.hostService.declareUser(t)),today:o(`today`,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map([...r].map(([r,i])=>[r,o(r,()=>e.managedStorage.declare(t,i,n.sessionId))]))},faults:a}}function cZ(e){let{hookData:t,deps:n}=e,r=t.session_id,i=n.lanes(),a=(e,t)=>{let i=n.faults.of(r,e);if(i!==void 0)return i;try{return t()}catch(t){return n.log(`error`,`${e} read threw: ${E(t)}`),R(`${e}: ${String(t)}`,`read`)}};return{lanes:{git:i.git.current(),usage:a(`session`,()=>n.usageStore.usageOf(r,t)),context:a(`context`,()=>n.contextProvider.contextOf(t)),metrics:a(`metrics`,()=>n.metricsProvider.metricsOf(r,t)),activity:a(`activity`,()=>n.activityProvider.activityOf(r)),tmuxSession:i.tmux.current(),hostName:i.hostName.current(),hostUser:i.hostUser.current(),cache:a(`cache`,()=>n.cacheExpiry.expiryOf(r)),speed:a(`speed`,()=>n.usageStore.speedOf(r)),autoCompact:a(`autocompact`,()=>n.autoCompact.stored(tZ(e.hints,n.home))),sources:new Map([...i.sources].map(([e,t])=>[e,t.current()]))},today:a(`today`,()=>lZ(i.today,n.usageStore,r)),faults:UX.flatMap(e=>{let t=n.faults.of(r,e);return t===void 0?[]:[{lane:e,reason:t.reason}]})}}function lZ(e,t,n){let r=e.current();if(r.kind!==`ok`)return r;let i=t.daysOutside(n,r.value.roots);return i.kind===`failed`?i:I({sums:r.value.sums,own:i.kind===`ok`?i.value:{}})}function uZ(e){return[e.git.current(),e.tmux.current(),e.hostName.current(),e.hostUser.current(),...[...e.sources.values()].map(e=>e.current())].flatMap(e=>e.kind===`pending`&&e.why===`unread`?[e.landed]:[])}function dZ(...e){let t=e.find(e=>e?.kind===`pending`);return t?.kind===`pending`?$a(t.why):void 0}const fZ=e=>{switch(e.kind){case`pending`:return e;case`absent`:return L;case`ok`:return I(e.value);case`failed`:return R(e.reason,e.failedAt)}};function pZ(e,t,n){let{hookData:r,hints:i}=t,{effective:a,configFacts:o}=n,{configPath:s,...c}=o,l=e.builtins,u={usage:fZ(l.session),context:fZ(l.context),metrics:fZ(l.metrics),activity:fZ(l.activity),cache:fZ(l.cache),speed:fZ(l.speed),autoCompact:fZ(l.autocompact),git:fZ(l.git),pr:fZ(l.pr),tmux:fZ(l.tmux),hostName:fZ(l.hostName),hostUser:fZ(l.hostUser)},d=(e,t)=>{switch(e.kind){case`pending`:return $a(e.why);case`failed`:case`absent`:return;case`ok`:return t(e.value)}},f=e=>e.kind===`ok`?e.value:void 0,p=i.tmux??null,m=u.git.kind===`pending`?$a(u.git.why):u.git.kind===`ok`?TZ(u.git.value,u.pr,$a):void 0,h=u.tmux.kind===`pending`?$a(u.tmux.why):f(u.tmux)?.session,g=u.hostName.kind===`pending`?$a(u.hostName.why):f(u.hostName),_=u.hostUser.kind===`pending`?$a(u.hostUser.why):f(u.hostUser),v=dZ(u.context)??bZ(u.autoCompact,f(u.context)?.maxTokens),y=r.rate_limits?.five_hour,b=r.rate_limits?.seven_day,x=dZ(u.usage,u.metrics)??gZ(f(u.usage)?.session.cost,f(u.metrics)?.sessionDuration),S=d(u.speed,_Z),C=d(u.usage,e=>CZ({cost:e.session.cost,tokens:e.session.tokens})),ee=d(u.metrics,e=>CZ({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),w=d(u.activity,xZ),te=d(u.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),ne=d(u.cache,e=>({expiresAt:e})),T=wZ(t.home),re=r.workspace?{...r.workspace,current_dir:wZ(r.workspace.current_dir)??``,project_dir:wZ(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>wZ(e)??e)}:r.workspace,E=r.session_id;return{...r,...re!==void 0&&{workspace:re},...T!==void 0&&{home:T},...m!==void 0&&{git:m},...r.location!==void 0&&{location:{...r.location,main:wZ(r.location.main)??``}},...p!==null&&{tmux:{pane:p.pane,...h!==void 0&&{session:h}}},host:{...g!==void 0&&{name:g},..._!==void 0&&{user:_},...i.ssh!==void 0&&{ssh:i.ssh}},...KX(a),history:n.history,navigation:{back:n.back},term:{cols:eZ(i)},...c,...s!==null&&{configPath:s},resumeCommand:HX(re,E,i.claudeConfigDir),...C!==void 0&&{session:C},...x!==void 0&&{burn:x},...S!==void 0&&{speed:S},...y!==void 0&&{block:{nativeUtilization:y.used_percentage,resetsAt:y.resets_at}},...b!==void 0&&{weekly:{percentage:b.used_percentage,resetsAt:b.resets_at}},...ne!==void 0&&{cache:ne},...te!==void 0&&{context:te},...ee!==void 0&&{metrics:ee},...w!==void 0&&{activity:w},...v!==void 0&&{autocompact:v},...hZ(Object.keys(e.sources),t=>{let n=fZ(e.sources[t]);return n.kind===`pending`?$a(n.why):n})}}function mZ(e){let t=Object.entries(e);return{sources:String(t.length),sourcesPending:t.flatMap(([e,t])=>t.kind===`pending`?[`${e}:${t.why}`]:[]).join(`,`)||`-`}}function hZ(e,t){let n=Object.fromEntries(tC.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 gZ(e,t){let n=e!=null&&t!=null?XX(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function _Z(e){let t=QX(e),n=$X(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function vZ(e,t){if(e.kind===`pending`)return $a(e.why);if(e.kind!==`ok`)return;let n=VX(e.value,t);return n.kind===`ok`?{cost:n.value.cost,tokens:n.value.tokens}:void 0}async function yZ(e,t,n){await rZ(e,t,n),await qj(()=>{let t=uZ(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function bZ(e,t){switch(e.kind){case`pending`:return $a(e.why);case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return GI(e.value,t)}}function xZ(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=SZ(e.running),i=SZ(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 SZ(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function CZ(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 wZ(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function TZ(e,t,n){let r=e=>e?.kind===`ok`?e.value:void 0,i=r(e.aheadBehind),a=r(e.sha),o=r(e.operation),s=r(e.committedAt),c=r(e.stashCount),l=r(e.upstream),u=e.upstream===void 0?void 0:r(Hq(e.upstream,e.aheadBehind)),d=r(e.repoName),f=r(e.repoUrl),p=t.kind===`pending`?t:Uq(t,e.head),m={};switch(p.kind){case`pending`:{let e=n(p.why);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`:break}return{branch:e.branch,status:e.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...e.workingTree!==void 0&&{staged:e.workingTree.staged,unstaged:e.workingTree.unstaged,untracked:e.workingTree.untracked,conflicts:e.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 EZ=Object.freeze({});function DZ(e,t){return e.kind===`decided`?t[e.name]??EZ:EZ}function OZ(e,t){return{...e,...Object.fromEntries(Zb.map(n=>[n,e[n]??t[n]]))}}const kZ=(e,t)=>yb(n=>{let{setting:r,on:i,inTmux:a}=fb[n].switch;return e[r]===i&&(t||!a)});function AZ(e,t,n,r){let i=$b(e);return rv(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function jZ(e,t){return Ix(t(`preset`),e.globals.preset,e.presets)}function MZ(e,t,n){let r=jZ(e,t),i=Bx(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=ute(a.palette,t(`theme`),i.palette),s=OZ(i,DZ(o,e.themeDefaults));return{...Object.fromEntries(Yb.map(e=>[e,AZ(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:hv(a.style,t(`style`),s.style,e.styles),effect:Tv(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}const NZ={moving:1e3/30,still:1e3},PZ=[`data`,`state`,`reload`,`visibility`];function FZ(e){return pb.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 IZ(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const LZ=(e,t)=>fb[t].handsOff?e.resp:e.statusline,RZ=e=>Math.round(1e3/e);var zZ=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 bb;let r=t-1,i=this.shown(n);return yb(e=>{let a=n.rates.get(e);if(a===void 0)return _b;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: ${E(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,RZ(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||LZ(a,t)!==LZ(i,t))&&IZ(r,n);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let n=LZ(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:gN(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=nM.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=${RZ(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${PZ.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 BZ(e,t){return pb.filter(n=>e[n]&&fb[n].handsOff&&t.has(n))}function VZ(e,t,n){return{severity:OU,lines:[[kU(`[⟲ claude]`,GS(e,[{verb:xS,args:[t,...n.map(e=>fb[e].switch.setting)]}]))]]}}function HZ(e,t){for(let n of Object.entries(t))e.push(n)}const UZ={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function WZ(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,E(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function GZ(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...WZ(n)];return{level:UZ[n.kind],line:KZ(e,i)}}const KZ=(e,t)=>`${e}${t.map(([e,t])=>` ${e}=${z(t)}`).join(``)}`;function qZ(e,t,n){if(t.kind===`pending`)return $a(t.why);if(e!==void 0&&e.kind!==`pending`){let{at:n,...r}=e;if((0,Y.compareStructural)(r,t))return e}return{...t,at:n}}const JZ=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`]),YZ=[[`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`]],XZ=[[`workspace.added_dirs`,`string-list`]];function ZZ(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of YZ){let i=eQ(n,e);if(i==null)t.missingRequired.push(e);else{let n=QZ(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of XZ){let i=eQ(n,e),a=i===void 0?r:$Z(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))JZ.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function QZ(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function $Z(e){return Array.isArray(e)&&e.every(e=>QZ(e)===`string`)?`string-list`:QZ(e)}function eQ(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 tQ(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}}function nQ(e){let t=tQ(e);if(!t.ok)throw Error(`session id ${t.problem}`);return t.id}new Set(UX);function rQ(e){let t=e.kind===`recording`?{kind:e.kind,v:2,session:e.session,home:e.home}:e.kind===`facts`?{kind:e.kind,at:e.at,facts:e.facts}:e.kind===`draw`?{kind:e.kind,request:e.request}:{kind:e.kind,...e.kind===`request`&&{at:e.at},hookData:e.request.hookData,cwd:e.request.cwd,hints:e.request.hints};return`${JSON.stringify(t)}\n`}function iQ(e,t){let n=new Map,r=!1,i=(e,t,r)=>{let i=n.get(e);i===void 0||!i.delete(t)||(i.size===0&&n.delete(e),t.detach(),t.sink.end(r))},a=(e,n,r)=>{try{n.sink.write(r),r.kind===`facts`&&(n.document=r.facts),(r.kind===`request`||r.kind===`declared`)&&(n.declaration=r.request)}catch(r){t(`error`,`recording sid=${JSON.stringify(e)}: ${E(r)}`),i(e,n,{kind:`failed`,error:r})}},o=(t,n)=>{let r=e.sessionView(t);n.detach=r===null?()=>{}:(0,Y.reaction)(()=>r.followed.stamped(),(e,r,i)=>{n.detach=()=>i.dispose(),a(t,n,{kind:`facts`,...e})},{fireImmediately:!0})};return{record(t,s){if(r)throw Error(`the daemon is closing: it records nothing more`);let c=e.sessionView(t);if(c===null)throw Error(`no view of session ${JSON.stringify(t)} is open in this daemon: it has not drawn a bar here since the daemon started, or its view closed while it was idle`);let l={sink:s,detach:()=>{},document:null,declaration:null},u=n.get(t)??new Set;return n.set(t,u.add(l)),a(t,l,{kind:`recording`,session:t,home:c.source.home()}),u.has(l)&&o(t,l),()=>i(t,l,{kind:`stopped`})},moved(e){for(let t of n.get(e)??[])t.detach(),o(e,t)},arrived(e,t){let r=new Set;for(let i of n.get(e)??[])a(e,i,{kind:`request`,...t}),r.add(i);return{at:t.at,noted:r}},drew(e,{at:t,noted:r},{document:i,declaration:o}){for(let s of n.get(e)??[]){if(!r.has(s))continue;let c=[...s.document===i.facts?[]:[{kind:`facts`,...i}],...s.declaration===o?[]:[{kind:`declared`,request:o}],{kind:`draw`,request:t}];for(let t of c)n.get(e)?.has(s)&&a(e,s,t)}},close(){r=!0;for(let[e,t]of n)for(let n of t)i(e,n,{kind:`closed`})}}}function aQ(e,t){let n=null,r=iQ({sessionView:e=>{if(n===null)throw Error(`a recorder read its cache before the cache was built`);return n.sessionView(e)}},t);return n=e({onSessionViewMoved:e=>r.moved(e)}),{cache:n,recorder:r}}function oQ(e,t,n){let r=e.arrived(t.sessionId,{at:n,request:t.facts()});return{...t.settle(n),arrival:r}}function sQ(e,t,n,r){let i=r();return e.drew(t.sessionId,n,{document:t.source.stamped(),declaration:t.facts()}),i}var cQ=class extends Error{name=`RecordingFailed`};function lQ(e,t,n,r,i,a){return new Promise((o,s)=>{let c;try{c=S(r,`wx`,384)}catch(e){s(Error(e.code===`EEXIST`?`${r} already exists: a recording writes a new file`:`${r} cannot be created: ${String(e)}`));return}let l=0,u=0,d=()=>{},f=t.after(i*1e3,()=>d()),p=()=>d(),m={write:e=>{h(c,rQ(e)),l++,e.kind===`draw`&&u++},end:e=>{f(),a.removeEventListener(`abort`,p);let t=e.kind===`failed`?e.error:null;try{g(c),u===0&&ne(r)}catch(e){t??=e}t===null?o({path:r,lines:l,answers:u,daemonClosed:e.kind===`closed`}):s(new cQ(`writing ${r}: ${String(t)}`))}};a.addEventListener(`abort`,p,{once:!0});try{d=e.record(n,m)}catch(e){a.removeEventListener(`abort`,p),f(),g(c),ne(r),s(e)}})}const uQ=()=>{},dQ=e=>({ok:!1,error:e instanceof Error?e.message:E(e),code:`RENDER_FAILED`,daemonV:3}),fQ={ansi:e=>({ok:!0,output:Hte(e)}),frame:e=>({ok:!0,frame:e})};function pQ(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.monotonic(),s=[[`sid`,t]];try{try{var c=no();let i=c.u(yQ(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=xQ(e,i,{by:`feed`,fps:n}),p=fQ.ansi(o.body),m=EQ(e.links.to,t,o,BZ(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:fQ.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}=GZ(`render`,s,{kind:`threw`,error:e},A(i,o)),r=dQ(e);return{bar:Ite(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:uQ,failure:{level:t,line:`frame ${n}`}}}}function mQ(e,t,n){let{sessionState:r}=e;return MZ(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function hQ(e,t){try{var n=no();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:kZ(i.view.source.effective(),rc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function gQ(e,t,n){try{var r=no();let{renderCache:i,frameFeeds:a}=e,o=r.u(i.hold(t.projectDir,t.cwd,t.target.path)),s=a.latest(n);return kZ(mQ(e,n,o.state),s===null||rc(s.hints.tmux))}catch(e){r.e=e}finally{r.d()}}function _Q(e,t,n,r){HZ(n,{renderer:r,at:t.toFixed(3)});let i=e.hints,a=ur(e,i),o=dr(a);return HZ(n,{termCols:String(i.termCols??`?`),termRows:String(i.termRows??`?`),refused:a.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:i.client?.kind??`unreported`,rateLimits:e.rateLimits}),o}function vQ(e,t,n,r){let{renderCache:i}=e,a=t.hookData.workspace?.current_dir??t.cwd,o={...t,hookData:{...t.hookData,...a!==void 0&&s.isAbsolute(a)&&{location:tc(a)}}},c=_Q(o,n,r,e.rendererName);HZ(r,{encoding:o.encoding});let l=o.requested;return bQ(i.holdSession(l.projectDir,l.cwd,l.target.path,o),o,c,n,r)}function yQ(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=_Q(o,n,r,e.rendererName)}catch(e){throw a[Symbol.dispose](),e}return bQ(a,o,s,n,r)}function bQ(e,t,n,r,i){try{let{entry:a,state:o,view:s}=e,{sessionId:c}=t;return{req:t,at:r,facts:i,sessionId:c,entry:a,state:o,view:s,hintsError:n,[Symbol.dispose]:()=>e[Symbol.dispose]()}}catch(t){throw e[Symbol.dispose](),t}}function xQ(e,t,n){let{sessionState:r,frameFeeds:i,renderCache:a,updateWatch:o,links: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.payload(),C=b.source.effective(),ee=b.source.failure(),w=kZ(C,S.tmux!==void 0);HZ(g,{lanes:pb.filter(e=>w[e]).join(`,`)||`-`});let te=b.source.hints(),ne=S.term.cols;HZ(g,{width:String(ne)});let T=Ls(r,_,h,n.by),re=T.kind===`held`||T.kind===`owed`?T.error:null,E=o.notice({to:s.to,sessionId:_,dismissed:r.get(_,Gz),enabled:C.updateNotice}),D=nW(v.repos,_,s),ie=(e,t)=>({about:e,text:t,copy:t}),O=e=>ie(e??``,e),ae=[O(pr(m.refusedArgs)),O(x),ie(`load`,v.lastError),ie(`update-act`,o.error()),...y.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),O(re?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),oe=v.watch===null?null:Aj(`config watch`,v.watch,null),se=p.launcherWarnings(h,n.by),ce=se.find(e=>e.kind===`launch-pipes`),le=ce?.event??null,ue=[...vc(c.delivery()),...se,...oe===null?[]:[{kind:`config-watch`,message:oe}],...v.lastWarning===null?[]:[{kind:`load`,message:v.lastWarning}],...ee===null?[]:[{kind:`facts`,message:`the bar is drawn from the last facts that were read; the next could not be stamped: ${ee}`}]],de={config:y.config},fe=AU(s.to,_,n.by,ae,[...E,...D],[...ue.map(e=>({about:e.kind,message:e.message})),...l.ofSession(_,n.by,de).map(e=>({about:`${e.kind}\0${e.message}`,message:e.message}))].map(e=>({about:e.about,text:e.message,copy:e.message}))),pe=b.source.facts(),me={diagnostics:BU(fe),drawing:n,feeds:i.feedsOf(_,h),today:vZ(pe.builtins.today,h)},he=eo(S.metrics)?void 0:S.metrics;HZ(g,mZ(pe.sources)),HZ(g,{factsSeq:String(pe.seq),prompts:String(he?.messageCount??`-`),nonPrompts:String(he?.nonPrompts??`-`),pr:JX(S.git),feeds:FZ(me.feeds)});let ge=[],_e=GX(C,ne),ve=d.of(_),ye=f.since(_,h),{frame:be,evaluated:xe,cellBreaks:Se,rules:Ce}=Bq(y.config,y.compiled,b.store,b.registry,me,h,_e,{perSegmentSink:b.lastRenderCellsBySegment,onRenderWarning:e=>ge.push(e)},{...C,effects:ve,idleSince:ye}),we=MU(fe),Te=new Map(fe.map((e,t)=>[we[t],e.copy])),Ee=()=>a.delivered(_,n.by,Te);f.observe(_,h,be.rows.some(e=>e.kind===`menu`),C.menuTimeout);let De=f.since(_,h);HZ(g,{menuIdle:De===void 0?`-`:`${(h-De).toFixed(1)}s/${C.menuTimeout}s`});let Oe=l.drawn(_,n.by,de,ge),ke={width:ne,rows:HU(te.termRows,n.by===`feed`?pb.flatMap(e=>{let t=fb[e].rows;return w[e]&&t!==null?[t]:[]}):[]),colorCompatibility:be.depth},Ae=VU(r.get(_,sS),fe),je=Ae===null?be:$P(be,UU(fe,Ae,s.to,_,n.by,ke)),Me=u.gitProvider.getStats(),Ne=u.usageStore.getStats(),Pe=ve.lastFrame(),Fe=Pe.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,k=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,Ie=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`facts`:case`config-watch`:case`lifeline`:case`launch-pipes`:case`when`:return e.kind}},Le=[...ue,...ge].map(Ie).join(`,`)||`-`;return HZ(g,{git:`${Me.size}/${Me.hits}h/${Me.misses}m`,usage:`${Ne.size}/${Ne.hits}h/${Ne.misses}m`,effect:Pe.effect,effectT:Pe.t.toFixed(3),speed:`${Pe.speed}x`,effectRows:`${Pe.made}made/${Pe.reused}reused`,effectOwn:Fe,fadeBasis:Pe.basis,stateRev:String(Pe.revision),fades:k(Pe.fades),leaves:k(Pe.leaves),motion:je.motion,evaluated:String(xe),cellBreaks:String(Se),pending:je.pending.join(`,`)||`-`,rules:[...Ce].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:ae.length>0?`Y`:`N`,clickError:T.kind===`none`?`-`:T.kind,pipeEvent:ce?.hold??`-`,upd:String(E.length),ask:String(D.length),warn:Le,diag:String(fe.length),warnRecord:Oe?`new`:`kept`,viewer:Ae===null?`-`:`${Ae.index}/${fe.length}p${Ae.page+1}`}),{drawn:{body:je,viewerOpen:Ae!==null,diagnostics:fe,geometry:ke},evaluated:xe,cellBreaks:Se,answersClick:Rs(T),pipeShown:le,delivered:Ee,lanes:w}}function SQ(e,t,n){let{laneSetups:r,tmuxStatusLines:i}=e;r.noted(CQ(t),n),i.observe(t.hookData.session_id,t.hints.tmux,n.tmuxStatus)}function CQ(e){return{sessionId:e.hookData.session_id,hints:e.hints,origin:e.requested,transcript:e.hookData.transcript_path,answered:_F(e.hookData)}}function wQ(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);a.clicked(t,s===null?null:CQ(s),n,r),s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus)}async function TQ(e,t,n,r,i){try{var a=no();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(vQ(e,t,n,i));SQ(e,t,kZ(l.view.source.effective(),rc(t.hints.tmux)));let u=oQ(e.recorder,l.view,n),d=o.monotonic(),f=r-d;HZ(i,{deadline:`${t.deadline.kind}:${Math.round(f)}ms`});let p=await Jj(e=>Promise.all([u.landed,l.view.registry.inFlight(e)]),f,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${E(e)}`),o.after),m=o.monotonic();HZ(i,{waited:`${Math.round(m-d)}ms`,ended:p,refreshed:nZ(u.refreshed)});let{drawn:h,answersClick:g,pipeShown:_,delivered:v,lanes:y}=sQ(e.recorder,l.view,u.arrival,()=>xQ(e,l,hb)),b=t.sessionId,x=BZ(y,s.following(b)),S=vF(t.hints.client??null)===`statusline`,C=fQ[t.encoding](S?EQ(e.links.to,b,h,x):h.body);return HZ(i,{handoff:(S?x:[]).join(`,`)||`-`,drew:`${A(o,m)}ms`}),{resp:C,motion:h.body.motion,answersClick:g,pipeShown:_,delivered:v}}catch(e){a.e=e}finally{a.d()}}function EQ(e,t,n,r){let[i,...a]=r;return i===void 0||n.viewerOpen?n.body:$P(n.body,WU(VZ(e,t,[i,...a]),n.diagnostics,e,t,n.geometry))}const DQ=/^─{20,}/,OQ=/^❯(\s|$)/,kQ=/›\s*stashed$/;function AQ(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>DQ.test(e)?[t]:[]).at(-2);return n===void 0||!OQ.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function jQ(e){if(e.inMode)return{kind:`in-mode`};let t=AQ(e);return t===null?{kind:`no-prompt`}:kQ.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function MQ(e){return/^❯\s*\S/u.test(AQ(e)?.prompt??``)}const NQ=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function PQ(e){return e.screen.some(e=>NQ.test(e))}const FQ={"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 IQ(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 LQ(e,t,n){let r=jQ(await e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:FQ[r.kind]};let i=await e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}async function RQ(e,t,n,r,i){let a=await Ms(e,t,n,r,i);if(a.kind===`failed`)throw Error(a.reason);return a}async function zQ(e,t){let n=await RQ(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(`
208
- `);return{inMode:r!==`0`,screen:i}}function BQ(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 VQ(e,t,n){let r=await RQ(e,t,`claude-input.type`,BQ(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 HQ(e){return{read:t=>zQ(e,t),type:(t,n)=>VQ(e,t,n)}}const UQ={kind:`ok`,said:``},WQ=e=>({kind:`failed`,said:e}),GQ={launch:({what:e})=>`launch:${e}`,"type-slash":({line:e})=>`type-slash:${e}`,"apply-update":()=>`apply-update`};function KQ(e){let t=GQ[e.kind];return t(e)}const qQ=`render-origin`,JQ=`client-hints`;var Z=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}},YQ=class extends Error{constructor(e){super(`the daemon closed: ${e} refused`),this.name=`DaemonClosing`}},XQ=class extends Error{constructor(e){super(`the client left: ${e} not run`),this.name=`ClickAbandoned`}};function ZQ(e){try{return e()}catch(e){throw e instanceof URIError?new Z(`malformed wire encoding: ${e.message}`):e}}function QQ(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?Pv:Fv;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const $Q=Object.entries(ix),e$=new Set(ox.map(e=>e.sessionKey)),t$=()=>!1;function n$(e,t){return MZ(e,e=>e$.has(e)?t(e):null,t$)}const r$=[`preset`,`theme`];function i$(e,t,n){let r=new Set(r$.slice(0,n).map(e=>ix[e].sessionKey));return MZ(e,e=>r.has(e)?t(e):null,t$)}function a$(e,t){let n=Array.from({length:r$.length+1},(n,r)=>i$(e,t,r));return e=>{let t=r$.indexOf(e);return n[t===-1?r$.length:t]}}function o$(e,t,n,r){return e.flatMap(([e,i])=>{let a=QQ(t,e);return a===null||a===QQ(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function s$(e,t,n){return QQ(n$(e,t),n)}function c$(e,t){let n=n$(e,t);return o$($Q,n,a$(e,t),t=>l$(e,n.preset,t.configKey))}function l$(e,t,n){return n in(Lx(e.presets,t).globals??{})?XN(t,n):n}function u$(e,t,n){let r=Ix(t(ix.preset.sessionKey),e.globals.preset,e.presets),i=ZN(n);return{key:i?.scope===`globals`?l$(e,r,i.field):n,globals:Bx(e,r)}}function d$(e,t){let{preset:n}=n$(e,t);return m$(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:gy(a,s);return c===void 0||hy(c)===hy(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function f$(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Fx(e.presets).flatMap(n=>{let i=m$(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 py(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:gy(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const p$=new WeakMap;function m$(e,t){let n=p$.get(e)??new Map;p$.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...Yv(Rx(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=dy(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 h$(e,t){let n=n$(e,t);return{from:n.preset,globals:Lx(e.presets,n.preset).globals??{},picks:o$($Q.filter(([e])=>e!==`preset`),n,a$(e,t),e=>e.configKey),placements:d$(e,t)}}function g$(e,t){return MZ({...e,globals:{palette:t},presets:{}},()=>null,t$)}function _$(e,t){let n=n$(e,t),r=QQ(n,`theme`);if(r===null)return{kind:`rule`};let i=g$(e,r),a=Bx(e,n.preset),o=Object.fromEntries(Zb.map(e=>[e,QQ(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:Zb.some(e=>o[e]!==QQ(i,e))}}function v$(e){return{sessionKeys:ox.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...ON(e)?FX.map(t=>XN(t,e)):[],...YN(e)?iv().map(t=>JN(t,e)):[]]}}function y$(e){return new Set(ox.map(e=>e.configKey).filter(t=>v$(t).fileKeys.some(t=>S$(e,x$(t)))))}function b$(e,t,n){let r=c$(e,n),i=new Set(r.map(e=>e.configKey)),a=dx(e=>i.has(ix[e].configKey)||t.has(ix[e].configKey)),o=_$(e,n);return{unsaved:r.length+d$(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function x$(e){let t=ZN(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return QN(t)}function S$(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&S$(e[n],r)}function C$(e,t,n){let r=fx.get(n);if(r!==void 0)return s$(e,t,r);for(let[,t]of sy(e))if(t.key===n)return t.default??null;return null}function w$(e,t){let n=HN(e).get(t);return n===void 0?null:String(n)}const T$={inside:()=>[],defaultOf:()=>Wi,menus:[]},E$=e=>`${e.key}\0${e.member}`;function D$(e){let t=new Map,n=n=>{let r=`${n.name}\0${Gv(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:rY(a,Gv(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(E$(e))??new Map;n.set(E$(t),t),o.set(E$(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(E$(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 Fx(e.presets))d(Rx(e,t).node,[]);for(let t of Object.values(e.actions)){let e=ia(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(E$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(E$(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(E$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const O$=new WeakMap;function k$(e){let t=O$.get(e);if(t!==void 0)return t;let n=D$(e);return O$.set(e,n),n}function A$(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 j$(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 M$(e,t,n){let r=(r,i,a)=>{let o=A$(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 N$=new Set([`1`,`true`]),P$=new Set([`0`,`false`,``]);function F$(e,t){let n=o1(e),r=n.scope===`segment-palette`?`string`:tx(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(N$.has(t))return`true`;if(P$.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function I$(e){try{return m.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function L$(e,t,n){try{if(t===null){m.rmSync(Qn(e),{force:!0});return}Zn(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function R$(e){return/^\s*$/.test(e)?null:ga(e)}function z$(e,t){return e!==null&&va(e,t)!==void 0}function B$(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(B$),...i}}return e}function V$(e){if(!Cx(e))return B$(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,B$(t)])),...n}}const H$=MX,U$=H$.segments,W$=H$.presets,G$=H$.root;function K$(e,t,n,r){if(!z$(e,t)&&n===void 0)throw new Z(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function q$(e,t){let n=QN(t);return t.scope===`segment-palette`&&K$(e,[`segments`,t.segment],U$[t.segment],n.join(`.`)),n}function J$(e){return ga(Ta(e))}function Y$(){return Object.entries(G$.rows).map(([e,t])=>{let n=B$(t);return{path:[`root`],fragment:J$({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function X$(e,t){let n=e===null?void 0:va(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function Z$(e,t){if(t===void 0)return null;let n=V$(t);return{path:e,fragment:J$(n),unit:{path:e,value:n}}}function Q$(e,t){let n=[`presets`,t],r=[...n,`root`],i=W$[t];K$(e,n,i,r.join(`.`));let a=X$(e,r)??Z$(r,i?.root);return a!==null&&ree(a.fragment)?a:null}function $$(e,t){let n=Ua(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 e1(e,t){return[...Y$(),X$(e,[`root`]),Q$(e,t)].filter(e=>e!==null).reduce($$,new Map)}function t1(e,t,n){for(let{node:r,...i}of e1(e,t).values())if(Ga(r,n))return i;throw new Z(`${n1(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 n1(e,t){return Q$(e,t)?.path??[`root`]}function r1(e,t){return t.scope===`preset-root`?n1(e,t.preset):QN(t)}function i1(e,{unit:t}){return t===null?e:Ra(e,t.path,Ta(t.value),Ca)}function a1(e){let t=ZN(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function o1(e){let t=a1(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function s1(e,t,n,r,i){let a=_1(t,r),o,s=()=>(o??={chain:Ane(t,n)}).chain;v1(t,s,a),i(t,s,a),L$(t.path,r,e.logger),e.record(t.path,n,r)}function c1(e,t,n){let r=d1(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 l1=()=>{};function u1(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 d1(e,t,n){if(t===null)return[];let r=new Set(h1(m1(t),m1(n)));return h1(p1(e,t),p1(e,n)).filter(e=>!r.has(e))}function Ane(e,t){try{return f1(e,t)}catch(e){if(e instanceof xy)return null;throw e}}function f1(e,t){return cX(e.locs,t===null?e.above:[mU(e.path),...e.above],PX,{warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:m.readFileSync(n,`utf8`))}function p1(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function m1(e){return e.layers.at(-1)?.config??e.base}function h1(e,t,n=``){return!g1(e)||!g1(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>h1(e[r],t[r],n===``?r:`${n}.${r}`))}function g1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _1(e,t){try{return f1(e,t)}catch(e){throw e instanceof xy?new Z(`refused: the config file would not load after this click — ${e.message}`):e}}function v1(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 xy(e,[t]).message).join(`
209
- `)}`)}function y1(e,t){let n=o1(t),r=R$(I$(e)??``),i=r===null?void 0:va(r,QN(n));return i!==void 0&&`value`in i?i.value:void 0}function b1(e,t,n){x1(e,t,n,[])}function x1(e,t,n,r){let i=I$(t.path),a=n.reduce((e,[t,n])=>Ra(e,q$(R$(e),o1(t)),F$(t,n),Ca),i??``);s1(e,t,i,u1(t,()=>S1(a,t.path,r,e=>e)),c1)}function S1(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=t1(R$(s),n,i),l=Ya(i1(s,c),c.path,i,a,Ta(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 C1(e,t,n){let r=R$(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of e1(r,t)){if(!Ga(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?ba(e,c):Ta(s.value);if(a!==`#`)return Ra(e,[...i,`rows`,a],l,Ca);if(Q$(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 Ra(e,i,l,Ca)}return e}function w1(e,t){return Ba(e,t,t[0]===`presets`&&t.length>2&&!IX(t[1])?2:0)}function T1(e,t,n){let r=n.map(a1),i=I$(t.path);if(i===null)return;let a=r.reduce((e,t)=>w1(e,r1(R$(e),t)),i);a!==i&&s1(e,t,i,a,l1)}function E1(e){let t=e===null?void 0:va(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function D1(e,t){let n=new Set([...FX,...E1(e),...t.above.flatMap(e=>Object.keys(la.default.parse(m.readFileSync(e.path,`utf8`)).presets??{}))].map(UM));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(UM(e)))}function O1(e,t,n,r,i,a){let o=I$(t.path),s=R$(o??``),c=D1(s,t),l=[`presets`,c],u=u1(t,()=>Q$(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?ba(o??``,u.fragment):Ta(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Ta(r)]]],f=i.map(([e,t])=>{let n=XN(c,e);return[q$(s,o1(n)),F$(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Ra(e,t,n,Ca),Ra(o??``,l,`{}`,Ca));return s1(e,t,o,u1(t,()=>S1(p,t.path,a.map(e=>({...e,preset:c})),C1)),c1),c}function k1(e,t,n,r){let i=I$(t.path);s1(e,t,i,Ra(i??``,[`themeDefaults`,n],Ta(r),Ca),c1)}function A1(e,t,n){if(IX(n))throw new Z(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=I$(t.path),a=R$(i??``);if(i===null||a===null||va(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=va(a,[`globals`,`preset`]);s1(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>w1(e,t),i),l1)}function j1(e,t,n,r){let i=a1(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=I$(t.path),o=r.op===`remove`?r.target:r.anchor,s=u1(t,()=>t1(R$(a??``),i.preset,o)),c=i1(a??``,s),{after:l,placed:u}=M1(c,s.path,r,()=>{let e=_1(t,c).config;return Fx(e.presets).map(t=>Rx(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 s1(e,t,a,l,c1),u}function M1(e,t,n,r){switch(n.op){case`remove`:return{after:qa(e,t,n.target),placed:null};case`insert`:{let i=hz(n.segment,n.anchor,r());return{after:Ja(e,t,i,n.anchor,n.relation),placed:i}}}}function N1(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 P1={load:()=>({}),save:()=>{},flush:()=>{}};var F1=class{sessions;storage;head=0;atom=(0,Y.createAtom)(`SessionState`);constructor(e=P1,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=P1}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function I1(e){let t=new Map;return{dir:e.dir,onDisk:n=>{let r=t.get(n);if(r!==void 0)return r;let i=e.onDisk(n);return t.set(n,i),i}}}function L1(e,t){return V1(e.dir,t)??R1(e,t)}function R1(e,t){let n=e.onDisk(e.dir);for(let r of z1(t)){let i=B1(n,e.onDisk(r));if(i!==null)return s.join(i,s.relative(r,t))}return null}function z1(e){let t=s.dirname(e);return t===e?[]:[t,...z1(t)]}function B1(e,t){let n=s.relative(e,t);return n===`..`||n.startsWith(`..${s.sep}`)||s.isAbsolute(n)?null:n}function V1(e,t){let n=B1(e,t);return n===``?null:n}function H1(e,t){let n=L1(e,t);return n===null?{kind:`world`,path:t}:{kind:`home`,path:n}}var U1=class extends Error{};function W1(e,t){if(typeof t==`string`){if(!s.isAbsolute(t))throw new U1(`an older build's stored path ${JSON.stringify(t)} is not absolute`);return G1(e,t)}if(typeof t!=`object`||!t)throw new U1(`stored path is not an object: ${JSON.stringify(t)}`);let{kind:n,path:r}=t;if(typeof r!=`string`)throw new U1(`stored path has no path: ${JSON.stringify(t)}`);if(n===`home`){let t=s.join(e.dir,r);if(s.isAbsolute(r)||V1(e.dir,t)!==r)throw new U1(`stored home path ${JSON.stringify(r)} is not a plain path inside the home's root ${e.dir}`);return t}if(n===`world`){if(!s.isAbsolute(r))throw new U1(`stored world path ${JSON.stringify(r)} is not absolute`);if(V1(e.dir,r)!==null)throw new U1(`stored world path ${r} lies under the home's root ${e.dir}; a home's file is stored relative to it`);return G1(e,r)}throw new U1(`stored path has no kind of home or world: ${JSON.stringify(t)}`)}function G1(e,t){let n=L1(e,t);return n===null?t:s.join(e.dir,n)}const K1={load:()=>({}),save:()=>{}},q1=new Set(ox.map(e=>e.sessionKey)),J1=e=>q1.has(e)||e.startsWith(uP),Y1=8*1024*1024,X1={past:[],future:[]},Z1=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var Q1=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=K1){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)??X1;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??X1}begin(){let e=new Map,t=!1,n=(n,r)=>{t=!0;let i=e.get(n)??new Map,a=i.get(Z1(r));i.set(Z1(r),a===void 0?r:{...r,before:a.before}),e.set(n,i)},r=new Map;return{sessionState:N1(this.sessionState,()=>!0,(e,i,a,o)=>{if(t=!0,!(!J1(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:o0(i,r),o=n.get(e),s=o===void 0?a:u0(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`,c0(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(Z1)),a=n.net.filter(e=>!i.has(Z1(e))),o=t0(d0(l0(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(p0).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=t0(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...r0(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(Z1)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:d0(n,t),future:d0(i,t),...a!==void 0&&{savepoint:{at:d0([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(Z1(e))),below:d0(a.below,t)}}}),new Z(`${r}: ${o.map(p0).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):I$(t.file)}write(e,t,n){t.kind===`file`?L$(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||$1(n)>Y1;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,e0(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${Y1} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function $1(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 e0({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...r0(n,1,[])}:{past:e,future:t.slice(1),...r0(n,0,[])}}function t0(e){return e.slice(-50)}const n0=e=>e===fP.member;function r0(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:i0(e.net,n),below:e.below}}}function i0(e,t){let n=new Map(e.map(e=>[Z1(e),e]));for(let e of t){let t=n.get(Z1(e));n.set(Z1(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const a0=e=>e.map(e=>({...e,before:e.after,after:e.before}));function o0(e,t){let n=[...e.past,t],r=t0(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...r0(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...s0(e.future,a),...i.below]},n.length-r.length,t)}}function s0(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function c0(e,t){return{past:e.past.slice(0,-1),future:t0([...e.future,t]),...r0(e.savepoint,0,a0(t))}}function l0(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...s0(r,t.at-i.length),...t.below]}function u0(e,t){if(n0(t.after)&&!n0(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!n0(t.after)&&n0(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function d0(e,t){return e.map(e=>e.filter(e=>!t.has(Z1(e)))).filter(e=>e.length>0)}function f0(e){return e.map(p0).join(`, `)}function p0(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function m0(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`&&`file`in t)&&n(t.before)&&n(t.after)}function h0(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(m0))}function g0(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(m0)&&h0(t.below)}function _0(e){if(typeof e!=`object`||!e)return!1;let t=e;return h0(t.past)&&h0(t.future)&&(t.savepoint===void 0||g0(t.savepoint))}function v0(e,t){let n=e=>e.kind===`file`||J1(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 y0(e,t){let n=(e,n)=>e.map(e=>e.kind===`file`?{...e,file:t(e.file,n)}:e),r=(e,t)=>e.map((e,r)=>n(e,`${t} step ${r+1}`)),{past:i,future:a,savepoint:o}=e;return{past:r(i,`undo`),future:r(a,`redo`),...o!==void 0&&{savepoint:{at:o.at,net:n(o.net,`edit mode's change`),below:r(o.below,`edit mode's redo`)}}}}function b0(e,t,n){return{load:()=>{let r;try{r=m.readFileSync(e,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&n(`warn`,`settings-history read failed (${t}); starting empty`),{}}let i;try{i=JSON.parse(r)}catch{i=null}if(typeof i!=`object`||!i||Array.isArray(i)||!Object.values(i).every(_0))return n(`warn`,`settings-history load: unexpected shape, starting empty`),{};let a=I1(t),o;try{o=Object.entries(i).map(([e,t])=>[e,y0(t,(t,n)=>{try{return W1(a,t)}catch(t){throw t instanceof U1?new U1(`session ${e}'s ${n}: ${t.message}`):t}})])}catch(e){if(!(e instanceof U1))throw e;return n(`warn`,`settings-history load: ${e.message}; starting empty`),{}}let s=new Set,c=Object.fromEntries(o.map(([e,t])=>[e,v0(t,s)]));return s.size>0&&n(`warn`,`settings-history load: dropped the changes to ${[...s].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),c},save:r=>{let i=I1(t),a=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,y0(t,e=>H1(i,e))]));try{m.mkdirSync(s.dirname(e),{recursive:!0}),Zn(e,JSON.stringify(a),384)}catch(e){let t=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw n(`error`,t),Error(t)}}}}const x0=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function S0(e){return{...Object.fromEntries(x0.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 C0=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function w0(e){let t=e=>({kind:`failed`,reason:e});if(!C0(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!C0(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!jF.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${jF.join(` or `)}`)}return{kind:`ok`,value:e}}function T0(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const E0=e=>CU(e,`doctor-marks.json`,{},w0),D0=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},O0=(e,t)=>e.includes(t)?e:[...e,t],k0=e=>CU(e,`doctor-clicked-terminals.json`,[],D0);var A0=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const j0=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},M0=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),N0=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=M0(e,t);return r===void 0?n:r.projectDir},P0=(e,t)=>M0(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function F0(e){let t=new Map;for(let n of e.split(`
207
+ Single-row example: root: { h: ["seg1", "seg2"] }`,line:J(e.source,[`layout`])}),t.root!==void 0&&(a.root=zJ(e,`root`,t.root)),t.insert!==void 0&&(a.insert=VJ(e,t.insert,i)),t.actions!==void 0&&(a.actions=yV(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:J(e.source,[`looks`])}),t.styles!==void 0&&(a.styles=dY(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=MN(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=pY(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=IN(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=vV(e,t.helpers)),t.plugins!==void 0&&(a.plugins=CX(e,t.plugins)),YJ(e,a),oY(e,a),gP(e,a),iP(e,a,tS,`the global settings menu`),aP(e,a,n),a}const SX=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function CX(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 ${Ly(t)}`,line:J(e.source,[`plugins`])})}const wX={},TX=BI(`commands.`),EX=KI(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),DX=PI(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),OX=`{{ ${jP} }}`,kX={min:0,max:100,step:5},AX={warnAt:{label:`warning at %`,domain:kX,default:50},errorAt:{label:`error at %`,domain:{...kX,atLeast:`warnAt`},default:80}};function jX(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:kX,default:80}}}const MX={globals:{palette:`tokyo-night`},variables:{...TX.variables,...IM,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:`⊫`},...DX.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:OX},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 ${DX.armed} }}{{ if ne .git.branch "" }} {{ end }}${DX.template}{{ end }}`,fg:OX,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:OI(``).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:TX.template,when:TX.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:jX(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:jX(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:AX,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:AX,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) ${A_} }}`,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:EX.template,bg:EX.bg,when:EX.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:{...OI(``).actions,...TX.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...DX.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...EX.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:wX,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 ${A_} }}{{ \$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 (${jP}) 2 (readableOn (color "accent") (bgOf) ${A_})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${A_}) .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:qI(`.`),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 .)) }}`}},NX=new Set([MX.globals.palette,...Object.keys(MX.themeDefaults),...Object.values(MX.segments).map(e=>e.palette)].filter(e=>e!==void 0)),PX=Xz(_X(`<default>`,JSON.stringify(MX),NX),MX),FX=Fx(PX.presets);function IX(e){return FX.includes(e)}const LX={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0};function RX(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function zX(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function BX(e,t,n){return{[zX(ot(e))]:{...LX,cost:t,input:n}}}function VX(e,t){let n=zX(ot(t)),r=e.sums[n],i=e.own[n];if(r===void 0&&i===void 0)return L;let a={...LX};return r!==void 0&&RX(a,r),i!==void 0&&RX(a,i),I({cost:a.cost,tokens:a.input+a.output+a.cacheCreation+a.cacheRead,tokenBreakdown:{input:a.input,output:a.output,cacheCreation:a.cacheCreation,cacheRead:a.cacheRead},date:n})}function HX(e,t,n){return an({dir:e.project_dir,env:n===void 0?[]:[[bo,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}const UX=[`session`,`today`,`context`,`metrics`,`activity`,`cache`,`speed`,`autocompact`];var WX=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:R(n,`read`)}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)})}};function GX(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function KX(e){return{...Object.fromEntries(Yb.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:IX(e.preset)}}}const qX={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function JX(e){if(eo(e))return`pending`;let{prState:t,prError:n,prEarlier:r}=e??{};return eo(t)?`pending`:t===void 0?n===void 0?r===void 0?`-`:`earlier-${String(r)}`:`failed`:t}const YX=10*1e3;function XX(e,t){if(!(t<60))return e*3600/t}function ZX(e,t,n,r){let i=r-t;if(i<50||i>YX)return;let a=n-e;if(!(a<=0))return a*1e3/i}function QX(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=ZX(t.input,t.atMs,n.input,n.atMs),i=ZX(t.output,t.atMs,n.output,n.atMs),a=ZX(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 $X(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>YX)continue;let o=ZX(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function eZ(e){return Vq(e.termCols??120)}function tZ(e,t){return Co(So(e.claudeConfigDir,t))}function nZ(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function rZ(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=r.session_id,s=i.usageStore.request(o,r.transcript_path),c=async(e,t)=>{let r=i.clock.monotonic();n.set(e,null);let a=null;try{await t()}catch(t){i.log(`error`,`${e} lane threw: ${E(t)}`),a=`${e}: ${String(t)}`}n.set(e,A(i.clock,r)),i.faults.refreshed(o,e,a)};await Promise.all([c(`session`,()=>s.usage(r)),c(`today`,()=>s.today()),c(`context`,()=>i.contextProvider.getContextInfo(r)),c(`metrics`,()=>i.metricsProvider.getMetricsInfo(o,r)),c(`activity`,()=>i.activityProvider.getActivityInfo(o,r)),c(`cache`,()=>i.cacheExpiry.refresh(o,r.transcript_path)),c(`speed`,()=>s.speed(ot(t).getTime())),c(`autocompact`,async()=>i.autoCompact.window(tZ(a,i.home)))])}function iZ(e,t){let n=Xj(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}const aZ={showSha:!0,showWorkingTree:!0,showStashCount:!0,showUpstream:!0,showRepoName:!0,showRepoUrl:!0,showOperation:!0,showCommittedAt:!0,showPullRequest:!0};function oZ({cwd:e,hookData:t}){return[e??t.workspace?.current_dir,aZ,t.workspace?.project_dir]}function sZ(e,t,n,r){let i=n.hints.tmux??null,a=[],o=(e,t)=>{try{return t()}catch(t){return a.push(`${e}: ${E(t)}`),Xj(R(`${e}: ${String(t)}`,`read`))}};return{lanes:{git:o(`git`,()=>e.gitProvider.declare(t,...oZ(n))),tmux:i===null?Xj(L):o(`tmux`,()=>e.tmuxService.declare(t,i)),hostName:o(`host.name`,()=>e.hostService.declareName(t)),hostUser:o(`host.user`,()=>e.hostService.declareUser(t)),today:o(`today`,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map([...r].map(([r,i])=>[r,o(r,()=>e.managedStorage.declare(t,i,n.sessionId))]))},faults:a}}function cZ(e){let{hookData:t,deps:n}=e,r=t.session_id,i=n.lanes(),a=(e,t)=>{let i=n.faults.of(r,e);if(i!==void 0)return i;try{return t()}catch(t){return n.log(`error`,`${e} read threw: ${E(t)}`),R(`${e}: ${String(t)}`,`read`)}};return{lanes:{git:i.git.current(),usage:a(`session`,()=>n.usageStore.usageOf(r,t)),context:a(`context`,()=>n.contextProvider.contextOf(t)),metrics:a(`metrics`,()=>n.metricsProvider.metricsOf(r,t)),activity:a(`activity`,()=>n.activityProvider.activityOf(r)),tmuxSession:i.tmux.current(),hostName:i.hostName.current(),hostUser:i.hostUser.current(),cache:a(`cache`,()=>n.cacheExpiry.expiryOf(r)),speed:a(`speed`,()=>n.usageStore.speedOf(r)),autoCompact:a(`autocompact`,()=>n.autoCompact.stored(tZ(e.hints,n.home))),sources:new Map([...i.sources].map(([e,t])=>[e,t.current()]))},today:a(`today`,()=>lZ(i.today,n.usageStore,r)),faults:UX.flatMap(e=>{let t=n.faults.of(r,e);return t===void 0?[]:[{lane:e,reason:t.reason}]})}}function lZ(e,t,n){let r=e.current();if(r.kind!==`ok`)return r;let i=t.daysOutside(n,r.value.roots);return i.kind===`failed`?i:I({sums:r.value.sums,own:i.kind===`ok`?i.value:{}})}function uZ(e){return[e.git.current(),e.tmux.current(),e.hostName.current(),e.hostUser.current(),...[...e.sources.values()].map(e=>e.current())].flatMap(e=>e.kind===`pending`&&e.why===`unread`?[e.landed]:[])}function dZ(...e){let t=e.find(e=>e?.kind===`pending`);return t?.kind===`pending`?$a(t.why):void 0}const fZ=e=>{switch(e.kind){case`pending`:return e;case`absent`:return L;case`ok`:return I(e.value);case`failed`:return R(e.reason,e.failedAt)}};function pZ(e,t,n){let{hookData:r,hints:i}=t,{effective:a,configFacts:o}=n,{configPath:s,...c}=o,l=e.builtins,u={usage:fZ(l.session),context:fZ(l.context),metrics:fZ(l.metrics),activity:fZ(l.activity),cache:fZ(l.cache),speed:fZ(l.speed),autoCompact:fZ(l.autocompact),git:fZ(l.git),pr:fZ(l.pr),tmux:fZ(l.tmux),hostName:fZ(l.hostName),hostUser:fZ(l.hostUser)},d=(e,t)=>{switch(e.kind){case`pending`:return $a(e.why);case`failed`:case`absent`:return;case`ok`:return t(e.value)}},f=e=>e.kind===`ok`?e.value:void 0,p=i.tmux??null,m=u.git.kind===`pending`?$a(u.git.why):u.git.kind===`ok`?TZ(u.git.value,u.pr,$a):void 0,h=u.tmux.kind===`pending`?$a(u.tmux.why):f(u.tmux)?.session,g=u.hostName.kind===`pending`?$a(u.hostName.why):f(u.hostName),_=u.hostUser.kind===`pending`?$a(u.hostUser.why):f(u.hostUser),v=dZ(u.context)??bZ(u.autoCompact,f(u.context)?.maxTokens),y=r.rate_limits?.five_hour,b=r.rate_limits?.seven_day,x=dZ(u.usage,u.metrics)??gZ(f(u.usage)?.session.cost,f(u.metrics)?.sessionDuration),S=d(u.speed,_Z),C=d(u.usage,e=>CZ({cost:e.session.cost,tokens:e.session.tokens})),ee=d(u.metrics,e=>CZ({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),w=d(u.activity,xZ),te=d(u.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),ne=d(u.cache,e=>({expiresAt:e})),T=wZ(t.home),re=r.workspace?{...r.workspace,current_dir:wZ(r.workspace.current_dir)??``,project_dir:wZ(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>wZ(e)??e)}:r.workspace,E=r.session_id;return{...r,...re!==void 0&&{workspace:re},...T!==void 0&&{home:T},...m!==void 0&&{git:m},...r.location!==void 0&&{location:{...r.location,main:wZ(r.location.main)??``}},...p!==null&&{tmux:{pane:p.pane,...h!==void 0&&{session:h}}},host:{...g!==void 0&&{name:g},..._!==void 0&&{user:_},...i.ssh!==void 0&&{ssh:i.ssh}},...KX(a),history:n.history,navigation:{back:n.back},term:{cols:eZ(i)},...c,...s!==null&&{configPath:s},resumeCommand:HX(re,E,i.claudeConfigDir),...C!==void 0&&{session:C},...x!==void 0&&{burn:x},...S!==void 0&&{speed:S},...y!==void 0&&{block:{nativeUtilization:y.used_percentage,resetsAt:y.resets_at}},...b!==void 0&&{weekly:{percentage:b.used_percentage,resetsAt:b.resets_at}},...ne!==void 0&&{cache:ne},...te!==void 0&&{context:te},...ee!==void 0&&{metrics:ee},...w!==void 0&&{activity:w},...v!==void 0&&{autocompact:v},...hZ(Object.keys(e.sources),t=>{let n=fZ(e.sources[t]);return n.kind===`pending`?$a(n.why):n})}}function mZ(e){let t=Object.entries(e);return{sources:String(t.length),sourcesPending:t.flatMap(([e,t])=>t.kind===`pending`?[`${e}:${t.why}`]:[]).join(`,`)||`-`}}function hZ(e,t){let n=Object.fromEntries(tC.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 gZ(e,t){let n=e!=null&&t!=null?XX(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function _Z(e){let t=QX(e),n=$X(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function vZ(e,t){if(e.kind===`pending`)return $a(e.why);if(e.kind!==`ok`)return;let n=VX(e.value,t);return n.kind===`ok`?{cost:n.value.cost,tokens:n.value.tokens}:void 0}async function yZ(e,t,n){await rZ(e,t,n),await qj(()=>{let t=uZ(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function bZ(e,t){switch(e.kind){case`pending`:return $a(e.why);case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return GI(e.value,t)}}function xZ(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=SZ(e.running),i=SZ(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 SZ(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function CZ(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 wZ(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function TZ(e,t,n){let r=e=>e?.kind===`ok`?e.value:void 0,i=r(e.aheadBehind),a=r(e.sha),o=r(e.operation),s=r(e.committedAt),c=r(e.stashCount),l=r(e.upstream),u=e.upstream===void 0?void 0:r(Hq(e.upstream,e.aheadBehind)),d=r(e.repoName),f=r(e.repoUrl),p=t.kind===`pending`?t:Uq(t,e.head),m={};switch(p.kind){case`pending`:{let e=n(p.why);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`:break}return{branch:e.branch,status:e.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...e.workingTree!==void 0&&{staged:e.workingTree.staged,unstaged:e.workingTree.unstaged,untracked:e.workingTree.untracked,conflicts:e.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 EZ=Object.freeze({});function DZ(e,t){return e.kind===`decided`?t[e.name]??EZ:EZ}function OZ(e,t){return{...e,...Object.fromEntries(Zb.map(n=>[n,e[n]??t[n]]))}}const kZ=(e,t)=>yb(n=>{let{setting:r,on:i,inTmux:a}=fb[n].switch;return e[r]===i&&(t||!a)});function AZ(e,t,n,r){let i=$b(e);return rv(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function jZ(e,t){return Ix(t(`preset`),e.globals.preset,e.presets)}function MZ(e,t,n){let r=jZ(e,t),i=Bx(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=ute(a.palette,t(`theme`),i.palette),s=OZ(i,DZ(o,e.themeDefaults));return{...Object.fromEntries(Yb.map(e=>[e,AZ(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:hv(a.style,t(`style`),s.style,e.styles),effect:Tv(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}const NZ={moving:1e3/30,still:1e3},PZ=[`data`,`state`,`reload`,`visibility`];function FZ(e){return pb.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 IZ(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const LZ=(e,t)=>fb[t].handsOff?e.resp:e.statusline,RZ=e=>Math.round(1e3/e);var zZ=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 bb;let r=t-1,i=this.shown(n);return yb(e=>{let a=n.rates.get(e);if(a===void 0)return _b;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: ${E(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,RZ(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||LZ(a,t)!==LZ(i,t))&&IZ(r,n);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let n=LZ(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:gN(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=nM.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=${RZ(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${PZ.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 BZ(e,t){return pb.filter(n=>e[n]&&fb[n].handsOff&&t.has(n))}function VZ(e,t,n){return{severity:OU,lines:[[kU(`[⟲ claude]`,GS(e,[{verb:xS,args:[t,...n.map(e=>fb[e].switch.setting)]}]))]]}}function HZ(e,t){for(let n of Object.entries(t))e.push(n)}const UZ={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function WZ(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,E(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function GZ(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...WZ(n)];return{level:UZ[n.kind],line:KZ(e,i)}}const KZ=(e,t)=>`${e}${t.map(([e,t])=>` ${e}=${z(t)}`).join(``)}`;function qZ(e,t,n){if(t.kind===`pending`)return $a(t.why);if(e!==void 0&&e.kind!==`pending`){let{at:n,...r}=e;if((0,Y.compareStructural)(r,t))return e}return{...t,at:n}}const JZ=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`]),YZ=[[`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`]],XZ=[[`workspace.added_dirs`,`string-list`]];function ZZ(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of YZ){let i=eQ(n,e);if(i==null)t.missingRequired.push(e);else{let n=QZ(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of XZ){let i=eQ(n,e),a=i===void 0?r:$Z(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))JZ.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function QZ(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function $Z(e){return Array.isArray(e)&&e.every(e=>QZ(e)===`string`)?`string-list`:QZ(e)}function eQ(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 tQ(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}}function nQ(e){let t=tQ(e);if(!t.ok)throw Error(`session id ${t.problem}`);return t.id}new Set(UX);function rQ(e){let t=e.kind===`recording`?{kind:e.kind,v:3,session:e.session,home:e.home}:e.kind===`facts`?{kind:e.kind,at:e.at,facts:e.facts}:e.kind===`draw`?{kind:e.kind,request:e.request,state:{...e.state,idleSince:e.state.idleSince??null}}:{kind:e.kind,...e.kind===`request`&&{at:e.at},hookData:e.request.hookData,cwd:e.request.cwd,hints:e.request.hints};return`${JSON.stringify(t)}\n`}function iQ(e,t){let n=new Map,r=!1,i=(e,t,r)=>{let i=n.get(e);i===void 0||!i.delete(t)||(i.size===0&&n.delete(e),t.detach(),t.sink.end(r))},a=(e,n,r)=>{try{n.sink.write(r),r.kind===`facts`&&(n.document=r.facts),(r.kind===`request`||r.kind===`declared`)&&(n.declaration=r.request)}catch(r){t(`error`,`recording sid=${JSON.stringify(e)}: ${E(r)}`),i(e,n,{kind:`failed`,error:r})}},o=(t,n)=>{let r=e.sessionView(t);n.detach=r===null?()=>{}:(0,Y.reaction)(()=>r.followed.stamped(),(e,r,i)=>{n.detach=()=>i.dispose(),a(t,n,{kind:`facts`,...e})},{fireImmediately:!0})};return{record(t,s){if(r)throw Error(`the daemon is closing: it records nothing more`);let c=e.sessionView(t);if(c===null)throw Error(`no view of session ${JSON.stringify(t)} is open in this daemon: it has not drawn a bar here since the daemon started, or its view closed while it was idle`);let l={sink:s,detach:()=>{},document:null,declaration:null},u=n.get(t)??new Set;return n.set(t,u.add(l)),a(t,l,{kind:`recording`,session:t,home:c.source.home()}),u.has(l)&&o(t,l),()=>i(t,l,{kind:`stopped`})},moved(e){for(let t of n.get(e)??[])t.detach(),o(e,t)},arrived(e,t){let r=new Set;for(let i of n.get(e)??[])a(e,i,{kind:`request`,...t}),r.add(i);return{at:t.at,noted:r}},drew(e,{at:t,noted:r},{document:i,declaration:o,state:s}){for(let c of n.get(e)??[]){if(!r.has(c))continue;let l=[...c.document===i.facts?[]:[{kind:`facts`,...i}],...c.declaration===o?[]:[{kind:`declared`,request:o}],{kind:`draw`,request:t,state:s}];for(let t of l)n.get(e)?.has(c)&&a(e,c,t)}},close(){r=!0;for(let[e,t]of n)for(let n of t)i(e,n,{kind:`closed`})}}}function aQ(e,t){let n=null,r=iQ({sessionView:e=>{if(n===null)throw Error(`a recorder read its cache before the cache was built`);return n.sessionView(e)}},t);return n=e({onSessionViewMoved:e=>r.moved(e)}),{cache:n,recorder:r}}function oQ(e,t,n){let r=e.arrived(t.sessionId,{at:n,request:t.facts()});return{...t.settle(n),arrival:r}}function sQ(e,t,n,r){let i=r();return e.drew(t.sessionId,n,{document:t.source.stamped(),declaration:t.facts(),state:{...t.source.state(),idleSince:i.idleSince}}),i}var cQ=class extends Error{name=`RecordingFailed`};function lQ(e,t,n,r,i,a){return new Promise((o,s)=>{let c;try{c=S(r,`wx`,384)}catch(e){s(Error(e.code===`EEXIST`?`${r} already exists: a recording writes a new file`:`${r} cannot be created: ${String(e)}`));return}let l=0,u=0,d=()=>{},f=t.after(i*1e3,()=>d()),p=()=>d(),m={write:e=>{h(c,rQ(e)),l++,e.kind===`draw`&&u++},end:e=>{f(),a.removeEventListener(`abort`,p);let t=e.kind===`failed`?e.error:null;try{g(c),u===0&&ne(r)}catch(e){t??=e}t===null?o({path:r,lines:l,answers:u,daemonClosed:e.kind===`closed`}):s(new cQ(`writing ${r}: ${String(t)}`))}};a.addEventListener(`abort`,p,{once:!0});try{d=e.record(n,m)}catch(e){a.removeEventListener(`abort`,p),f(),g(c),ne(r),s(e)}})}const uQ=()=>{},dQ=e=>({ok:!1,error:e instanceof Error?e.message:E(e),code:`RENDER_FAILED`,daemonV:3}),fQ={ansi:e=>({ok:!0,output:Hte(e)}),frame:e=>({ok:!0,frame:e})};function pQ(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.monotonic(),s=[[`sid`,t]];try{try{var c=no();let i=c.u(yQ(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=xQ(e,i,{by:`feed`,fps:n}),p=fQ.ansi(o.body),m=EQ(e.links.to,t,o,BZ(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:fQ.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}=GZ(`render`,s,{kind:`threw`,error:e},A(i,o)),r=dQ(e);return{bar:Ite(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:uQ,failure:{level:t,line:`frame ${n}`}}}}function mQ(e,t,n){let{sessionState:r}=e;return MZ(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function hQ(e,t){try{var n=no();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:kZ(i.view.source.effective(),rc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function gQ(e,t,n){try{var r=no();let{renderCache:i,frameFeeds:a}=e,o=r.u(i.hold(t.projectDir,t.cwd,t.target.path)),s=a.latest(n);return kZ(mQ(e,n,o.state),s===null||rc(s.hints.tmux))}catch(e){r.e=e}finally{r.d()}}function _Q(e,t,n,r){HZ(n,{renderer:r,at:t.toFixed(3)});let i=e.hints,a=ur(e,i),o=dr(a);return HZ(n,{termCols:String(i.termCols??`?`),termRows:String(i.termRows??`?`),refused:a.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:i.client?.kind??`unreported`,rateLimits:e.rateLimits}),o}function vQ(e,t,n,r){let{renderCache:i}=e,a=t.hookData.workspace?.current_dir??t.cwd,o={...t,hookData:{...t.hookData,...a!==void 0&&s.isAbsolute(a)&&{location:tc(a)}}},c=_Q(o,n,r,e.rendererName);HZ(r,{encoding:o.encoding});let l=o.requested;return bQ(i.holdSession(l.projectDir,l.cwd,l.target.path,o),o,c,n,r)}function yQ(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=_Q(o,n,r,e.rendererName)}catch(e){throw a[Symbol.dispose](),e}return bQ(a,o,s,n,r)}function bQ(e,t,n,r,i){try{let{entry:a,state:o,view:s}=e,{sessionId:c}=t;return{req:t,at:r,facts:i,sessionId:c,entry:a,state:o,view:s,hintsError:n,[Symbol.dispose]:()=>e[Symbol.dispose]()}}catch(t){throw e[Symbol.dispose](),t}}function xQ(e,t,n){let{sessionState:r,frameFeeds:i,renderCache:a,updateWatch:o,links: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.payload(),C=b.source.effective(),ee=b.source.failure(),w=kZ(C,S.tmux!==void 0);HZ(g,{lanes:pb.filter(e=>w[e]).join(`,`)||`-`});let te=b.source.hints(),ne=S.term.cols;HZ(g,{width:String(ne)});let T=Ls(r,_,h,n.by),re=T.kind===`held`||T.kind===`owed`?T.error:null,E=o.notice({to:s.to,sessionId:_,dismissed:r.get(_,Gz),enabled:C.updateNotice}),D=nW(v.repos,_,s),ie=(e,t)=>({about:e,text:t,copy:t}),O=e=>ie(e??``,e),ae=[O(pr(m.refusedArgs)),O(x),ie(`load`,v.lastError),ie(`update-act`,o.error()),...y.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),O(re?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),oe=v.watch===null?null:Aj(`config watch`,v.watch,null),se=p.launcherWarnings(h,n.by),ce=se.find(e=>e.kind===`launch-pipes`),le=ce?.event??null,ue=[...vc(c.delivery()),...se,...oe===null?[]:[{kind:`config-watch`,message:oe}],...v.lastWarning===null?[]:[{kind:`load`,message:v.lastWarning}],...ee===null?[]:[{kind:`facts`,message:`the bar is drawn from the last facts that were read; the next could not be stamped: ${ee}`}]],de={config:y.config},fe=AU(s.to,_,n.by,ae,[...E,...D],[...ue.map(e=>({about:e.kind,message:e.message})),...l.ofSession(_,n.by,de).map(e=>({about:`${e.kind}\0${e.message}`,message:e.message}))].map(e=>({about:e.about,text:e.message,copy:e.message}))),pe=b.source.facts(),me={diagnostics:BU(fe),drawing:n,feeds:i.feedsOf(_,h),today:vZ(pe.builtins.today,h)},he=eo(S.metrics)?void 0:S.metrics;HZ(g,mZ(pe.sources)),HZ(g,{factsSeq:String(pe.seq),prompts:String(he?.messageCount??`-`),nonPrompts:String(he?.nonPrompts??`-`),pr:JX(S.git),feeds:FZ(me.feeds)});let ge=[],_e=GX(C,ne),ve=d.of(_),{frame:ye,evaluated:be,cellBreaks:xe,rules:Se,idleSince:Ce}=f.drawn(_,h,C.menuTimeout,e=>Bq(y.config,y.compiled,b.store,b.registry,me,h,_e,{perSegmentSink:b.lastRenderCellsBySegment,onRenderWarning:e=>ge.push(e)},{...C,effects:ve,idleSince:e})),we=MU(fe),Te=new Map(fe.map((e,t)=>[we[t],e.copy])),Ee=()=>a.delivered(_,n.by,Te),De=f.since(_,h);HZ(g,{menuIdle:De===void 0?`-`:`${(h-De).toFixed(1)}s/${C.menuTimeout}s`});let Oe=l.drawn(_,n.by,de,ge),ke={width:ne,rows:HU(te.termRows,n.by===`feed`?pb.flatMap(e=>{let t=fb[e].rows;return w[e]&&t!==null?[t]:[]}):[]),colorCompatibility:ye.depth},Ae=VU(r.get(_,sS),fe),je=Ae===null?ye:$P(ye,UU(fe,Ae,s.to,_,n.by,ke)),Me=u.gitProvider.getStats(),Ne=u.usageStore.getStats(),Pe=ve.lastFrame(),Fe=Pe.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,k=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,Ie=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`facts`:case`config-watch`:case`lifeline`:case`launch-pipes`:case`when`:return e.kind}},Le=[...ue,...ge].map(Ie).join(`,`)||`-`;return HZ(g,{git:`${Me.size}/${Me.hits}h/${Me.misses}m`,usage:`${Ne.size}/${Ne.hits}h/${Ne.misses}m`,effect:Pe.effect,effectT:Pe.t.toFixed(3),speed:`${Pe.speed}x`,effectRows:`${Pe.made}made/${Pe.reused}reused`,effectOwn:Fe,fadeBasis:Pe.basis,stateRev:String(Pe.revision),fades:k(Pe.fades),leaves:k(Pe.leaves),motion:je.motion,evaluated:String(be),cellBreaks:String(xe),pending:je.pending.join(`,`)||`-`,rules:[...Se].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:ae.length>0?`Y`:`N`,clickError:T.kind===`none`?`-`:T.kind,pipeEvent:ce?.hold??`-`,upd:String(E.length),ask:String(D.length),warn:Le,diag:String(fe.length),warnRecord:Oe?`new`:`kept`,viewer:Ae===null?`-`:`${Ae.index}/${fe.length}p${Ae.page+1}`}),{drawn:{body:je,viewerOpen:Ae!==null,diagnostics:fe,geometry:ke},evaluated:be,cellBreaks:xe,answersClick:Rs(T),pipeShown:le,delivered:Ee,lanes:w,idleSince:Ce}}function SQ(e,t,n){let{laneSetups:r,tmuxStatusLines:i}=e;r.noted(CQ(t),n),i.observe(t.hookData.session_id,t.hints.tmux,n.tmuxStatus)}function CQ(e){return{sessionId:e.hookData.session_id,hints:e.hints,origin:e.requested,transcript:e.hookData.transcript_path,answered:_F(e.hookData)}}function wQ(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);a.clicked(t,s===null?null:CQ(s),n,r),s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus)}async function TQ(e,t,n,r,i){try{var a=no();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(vQ(e,t,n,i));SQ(e,t,kZ(l.view.source.effective(),rc(t.hints.tmux)));let u=oQ(e.recorder,l.view,n),d=o.monotonic(),f=r-d;HZ(i,{deadline:`${t.deadline.kind}:${Math.round(f)}ms`});let p=await Jj(e=>Promise.all([u.landed,l.view.registry.inFlight(e)]),f,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${E(e)}`),o.after),m=o.monotonic();HZ(i,{waited:`${Math.round(m-d)}ms`,ended:p,refreshed:nZ(u.refreshed)});let{drawn:h,answersClick:g,pipeShown:_,delivered:v,lanes:y}=sQ(e.recorder,l.view,u.arrival,()=>xQ(e,l,hb)),b=t.sessionId,x=BZ(y,s.following(b)),S=vF(t.hints.client??null)===`statusline`,C=fQ[t.encoding](S?EQ(e.links.to,b,h,x):h.body);return HZ(i,{handoff:(S?x:[]).join(`,`)||`-`,drew:`${A(o,m)}ms`}),{resp:C,motion:h.body.motion,answersClick:g,pipeShown:_,delivered:v}}catch(e){a.e=e}finally{a.d()}}function EQ(e,t,n,r){let[i,...a]=r;return i===void 0||n.viewerOpen?n.body:$P(n.body,WU(VZ(e,t,[i,...a]),n.diagnostics,e,t,n.geometry))}const DQ=/^─{20,}/,OQ=/^❯(\s|$)/,kQ=/›\s*stashed$/;function AQ(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>DQ.test(e)?[t]:[]).at(-2);return n===void 0||!OQ.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function jQ(e){if(e.inMode)return{kind:`in-mode`};let t=AQ(e);return t===null?{kind:`no-prompt`}:kQ.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function MQ(e){return/^❯\s*\S/u.test(AQ(e)?.prompt??``)}const NQ=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function PQ(e){return e.screen.some(e=>NQ.test(e))}const FQ={"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 IQ(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 LQ(e,t,n){let r=jQ(await e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:FQ[r.kind]};let i=await e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}async function RQ(e,t,n,r,i){let a=await Ms(e,t,n,r,i);if(a.kind===`failed`)throw Error(a.reason);return a}async function zQ(e,t){let n=await RQ(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(`
208
+ `);return{inMode:r!==`0`,screen:i}}function BQ(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 VQ(e,t,n){let r=await RQ(e,t,`claude-input.type`,BQ(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 HQ(e){return{read:t=>zQ(e,t),type:(t,n)=>VQ(e,t,n)}}const UQ={kind:`ok`,said:``},WQ=e=>({kind:`failed`,said:e}),GQ={launch:({what:e})=>`launch:${e}`,"type-slash":({line:e})=>`type-slash:${e}`,"apply-update":()=>`apply-update`};function KQ(e){let t=GQ[e.kind];return t(e)}const qQ=`render-origin`,JQ=`client-hints`;var Z=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}},YQ=class extends Error{constructor(e){super(`the daemon closed: ${e} refused`),this.name=`DaemonClosing`}},XQ=class extends Error{constructor(e){super(`the client left: ${e} not run`),this.name=`ClickAbandoned`}};function ZQ(e){try{return e()}catch(e){throw e instanceof URIError?new Z(`malformed wire encoding: ${e.message}`):e}}function QQ(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?Pv:Fv;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const $Q=Object.entries(ix),e$=new Set(ox.map(e=>e.sessionKey)),t$=()=>!1;function n$(e,t){return MZ(e,e=>e$.has(e)?t(e):null,t$)}const r$=[`preset`,`theme`];function i$(e,t,n){let r=new Set(r$.slice(0,n).map(e=>ix[e].sessionKey));return MZ(e,e=>r.has(e)?t(e):null,t$)}function a$(e,t){let n=Array.from({length:r$.length+1},(n,r)=>i$(e,t,r));return e=>{let t=r$.indexOf(e);return n[t===-1?r$.length:t]}}function o$(e,t,n,r){return e.flatMap(([e,i])=>{let a=QQ(t,e);return a===null||a===QQ(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function s$(e,t,n){return QQ(n$(e,t),n)}function c$(e,t){let n=n$(e,t);return o$($Q,n,a$(e,t),t=>l$(e,n.preset,t.configKey))}function l$(e,t,n){return n in(Lx(e.presets,t).globals??{})?XN(t,n):n}function u$(e,t,n){let r=Ix(t(ix.preset.sessionKey),e.globals.preset,e.presets),i=ZN(n);return{key:i?.scope===`globals`?l$(e,r,i.field):n,globals:Bx(e,r)}}function d$(e,t){let{preset:n}=n$(e,t);return m$(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:gy(a,s);return c===void 0||hy(c)===hy(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function f$(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Fx(e.presets).flatMap(n=>{let i=m$(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 py(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:gy(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const p$=new WeakMap;function m$(e,t){let n=p$.get(e)??new Map;p$.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...Yv(Rx(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=dy(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 h$(e,t){let n=n$(e,t);return{from:n.preset,globals:Lx(e.presets,n.preset).globals??{},picks:o$($Q.filter(([e])=>e!==`preset`),n,a$(e,t),e=>e.configKey),placements:d$(e,t)}}function g$(e,t){return MZ({...e,globals:{palette:t},presets:{}},()=>null,t$)}function _$(e,t){let n=n$(e,t),r=QQ(n,`theme`);if(r===null)return{kind:`rule`};let i=g$(e,r),a=Bx(e,n.preset),o=Object.fromEntries(Zb.map(e=>[e,QQ(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:Zb.some(e=>o[e]!==QQ(i,e))}}function v$(e){return{sessionKeys:ox.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...ON(e)?FX.map(t=>XN(t,e)):[],...YN(e)?iv().map(t=>JN(t,e)):[]]}}function y$(e){return new Set(ox.map(e=>e.configKey).filter(t=>v$(t).fileKeys.some(t=>S$(e,x$(t)))))}function b$(e,t,n){let r=c$(e,n),i=new Set(r.map(e=>e.configKey)),a=dx(e=>i.has(ix[e].configKey)||t.has(ix[e].configKey)),o=_$(e,n);return{unsaved:r.length+d$(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function x$(e){let t=ZN(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return QN(t)}function S$(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&S$(e[n],r)}function C$(e,t,n){let r=fx.get(n);if(r!==void 0)return s$(e,t,r);for(let[,t]of sy(e))if(t.key===n)return t.default??null;return null}function w$(e,t){let n=HN(e).get(t);return n===void 0?null:String(n)}const T$={inside:()=>[],defaultOf:()=>Wi,menus:[]},E$=e=>`${e.key}\0${e.member}`;function D$(e){let t=new Map,n=n=>{let r=`${n.name}\0${Gv(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:rY(a,Gv(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(E$(e))??new Map;n.set(E$(t),t),o.set(E$(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(E$(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 Fx(e.presets))d(Rx(e,t).node,[]);for(let t of Object.values(e.actions)){let e=ia(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(E$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(E$(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(E$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const O$=new WeakMap;function k$(e){let t=O$.get(e);if(t!==void 0)return t;let n=D$(e);return O$.set(e,n),n}function A$(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 j$(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 M$(e,t,n){let r=(r,i,a)=>{let o=A$(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),values:t=>e.values(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 N$=new Set([`1`,`true`]),P$=new Set([`0`,`false`,``]);function F$(e,t){let n=o1(e),r=n.scope===`segment-palette`?`string`:tx(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(N$.has(t))return`true`;if(P$.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function I$(e){try{return m.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function L$(e,t,n){try{if(t===null){m.rmSync(Qn(e),{force:!0});return}Zn(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function R$(e){return/^\s*$/.test(e)?null:ga(e)}function z$(e,t){return e!==null&&va(e,t)!==void 0}function B$(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(B$),...i}}return e}function V$(e){if(!Cx(e))return B$(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,B$(t)])),...n}}const H$=MX,U$=H$.segments,W$=H$.presets,G$=H$.root;function K$(e,t,n,r){if(!z$(e,t)&&n===void 0)throw new Z(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function q$(e,t){let n=QN(t);return t.scope===`segment-palette`&&K$(e,[`segments`,t.segment],U$[t.segment],n.join(`.`)),n}function J$(e){return ga(Ta(e))}function Y$(){return Object.entries(G$.rows).map(([e,t])=>{let n=B$(t);return{path:[`root`],fragment:J$({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function X$(e,t){let n=e===null?void 0:va(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function Z$(e,t){if(t===void 0)return null;let n=V$(t);return{path:e,fragment:J$(n),unit:{path:e,value:n}}}function Q$(e,t){let n=[`presets`,t],r=[...n,`root`],i=W$[t];K$(e,n,i,r.join(`.`));let a=X$(e,r)??Z$(r,i?.root);return a!==null&&ree(a.fragment)?a:null}function $$(e,t){let n=Ua(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 e1(e,t){return[...Y$(),X$(e,[`root`]),Q$(e,t)].filter(e=>e!==null).reduce($$,new Map)}function t1(e,t,n){for(let{node:r,...i}of e1(e,t).values())if(Ga(r,n))return i;throw new Z(`${n1(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 n1(e,t){return Q$(e,t)?.path??[`root`]}function r1(e,t){return t.scope===`preset-root`?n1(e,t.preset):QN(t)}function i1(e,{unit:t}){return t===null?e:Ra(e,t.path,Ta(t.value),Ca)}function a1(e){let t=ZN(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function o1(e){let t=a1(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function s1(e,t,n,r,i){let a=_1(t,r),o,s=()=>(o??={chain:Ane(t,n)}).chain;v1(t,s,a),i(t,s,a),L$(t.path,r,e.logger),e.record(t.path,n,r)}function c1(e,t,n){let r=d1(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 l1=()=>{};function u1(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 d1(e,t,n){if(t===null)return[];let r=new Set(h1(m1(t),m1(n)));return h1(p1(e,t),p1(e,n)).filter(e=>!r.has(e))}function Ane(e,t){try{return f1(e,t)}catch(e){if(e instanceof xy)return null;throw e}}function f1(e,t){return cX(e.locs,t===null?e.above:[mU(e.path),...e.above],PX,{warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:m.readFileSync(n,`utf8`))}function p1(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function m1(e){return e.layers.at(-1)?.config??e.base}function h1(e,t,n=``){return!g1(e)||!g1(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>h1(e[r],t[r],n===``?r:`${n}.${r}`))}function g1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _1(e,t){try{return f1(e,t)}catch(e){throw e instanceof xy?new Z(`refused: the config file would not load after this click — ${e.message}`):e}}function v1(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 xy(e,[t]).message).join(`
209
+ `)}`)}function y1(e,t){let n=o1(t),r=R$(I$(e)??``),i=r===null?void 0:va(r,QN(n));return i!==void 0&&`value`in i?i.value:void 0}function b1(e,t,n){x1(e,t,n,[])}function x1(e,t,n,r){let i=I$(t.path),a=n.reduce((e,[t,n])=>Ra(e,q$(R$(e),o1(t)),F$(t,n),Ca),i??``);s1(e,t,i,u1(t,()=>S1(a,t.path,r,e=>e)),c1)}function S1(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=t1(R$(s),n,i),l=Ya(i1(s,c),c.path,i,a,Ta(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 C1(e,t,n){let r=R$(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of e1(r,t)){if(!Ga(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?ba(e,c):Ta(s.value);if(a!==`#`)return Ra(e,[...i,`rows`,a],l,Ca);if(Q$(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 Ra(e,i,l,Ca)}return e}function w1(e,t){return Ba(e,t,t[0]===`presets`&&t.length>2&&!IX(t[1])?2:0)}function T1(e,t,n){let r=n.map(a1),i=I$(t.path);if(i===null)return;let a=r.reduce((e,t)=>w1(e,r1(R$(e),t)),i);a!==i&&s1(e,t,i,a,l1)}function E1(e){let t=e===null?void 0:va(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function D1(e,t){let n=new Set([...FX,...E1(e),...t.above.flatMap(e=>Object.keys(la.default.parse(m.readFileSync(e.path,`utf8`)).presets??{}))].map(UM));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(UM(e)))}function O1(e,t,n,r,i,a){let o=I$(t.path),s=R$(o??``),c=D1(s,t),l=[`presets`,c],u=u1(t,()=>Q$(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?ba(o??``,u.fragment):Ta(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Ta(r)]]],f=i.map(([e,t])=>{let n=XN(c,e);return[q$(s,o1(n)),F$(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Ra(e,t,n,Ca),Ra(o??``,l,`{}`,Ca));return s1(e,t,o,u1(t,()=>S1(p,t.path,a.map(e=>({...e,preset:c})),C1)),c1),c}function k1(e,t,n,r){let i=I$(t.path);s1(e,t,i,Ra(i??``,[`themeDefaults`,n],Ta(r),Ca),c1)}function A1(e,t,n){if(IX(n))throw new Z(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=I$(t.path),a=R$(i??``);if(i===null||a===null||va(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=va(a,[`globals`,`preset`]);s1(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>w1(e,t),i),l1)}function j1(e,t,n,r){let i=a1(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=I$(t.path),o=r.op===`remove`?r.target:r.anchor,s=u1(t,()=>t1(R$(a??``),i.preset,o)),c=i1(a??``,s),{after:l,placed:u}=M1(c,s.path,r,()=>{let e=_1(t,c).config;return Fx(e.presets).map(t=>Rx(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 s1(e,t,a,l,c1),u}function M1(e,t,n,r){switch(n.op){case`remove`:return{after:qa(e,t,n.target),placed:null};case`insert`:{let i=hz(n.segment,n.anchor,r());return{after:Ja(e,t,i,n.anchor,n.relation),placed:i}}}}function N1(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),values:t=>e.values(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 P1={load:()=>({}),save:()=>{},flush:()=>{}};var F1=class{sessions;storage;head=0;atom=(0,Y.createAtom)(`SessionState`);constructor(e=P1,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).filter(([,e])=>Object.keys(e).length>0).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}values(e){return this.atom.reportObserved(),Object.fromEntries(this.sessions.get(e)?.values??[])}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&&this.commit(e,e=>{t.some(({key:t,value:n})=>e.values.get(t)!==n)&&(e.revision=++this.head);for(let{key:n,value:r}of t)e.values.set(n,r)})}clear(e,t){this.commit(e,e=>{e.values.delete(t)&&(e.revision=++this.head)})}restore(e,t,n){(this.sessions.get(e)?.revision??0)!==n&&this.commit(e,e=>{e.values.clear();for(let[n,r]of Object.entries(t))e.values.set(n,r);e.revision=n,this.head=Math.max(this.head,n)})}commit(e,t){(0,Y.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t(n),n.values.size===0?this.sessions.delete(e):(this.touch(e,n),this.evictOldest()),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=P1}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function I1(e){let t=new Map;return{dir:e.dir,onDisk:n=>{let r=t.get(n);if(r!==void 0)return r;let i=e.onDisk(n);return t.set(n,i),i}}}function L1(e,t){return V1(e.dir,t)??R1(e,t)}function R1(e,t){let n=e.onDisk(e.dir);for(let r of z1(t)){let i=B1(n,e.onDisk(r));if(i!==null)return s.join(i,s.relative(r,t))}return null}function z1(e){let t=s.dirname(e);return t===e?[]:[t,...z1(t)]}function B1(e,t){let n=s.relative(e,t);return n===`..`||n.startsWith(`..${s.sep}`)||s.isAbsolute(n)?null:n}function V1(e,t){let n=B1(e,t);return n===``?null:n}function H1(e,t){let n=L1(e,t);return n===null?{kind:`world`,path:t}:{kind:`home`,path:n}}var U1=class extends Error{};function W1(e,t){if(typeof t==`string`){if(!s.isAbsolute(t))throw new U1(`an older build's stored path ${JSON.stringify(t)} is not absolute`);return G1(e,t)}if(typeof t!=`object`||!t)throw new U1(`stored path is not an object: ${JSON.stringify(t)}`);let{kind:n,path:r}=t;if(typeof r!=`string`)throw new U1(`stored path has no path: ${JSON.stringify(t)}`);if(n===`home`){let t=s.join(e.dir,r);if(s.isAbsolute(r)||V1(e.dir,t)!==r)throw new U1(`stored home path ${JSON.stringify(r)} is not a plain path inside the home's root ${e.dir}`);return t}if(n===`world`){if(!s.isAbsolute(r))throw new U1(`stored world path ${JSON.stringify(r)} is not absolute`);if(V1(e.dir,r)!==null)throw new U1(`stored world path ${r} lies under the home's root ${e.dir}; a home's file is stored relative to it`);return G1(e,r)}throw new U1(`stored path has no kind of home or world: ${JSON.stringify(t)}`)}function G1(e,t){let n=L1(e,t);return n===null?t:s.join(e.dir,n)}const K1={load:()=>({}),save:()=>{}},q1=new Set(ox.map(e=>e.sessionKey)),J1=e=>q1.has(e)||e.startsWith(uP),Y1=8*1024*1024,X1={past:[],future:[]},Z1=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var Q1=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=K1){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)??X1;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??X1}begin(){let e=new Map,t=!1,n=(n,r)=>{t=!0;let i=e.get(n)??new Map,a=i.get(Z1(r));i.set(Z1(r),a===void 0?r:{...r,before:a.before}),e.set(n,i)},r=new Map;return{sessionState:N1(this.sessionState,()=>!0,(e,i,a,o)=>{if(t=!0,!(!J1(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:o0(i,r),o=n.get(e),s=o===void 0?a:u0(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`,c0(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(Z1)),a=n.net.filter(e=>!i.has(Z1(e))),o=t0(d0(l0(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(p0).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=t0(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...r0(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(Z1)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:d0(n,t),future:d0(i,t),...a!==void 0&&{savepoint:{at:d0([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(Z1(e))),below:d0(a.below,t)}}}),new Z(`${r}: ${o.map(p0).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):I$(t.file)}write(e,t,n){t.kind===`file`?L$(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||$1(n)>Y1;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,e0(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${Y1} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function $1(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 e0({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...r0(n,1,[])}:{past:e,future:t.slice(1),...r0(n,0,[])}}function t0(e){return e.slice(-50)}const n0=e=>e===fP.member;function r0(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:i0(e.net,n),below:e.below}}}function i0(e,t){let n=new Map(e.map(e=>[Z1(e),e]));for(let e of t){let t=n.get(Z1(e));n.set(Z1(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const a0=e=>e.map(e=>({...e,before:e.after,after:e.before}));function o0(e,t){let n=[...e.past,t],r=t0(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...r0(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...s0(e.future,a),...i.below]},n.length-r.length,t)}}function s0(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function c0(e,t){return{past:e.past.slice(0,-1),future:t0([...e.future,t]),...r0(e.savepoint,0,a0(t))}}function l0(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...s0(r,t.at-i.length),...t.below]}function u0(e,t){if(n0(t.after)&&!n0(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!n0(t.after)&&n0(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function d0(e,t){return e.map(e=>e.filter(e=>!t.has(Z1(e)))).filter(e=>e.length>0)}function f0(e){return e.map(p0).join(`, `)}function p0(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function m0(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`&&`file`in t)&&n(t.before)&&n(t.after)}function h0(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(m0))}function g0(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(m0)&&h0(t.below)}function _0(e){if(typeof e!=`object`||!e)return!1;let t=e;return h0(t.past)&&h0(t.future)&&(t.savepoint===void 0||g0(t.savepoint))}function v0(e,t){let n=e=>e.kind===`file`||J1(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 y0(e,t){let n=(e,n)=>e.map(e=>e.kind===`file`?{...e,file:t(e.file,n)}:e),r=(e,t)=>e.map((e,r)=>n(e,`${t} step ${r+1}`)),{past:i,future:a,savepoint:o}=e;return{past:r(i,`undo`),future:r(a,`redo`),...o!==void 0&&{savepoint:{at:o.at,net:n(o.net,`edit mode's change`),below:r(o.below,`edit mode's redo`)}}}}function b0(e,t,n){return{load:()=>{let r;try{r=m.readFileSync(e,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&n(`warn`,`settings-history read failed (${t}); starting empty`),{}}let i;try{i=JSON.parse(r)}catch{i=null}if(typeof i!=`object`||!i||Array.isArray(i)||!Object.values(i).every(_0))return n(`warn`,`settings-history load: unexpected shape, starting empty`),{};let a=I1(t),o;try{o=Object.entries(i).map(([e,t])=>[e,y0(t,(t,n)=>{try{return W1(a,t)}catch(t){throw t instanceof U1?new U1(`session ${e}'s ${n}: ${t.message}`):t}})])}catch(e){if(!(e instanceof U1))throw e;return n(`warn`,`settings-history load: ${e.message}; starting empty`),{}}let s=new Set,c=Object.fromEntries(o.map(([e,t])=>[e,v0(t,s)]));return s.size>0&&n(`warn`,`settings-history load: dropped the changes to ${[...s].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),c},save:r=>{let i=I1(t),a=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,y0(t,e=>H1(i,e))]));try{m.mkdirSync(s.dirname(e),{recursive:!0}),Zn(e,JSON.stringify(a),384)}catch(e){let t=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw n(`error`,t),Error(t)}}}}const x0=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function S0(e){return{...Object.fromEntries(x0.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 C0=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function w0(e){let t=e=>({kind:`failed`,reason:e});if(!C0(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!C0(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!jF.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${jF.join(` or `)}`)}return{kind:`ok`,value:e}}function T0(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const E0=e=>CU(e,`doctor-marks.json`,{},w0),D0=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},O0=(e,t)=>e.includes(t)?e:[...e,t],k0=e=>CU(e,`doctor-clicked-terminals.json`,[],D0);var A0=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const j0=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},M0=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),N0=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=M0(e,t);return r===void 0?n:r.projectDir},P0=(e,t)=>M0(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function F0(e){let t=new Map;for(let n of e.split(`
210
210
  `)){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*I0(e,t){let n=new Set;for(let r=e.get(t);r!==void 0&&!n.has(r.pid);)n.add(r.pid),yield r,r=e.get(r.ppid)}const L0={pullRequests:e=>Object.keys(qX).some(t=>e.has(`git.${t}`)),rateLimits:e=>R0(e,`block`)||R0(e,`weekly`)};function R0(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function z0(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 B0(e,t,n){let r=QG(e),i=new Map(RC(e)),a=[...z0(e,t),...n].flatMap(e=>r.ofTemplate(e).flatMap(({reaches:e})=>e)),o=new Set,s=new Set;for(;a.length>0;){let e=a.pop();if(o.has(e))continue;o.add(e);let t=i.get(e),n=XG(e,t);n!==void 0&&s.add(n);for(let{reaches:e}of r.ofVariable(t))a.push(...e)}return s}function V0(e,t){let n=new Map;for(let r of Yv(Rx(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=>oy(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,B0(e,t,n.get(t))])),a=e=>r.filter(t=>L0[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}const H0=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function U0(e){if(typeof e==`string`)return H0.exec(e)?.[1]}function W0(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 G0(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 K0(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=W0(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`?U0(G0(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 q0(e,t){return e===void 0?[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>v(e)):[e]}async function J0(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await Y0(so(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function Y0(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function X0(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await so(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=d(a,o);if(n?.has(t)){r.push(t);continue}let s=await mo(t,void 0,void 0);if(s.kind!==`ok`){k(`Failed to check agent file ${t}`);continue}i=i2(i,t,s.value);let c=t2(ho(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 Z0(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if($0(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=G0(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||Q0.test(r)?`claude-code`:`prompt`}const Q0=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function $0(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function e2(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=Z0(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:K0(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 t2(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 n2(e){let t=t2(e);if(t.kind===`unparsed`)return k(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return e2(t.value)}catch(e){return k(`Failed to project JSONL line: ${e}`),null}}function r2(e){let t=[];for(let n of e.split(`
211
211
  `)){let e=n2(n);e&&t.push(e)}return t}function i2(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function a2(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function o2(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await mo(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=i2(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,ho(c,e=>r2(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return I({folded:{cursor:a,value:o},longLines:i})}}
212
212
  /*!
@@ -497,13 +497,13 @@ function run(argv) {
497
497
  `),t.now());let e=`dispatch: ${r.join(`; `)}`;throw i?Error(e):new Z(e)}}function S6(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}async function C6(e,t,n,r){let i=e===null?null:F3(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)}S6(e)}),c=[],l=e=>M$(e,e=>I3(t,e),e=>t.log(`info`,e)),u={...t,sessionState:l(a.sessionState),journal:a,navigating:l(o.sessionState)},d=[];try{await r({...u,effect:e=>void d.push(e),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)}f&&t.described(d),S6(c)}function w6(e,t,n){return async(r,i)=>{let a=g6(e,r),o=a?.ok?a.id:null;return i.journalTurns.click(e,o,i.asker,()=>t(r,i),(e,t)=>C6(o,i,t,async t=>{try{await n(r,t,e)}finally{o!==null&&i.clickLanded(o)}}))}}const T6=new Map([...[...m6].map(([e,t])=>[e,w6(e,async(e,n)=>t.gathers?v6(t,e,n):void 0,(e,n,r)=>y6(t,e,n,r))]),[lS,w6(lS,b6,x6)],[jS,l6]]);Object.freeze([...T6.keys()]);function E6(e){let t=T6.get(e);return t===void 0?null:{name:e,run:t}}function D6(e,t,n){return n.journalTurns.take(`menu-idle`,{waited:t=>n.log(`info`,`menu-idle: waited=${t}ms (session=${e})`),gone:()=>!1},r=>C6(e,n,r,async n=>{if(!t.stillIdle()){n.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}t.closed();let r=j$(I3(n,e),t=>n.navigating.get(e,t));n.navigating.setBatch(e,r.map(({key:e})=>({key:e,value:Wi}))),n.log(`info`,`menu-idle: closed=${r.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)}))}const O6=[],k6=e=>({waited:t=>HZ(e,{turnWait:`${t}ms`}),gone:()=>!1}),A6={request:async({req:e,at:t,waitEndsAt:n,facts:r},{verbCtx:i,draw:a})=>{let o=await i.journalTurns.take(`request`,k6(r),async()=>(j6(i.sessionState,e),i.sessionState.revision(e.sessionId)));return HZ(r,{revision:String(o)}),{answer:await a(e,t,n,r),effects:O6,facts:[]}},click:async({verb:e,value:t,arrival:n,pending:r,asker:i},{verbCtx:a,menuIdle:o})=>{r!==null&&o.clickArrived(r);let s=[],c=null;try{await e.run(t,{...a,arrival:n,asker:i,described:e=>void s.push(...e)})}catch(e){c={error:e}}finally{r!==null&&o.clickSettled(r)}return{answer:c,effects:s,facts:[]}},"menu-idle":async({session:e,idle:t},{verbCtx:n})=>{let r=[];return await D6(e,t,{...n,described:e=>void r.push(...e)}),{answer:void 0,effects:r,facts:[]}},"effect-done":async({of:e,outcome:t},{verbCtx:n})=>{let r=[];return await n.journalTurns.take(`effect-done`,k6(r),async()=>{t.kind===`failed`&&e.session!==null&&Ps(n.sessionState,e.session,t.said,n.now())}),{answer:void 0,effects:O6,facts:r}},answered:async({session:e,error:t},{verbCtx:n})=>{let r=[];return await n.journalTurns.take(`answered`,k6(r),async()=>Fs(n.sessionState,e,t)),{answer:void 0,effects:O6,facts:r}}};function j6(e,t){let{client:n,configEnv:r,...i}=t.hints,a=[{key:JQ,value:JSON.stringify(i)},{key:qQ,value:t.originRecord}];e.setBatch(t.sessionId,a.filter(({key:n,value:r})=>e.get(t.sessionId,n)!==r))}async function M6(e,t){let n=A6[e.kind],r=await n(e,t),i=V6(e),a=L6[e.kind],o=a(e,r);return o!==null&&t.log(o.level,KZ(`apply`,[[`kind`,e.kind],[`verb`,i.verb],[`sid`,i.session??`-`],...o.facts,...r.facts,[`effects`,r.effects.map(e=>KQ(e)).join(`,`)||`-`],[`revision`,i.session===null?`-`:String(t.verbCtx.sessionState.revision(i.session))]])),{answer:r.answer,performed:r.effects.length===0?N6:G6(t,i,r.effects)}}const N6=Promise.resolve(),P6={level:`info`,facts:[[`outcome`,`ok`]]},F6=({error:e})=>({level:`info`,facts:[[`outcome`,`refused`],[`said`,e instanceof Error?e.message:String(e)]]}),I6={ok:`info`,failed:`warn`},L6={request:()=>null,click:(e,{answer:t})=>t===null?P6:F6(t),"menu-idle":()=>P6,answered:()=>P6,"effect-done":({effect:e,outcome:t})=>({level:I6[t.kind],facts:[[`effect`,KQ(e)],[`outcome`,t.kind],[`said`,t.said||`-`]]})},R6={request:({req:e})=>({verb:`request`,session:e.sessionId}),click:({verb:e,pending:t})=>({verb:e.name,session:t}),"menu-idle":({session:e})=>({verb:`menu-idle`,session:e}),"effect-done":({of:e})=>e,answered:({session:e})=>({verb:`answered`,session:e})};function z6(e,t,n,r){e(r instanceof YQ?`info`:`error`,`apply: ${t} not applied (${n}): ${E(r)}`)}function B6(e,t,n){return M6(e,t).then(()=>void 0,r=>z6(t.log,e.kind,n,r))}function V6(e){let t=R6[e.kind];return t(e)}const H6={launch:({spec:e,what:t},{verbCtx:n})=>U6(n.launcher,e,t),"type-slash":async({pane:e,line:t},{verbCtx:n})=>{let r=await LQ(n.claudeInput,e,t);return r.kind===`typed`?{kind:`ok`,said:`typed into ${r.pane}`}:WQ(`${t} was not typed: ${r.reason}`)},"apply-update":async(e,{verbCtx:t})=>(await t.applyUpdate(),UQ)};async function U6(e,t,n){let r=await e.launch({...t,timeoutMs:d3});return r.ok?UQ:WQ(`${n} failed (${j(r)})`)}async function W6(e,t){let n=H6[e.kind];try{return await n(e,t)}catch(e){return WQ(e instanceof Error?e.message:String(e))}}function G6(e,t,n){return e.verbCtx.journalTurns.performing(t.session,async()=>{for(let r of n){let n=await W6(r,e);await B6({kind:`effect-done`,of:t,effect:r,outcome:n},e,`${KQ(r)} ${n.kind}: ${n.said}`)}})}function K6({projectDir:e,cwd:t,target:n},r){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path===void 0?null:H1(r,n.path),source:n.source})}function q6(e,t,n){let{tokens:r}=D({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:NP(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function J6(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=sr.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${sr.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function Y6(e,t,n,r,i){let{report:a}=ZZ(e.hookData),o=[];for(let e of a.missingRequired)o.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of a.typeMismatches)o.push(`field '${e}' expected ${t}, got ${n}`);let s=tQ(e.hookData?.session_id);s.ok||o.push(`field 'session_id' ${s.problem}`),(typeof e.cwd!=`string`||!u(e.cwd))&&o.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&o.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let c=J6(e.encoding);c.ok||o.push(c.problem);let l=zr(e.deadline);if(l.kind===`refused`)return{ok:!1,problems:[...o,l.problem]};if(o.length>0||!s.ok||!c.ok)return{ok:!1,problems:o};for(let e of a.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let d=lr(e),{configFile:f,refusedArgs:p}=q6(e.args,e.cwd,r),m=I1(i),h=IP(f,d.configEnv),g={projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:h.source===`search`?h:{...h,path:G1(m,h.path)}};return{ok:!0,req:{...e,deadline:l,encoding:c.encoding,sessionId:s.id,hints:d,rateLimits:$te(e.hookData),requested:g,originRecord:K6(g,m),refusedArgs:p}}}function X6(e,t){switch(e){case`vars`:return{what:e,vars:Z6(t)};case`segments`:return{what:e,segments:n8(t)};case`config`:return{what:e,config:o8(t)}}}function Z6(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=e8(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=Q6(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:$6(r.lastUpdatedMs(),t.clock)})}return o}function Q6(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 $6(e,t){return e===null?null:Math.max(0,t.now()-e)}function e8(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,t8(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}`,t8(i));return t}function t8(e){return e.kind}function n8(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=i8(n),o=r8(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:a8(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function r8(e){let t=new Map;for(let n of Fx(e.presets))for(let r of Yv(Rx(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=Gv(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function i8(e){let t=[],n=new Set;for(let r of Yv(Tx(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 a8(e,t,n){let r=new Set([...SC(e,t).keys()].flatMap(e=>zC(e,n)));return Array.from(r).sort()}function o8(e){return e===null?null:e.config}const s8=[`vars`,`segments`,`config`];function c8(e){return typeof e==`string`&&s8.includes(e)}const l8=e=>({resp:e,exitAfterFlush:null,delivered:uQ}),u8=e=>({kind:`reply`,...e}),d8={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},f8=(e,t)=>u8(l8({ok:!1,error:t,code:e,daemonV:3}));function p8(e){let t=tQ(e.sessionId);if(!t.ok)return f8(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return f8(`VERSION_MISMATCH`,`this client's subscribe names no lane (${pb.join(`, `)}): it predates the lane toggles — update it`);let n=xb(e.lane);return n===null?f8(`BAD_REQUEST`,`subscribe needs a lane, one of ${pb.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}function m8(e){let{session:t,path:n,seconds:r}=e,i=tQ(t);if(!i.ok)return{ok:!1,problem:`record's session ${i.problem}`};if(typeof n!=`string`||!u(n))return{ok:!1,problem:`record's path is not an absolute path: ${JSON.stringify(n)}`};let a=Cr(r);return a.ok?{ok:!0,session:i.id,path:n,seconds:a.seconds}:{ok:!1,problem:`record's seconds ${JSON.stringify(r)} ${a.problem}`}}function h8(e,t){let n=m8(t);if(!n.ok)return f8(`BAD_REQUEST`,n.problem);let{session:r,path:i,seconds:a}=n;return{kind:`held`,start:t=>lQ(e.recorder,e.clock,r,i,a,t).then(e=>l8({ok:!0,recorded:e}),e=>l8({ok:!1,error:e instanceof Error?e.message:String(e),code:e instanceof cQ?`RENDER_FAILED`:`BAD_REQUEST`,daemonV:3}))}}async function g8(e,t,n,r,i){if(t.kind===`url`)return u8(l8(await w8(e,t.frame,n,r,i)));let a=t.req;return!a||typeof a!=`object`||typeof a.v!=`number`?f8(`BAD_REQUEST`,`malformed request`):a.v===3?a.kind===`subscribe`?p8(a):a.kind===`record`?h8(e,a):typeof a.kind!=`string`||!Object.hasOwn(d8,a.kind)?f8(`BAD_REQUEST`,`unknown kind`):u8(await _8(e,a,n,r,i)):(a.v>3?e.log(`info`,`version mismatch: client=${a.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):e.log(`info`,`version mismatch: client=${a.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${a.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:a.v>3?0:null,delivered:uQ})}async function _8(e,t,n,r,i){let{stats:a,clock:o,frameFeeds:s,renderCache:c,payloadProviders:{gitProvider:l,usageStore:u},fileEvents:d,runs:f,sourceRuns:p,effectSessions:m,menuIdle:h,journalTurns:g,tmuxStatusLines:_,watcherRegistry:v,limits:y,handlerProbes:b,renderSightings:x,bundle:S,sourceDigest:C,doctorStores:ee}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:uQ};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return l8(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 l8({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:v8(e),fileEvents:d.stats(),sourceRuns:p.stats(),runs:f.stats(),transcriptReads:uo(),renderCache:c.stats,effectCache:m.getStats(),menuIdle:h.getStats(),journalTurns:g.getStats(),sessionState:{sessions:e.sessionGauges.size(),observers:e.sessionGauges.observers(),revision:e.sessionGauges.latestRevision()},frameFeeds:s.getStats(),tmuxStatus:_.stats(),watchersActive:v.size(),dirWatchesActive:v.dirWatches(),nextRestartReason:y.describeNextRestart(),handlerProbes:b.list(),clients:x.list(it(new Date(o.now()))),bundle:S,sourceDigest:C,daemon:y.serving(),doctorStores:r4(ee)})});if(t.kind===`render`){let c=new Date(o.now()),l=it(c),u=o.monotonic(),d=Qe(r,u),f=[],p=++a.requestsTotal,m=Y6(t,a,e.log,e.home,e.storedRoot),h=(t,n)=>x.see(t.sessionId,{client:t.hints.client??null,termCols:t.hints.termCols??null,rateLimits:t.rateLimits,claudeConfigDir:So(t.hints.claudeConfigDir,e.home),projectDir:t.requested.projectDir,transcript:ene(t.hookData),frame:n},l,p);m.ok&&(HZ(f,{sid:m.req.sessionId}),h(m.req,`drawing`),s.note(m.req.sessionId,m.req,p));let g=m.ok?await M6({kind:`request`,req:m.req,at:l,waitEndsAt:Ze(u,Br(m.req.deadline,r,{epochMs:c.getTime(),monoMs:u})),facts:f},e).then(({answer:{resp:t,motion:n,answersClick:r,pipeShown:i,delivered:a}})=>(h(m.req,n),{outcome:{kind:`ok`},resp:t,delivered:()=>{a(),r!==null&&B6({kind:`answered`,session:m.req.sessionId,error:r},e,`sid=${m.req.sessionId}`),i!==null&&e.launcher.answeredPipeEvent(i)}}),e=>(h(m.req,`failed`),{outcome:D8(e),resp:dQ(e),delivered:uQ})):P8(m.problems);g.outcome.kind!==`ok`&&a.requestsErrored++,HZ(f,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:_,line:v}=GZ(`render`,f,g.outcome,A(o,u));return e.log(_,v),{resp:g.resp,exitAfterFlush:null,delivered:g.delivered}}if(t.kind===`click`)return l8(await S8(e,r,n,i,(n,r)=>C8(e,t,n,r)));if(t.kind===`debug`){if(!c8(t.what))return l8({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${s8.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`?x8(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??ex(`colorCompatibility`)):b8};return l8({ok:!0,debug:X6(t.what,n)})}throw Error(`no reply for request ${E(t)}`)}function v8(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 y8={endcaps:ex(`endcaps`),colorCompatibility:ex(`colorCompatibility`),wrap:ex(`autoWrap`),padding:ex(`padding`),width:1/0},b8=new Map;function x8(e,t){let n=new Map;for(let[r,i]of e)n.set(r,Yte(i,{...y8,colorCompatibility:t}));return n}async function S8(e,t,n,r,i){let{clock:a}=e,o=a.monotonic(),s=[[`queued`,`${Qe(t,o)}ms`]],c=await i(s,()=>n()||r());HZ(s,{timedOut:n()?`Y`:`N`,clientLeft:r()?`Y`:`N`});let{level:l,line:u}=GZ(`click`,s,c,A(a,o));return e.log(l,u),M8(c)}async function C8(e,t,n,r){let i={via:`link`,delivery:{kind:`cli`}};HZ(n,{via:`cli`});let{url:a}=t;return typeof a==`string`?T8(()=>A8(e,a,i,n,r)):{kind:`bad-request`,problems:[`a click's link is a string, got ${typeof a}`]}}async function w8(e,t,n,r,i){return S8(e,r,n,i,async(n,r)=>{let{urlV:i,url:a}=t;if(HZ(n,{via:`forwarder`,urlV:String(i)}),typeof i!=`number`||!br.has(i))return{kind:`bad-request`,problems:[`the URL handler's frame version ${E(i)} is not one this daemon speaks (${[...br].join(`, `)})`]};if(typeof a!=`string`)return{kind:`bad-request`,problems:[`the URL handler's frame carries no url string`]};let o={via:`link`,delivery:{kind:`forwarder`,urlV:i}};return T8(()=>A8(e,a,o,n,r))})}async function T8(e){try{return await e()}catch(e){return E8(e)}}function E8(e){return e instanceof Z?{kind:`bad-request`,problems:[e.message]}:e instanceof XQ?{kind:`abandoned`,error:e}:D8(e)}function D8(e){return e instanceof YQ?{kind:`closing`,error:e}:{kind:`threw`,error:e}}const O8={link:`to`,"tmux-status":`linkTo`},k8={link:`verb`,"tmux-status":`linkVerb`};async function A8(e,t,n,r,i){let a=QS(t);if(!a.ok)return{kind:`bad-request`,problems:[a.problem]};HZ(r,{[O8[n.via]]:a.to});let o=e.links.to;return a.to===o?j8(e,a.verb,a.value,n,r,i):{kind:`bad-request`,problems:[`the link is addressed to renderer ${JSON.stringify(a.to)}, and this is ${JSON.stringify(o)}`]}}async function j8(e,t,n,r,i,a){if(t===`tmux-status-click`)return r.via===`tmux-status`?{kind:`bad-request`,problems:[`a status-line link names another status-line click`]}:(HZ(i,{verb:t}),N8(e,n,i,a));let o=E6(t);if(o===null)return{kind:`bad-request`,problems:[`unknown click verb: ${t}`]};HZ(i,{[k8[r.via]]:t});let s=g6(t,n),c=s?.ok?s.id:null;s===null?HZ(i,{sid:`-`}):c!==null&&HZ(i,{sid:c});let{answer:l}=await M6({kind:`click`,verb:o,value:n,arrival:r,pending:c,asker:{placed:e=>HZ(i,{placeWait:`${e}ms`}),gathered:e=>HZ(i,{gather:`${e}ms`}),waited:e=>HZ(i,{turnWait:`${e}ms`}),gone:a}},e);if(l!==null)throw l.error;return{kind:`ok`}}function M8(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 dQ(e.error)}}async function N8(e,n,r,i){let{tmuxStatusLines:a}=e,o=e=>({kind:`bad-request`,problems:[e]}),s=a.linkAt(n);return s.kind===`refused`?o(s.reason):(HZ(r,{link:s.url}),Ui(s.url)?A8(e,s.url,{via:`tmux-status`},r,i):(await p3(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,d3,e.tmp),{kind:`ok`}))}const P8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:uQ});function F8(e,t){let n=le(`sha256`).update(t).digest(`hex`).slice(0,16);return s.join(e,`update-act`,n)}const I8={kind:`idle`};function L8(e){if(e===null)return I8;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 R8=e=>({stdout:s.join(e,`stdout`),stderr:s.join(e,`stderr`),status:s.join(e,`status`)}),z8=e=>s.join(e,`record.json`);function B8(e){let t;try{t=m.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 V8(e){let t=yo(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 H8(e,t){let n=s.join(e,`.removed-${t}-${process.pid}`);try{m.renameSync(s.join(e,String(t)),n)}catch(e){if(e.code===`ENOENT`)return;throw e}m.rmSync(n,{recursive:!0,force:!0})}const U8=e=>e.now()-o.uptime()*1e3;async function W8(e,t,n,r){if(e.started<=r||!n.jobGroupAlive(e.pid))return!1;let i=await t(e.pid);return e.startTime===null||i.kind===`unavailable`||i.token===e.startTime}function G8(e){try{return JSON.parse(m.readFileSync(z8(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}const K8=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function q8(e,t,n,r){let i=null;async function a(a){let o=s.join(e,String(a)),c=G8(o);if(c===null)return null;if((i===null||!K8(i.record,c))&&(i={record:c,ours:await W8(c,t,n,U8(r)),final:null}),i.final!==null)return i.final;i.ours=i.ours&&n.jobGroupAlive(c.pid);let l=R8(o),u=Gt(l.status),d=u===null?null:V8(l.stderr)??V8(l.stdout);if(!m.existsSync(o))return null;let f={act:a,record:c,alive:i.ours,end:u,lastLine:d};return f.alive||(i.final=f),f}return{async read(){let t=null;for(;;){let n=B8(e).at(-1);if(n===void 0)return null;if(n===t)throw Error(`${s.join(e,String(n))}: an act with no record`);let r=await a(n);if(r!==null)return r;t=n}}}}function J8(e,t,n){m.mkdirSync(e,{recursive:!0});let r=m.mkdtempSync(s.join(e,`.claim-`));try{return m.writeFileSync(z8(r),JSON.stringify(n)),m.renameSync(r,t),!0}catch(e){let t=e.code;if(t===`ENOTEMPTY`||t===`EEXIST`)return!1;throw e}finally{m.rmSync(r,{recursive:!0,force:!0})}}async function Y8(e,t,n,r,i,a,o,c){let l=(n??0)+1,u=s.join(t,String(l)),d=e.launchJobSync(i,R8(u));if(!d.ok)throw Error(`apply-update: ${d.error}`);let f=!1;try{let e=await c(d.pid);if(!J8(t,u,{identity:r,pid:d.pid,startTime:e.kind===`start`?e.token:null,started:o,deadline:o+a}))return X8;if(B8(t).some(e=>e>l))return H8(t,l),X8;f=!0}finally{f?d.release():d.withdraw()}for(let e of B8(t).filter(e=>e<l))H8(t,e);return{ok:!0,act:l}}const X8={ok:!1,reason:`another act claimed this bundle first`};function Z8(e,t,n){let r=R8(s.join(e,String(t.act))).status;return n.endJob(t.record.pid,r,{kind:`timeout`})}var Q8=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 $8(e){return e.kind===`source`?e.newer.digest:No(e.newer)}const e5=e=>`${e.version} [${yn(e.digest)}]`;function t5(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:e5(e.newer),running:e5(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:No(e.newer),running:No(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${Fo}@${No(e.newer)}`,`install`]}}}}function n5(e,t,n){if(e===null)return[];let r=$8(e);if(!n.enabled||n.dismissed===r)return[];let i=t5(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(`
498
498
  `),c=t.kind===`running`?kU(`[${i.busy}]`,null):kU(`[${i.act}]`,GS(n.to,[{verb:DS,args:[n.sessionId]}])),l=[kU(a,null),c,kU(`[dismiss]`,GS(n.to,[{verb:uS,args:[n.sessionId,Gz,r]}])),kU(`[disable]`,GS(n.to,[{verb:hS,args:[n.sessionId,Kz,`false`]},{verb:uS,args:[n.sessionId,qz,`false`]}]))],u=o.map(e=>[kU(e,null)]);return[{severity:EU,about:`update\0${r}`,message:s,copy:s,lines:[l,...u]}]}function r5(e,t){if(e.kind===`pending`)return e;let n=e.value;switch(n.kind){case`stale`:return I({kind:`source`,root:n.root,newer:n.source,running:n.running});case`current`:return L;case`unchecked`:return R(`build: unchecked: ${n.reason}`,`read`);case`not-source-checkout`:return i5(t)}}function i5(e){if(e.kind===`pending`)return e;let t=e.value;switch(t.kind){case`stale`:return I({kind:`release`,newer:t.latest,running:t.installed});case`current`:case`ahead`:return L;case`unchecked`:return R(`release: unchecked: ${t.reason}`,`read`)}}function a5(e){switch(e.kind){case`current`:return[`info`,`build: current ${e5(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${e5(e.source)}, running ${e5(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function o5(e){switch(e.kind){case`current`:return[`info`,`release: current ${No(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${No(e.latest)}, running ${No(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${No(e.installed)}, latest ${No(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function s5(e){let{fact:t,clock:n,launcher:r,probe:i,entryUrl:a,digest:o,actsDir:s,intervalMs:c,releaseIntervalMs:l,registryUrl:u,fetchImpl:d,gates:f,onApplied:p,log:m}=e,h=$a(`unread`),g=$a(`unread`),_=async e=>{let t=await i.startTime(e);if(w)throw new YQ(`apply-update`);return t},v=q8(s,_,r,n),y=null,b=null,x=Ie(m),S=Ie(m),C=new Q8,ee=e=>C.run(`acts`,e),w=!1,te=[],ne=(e,t)=>{te.push(n.every(t,e,{unref:!0}))},T=()=>{let e=t.get();return e.kind===`ok`?e.value:null};function re(){let e=T(),t=e===null?null:$8(e);(b===null?null:b.identity)!==t&&(b?.dispose(),b=t===null?null:{identity:t,dispose:f.state.register(Gz,[t])})}function E(){let e=w?L:r5(h,g),r=qZ(t.get(),e,st(n));(0,Y.runInAction)(()=>t.set(r)),re()}function D(){let e=P(a,()=>Sn(o));return h=I(e),x(a5(e)),E(),e}async function ie(){let e=Lo(bn,await Io(Fo,d,u,n));g=I(e),S(o5(e)),E()}let O=null,ae=Ie(m);async function oe(e){try{let t=await e();return O=null,{ok:!0,value:t}}catch(e){return e instanceof YQ?{ok:!1,error:e.message}:(O=`update act files (${s}): ${e.message}`,ae([`error`,O]),{ok:!1,error:O})}}function se(e){if(!e?.alive||n.now()<=e.record.deadline)return;let{stands:t,signalled:i}=Z8(s,e,r),a=t?`timed out`:`outlived its verdict`,o=i?`ending it`:`its group took no signal`;m(`error`,`apply-update: act ${e.act} ${a}; ${o}`)}async function ce(){let e=await oe(async()=>{let e=await v.read();return w||se(e),e});if(w||!e.ok)return;let t=L8(e.value);y===null&&t.kind===`running`&&m(`info`,`apply-update: act ${t.act} is running; watching it`),y?.kind===`running`&&t.kind!==`running`&&(t.kind===`succeeded`&&(m(`info`,`apply-update: act ${t.act} succeeded`),D(),p()),t.kind===`failed`&&m(`error`,`apply-update: act ${t.act} failed: ${t.reason}`)),y=t}let le;async function ue(){await ee(ce),!w&&(le=n.after(2e3,()=>void ue(),{unref:!0}))}return{arm(){let e=D();ne(D,c),te.push(()=>le?.()),ue(),e.kind===`not-source-checkout`&&(ie(),ne(()=>void ie(),l))},close(){w=!0,E(),te.forEach(e=>e())},notice:e=>n5(T(),y??I8,e),running:()=>ee(async()=>{let e=await oe(()=>v.read());return e.ok&&L8(e.value).kind===`running`}),error:()=>O,act:()=>ee(async()=>{if(w)throw new YQ(`apply-update`);let e=await oe(()=>v.read());if(w)throw new YQ(`apply-update`);if(!e.ok)throw new Z(`apply-update: ${e.error}`);let t=T();if(t===null)throw new Z(`apply-update: nothing newer is known to apply`);let i=t5(t),a=e.value;if(L8(a).kind===`running`)throw new Z(`apply-update: already ${i.busy}`);let o=await Y8(r,s,a===null?null:a.act,$8(t),{...i.command,category:`update.apply`},6e5,n.now(),_);if(!o.ok)throw new Z(`apply-update: ${o.reason}`);m(`info`,`apply-update: act ${o.act}: ${i.act} — ${i.command.bin} ${i.command.args?.join(` `)??``}`),y={kind:`running`,act:o.act}})}}function c5(){return Y.observable.box($a(`unread`),{deep:!1})}function l5(e,t){try{return I(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?L:R(e.message,`read`)}}function u5(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function d5(e){let{targets:t,intervalMs:n,stat:r,held:i,exit:a,log:o,clock:s}=e,c=Ie(o),l=t.map(e=>({path:e,stamp:l5(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=l5(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!u5(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}}var f5=class{running=new Map;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:{kind:`started`,done:this.start(e,t)}}share(e,t){let n=this.running.get(e);return n===void 0?(this.again.add(e),this.start(e,t)):n}start(e,t){let n=this.loop(e,t);return this.running.set(e,n),n}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const p5=`pass`,m5={okMs:5*6e4,failedMs:45e3},h5=m5.okMs;function g5({failures:e}){return Rj(m5,e,h5)}function _5(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function v5(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function y5(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function b5(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:s.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>cc(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${lc(i[t])}`).join(`|`)}`,targets:{dirs:r},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function x5(e){return e.find(e=>e.kind===`ok`)?.value.branch}function S5(e){e.missed=!0,Uj(e,`unread`)}function C5(e,t){return e.missed&&e.reading.get().kind===`pending`&&Hj(e,t.size>0?R([...t].join(`; `),`read`):L),`unkeyed`}function w5(e,t){let n=Kj(e);return t===null||n.kind!==`ok`?n:I({...n.value,pullRequest:Kj(t)})}const jne=R(`git cache closed`,`read`);function T5(e){return t=>R(`${e} threw: ${String(t)}`,`read`)}var Mne=class{repos=new Map;resolutions=new Map;closed=!1;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;forgeLookups;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.forgeLookups=new to(e.maxPrLookups??2),this.logger=e.logger??Le;let t=e.ledger??new rM(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 Ij({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.monotonic(),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=R(`resolver threw: ${String(e)}`,`read`)}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 Xj(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>w5(a,o)}}asked(e,t,n,r){if(this.closed)return{kind:`settled`,outcome:jne};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 f5,watch:this.followWatch(e,null).watch,period:new zj(()=>{n.refresh.share(p5,()=>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=b5(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(p5,()=>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&&S5(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(p5,()=>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:Bj(),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=y5(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(v5(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.monotonic(),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(T5(`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,Hj(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of Jq(n.value))c.add(e)});let l=x5(o),u=a===null||i.length===0?`-`:l===void 0?C5(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}`,_5(n),c.size===0?I(null):R([...c].join(`; `),`read`),A(this.clock,t))}prSource(e){let t={period:new zj(()=>{this.readPr(e,t,`period`)},this.clock),seen:new Map,holders:0,missed:!0,key:``,remote:L,reading:Bj(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(T5(`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?(S5(t),`owed`):(Uj(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,Hj(t,a.outcome),t.period.landed(g5(a),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.monotonic(),o=(i.kind===`ok`?this.forgeLookups.run(()=>(a=this.clock.monotonic(),this.inner.resolvePullRequest(e.root,i.value))).catch(T5(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:L)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${z(r)}`,n,i,A(this.clock,a));let o=this.clock.monotonic(),s={outcome:i,at:o,failures:i.kind===`failed`?(t.seen.get(r)?.failures??0)+1:0};t.seen.delete(r),t.seen.set(r,s);for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==r||t.missed||(Hj(t,i),t.period.landed(g5(s),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=R(`git state dropped: ${e.root}`,`read`);for(let n of e.values.values())Wj(n,t);e.pr!==null&&Wj(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()}};const E5={"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}},D5=new n(`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`);function Nne(e){let t=null;return{table:()=>e.closing.aborted?Promise.resolve(E5):t??=Pne(e).catch(t=>(e.log(`error`,`pricing load threw: ${String(t)}`),E5))}}const O5=e=>s.join(e,`usage`,`pricing.json`);async function Pne(e){let t=await Fne(e);if(t!==null)return t;let n=e.closing.aborted?null:await Lne(e.closing);return n===null?(k(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(E5).length} models`),E5):(e.closing.aborted||await Ine(e,n),n)}async function Fne(e){try{let t=JSON.parse(await m.promises.readFile(O5(e.cacheRoot),`utf8`));return typeof t.timestamp==`number`&&t.timestamp>=e.clock.now()-864e5&&k5(t.data)?t.data:null}catch(t){return t.code!==`ENOENT`&&e.log(`warn`,`pricing disk cache unreadable: ${String(t)}`),null}}async function Ine(e,t){let n=O5(e.cacheRoot),r=`${n}.${process.pid}.${fe()}`;try{await m.promises.mkdir(s.dirname(n),{recursive:!0}),await m.promises.writeFile(r,JSON.stringify({data:t,timestamp:e.clock.now()}),`utf8`),await m.promises.rename(r,n)}catch(t){e.log(`warn`,`pricing disk cache not written: ${String(t)}`),await m.promises.rm(r,{force:!0}).catch(()=>{})}}function Lne(e){return new Promise(t=>{let n=be({hostname:D5.hostname,path:D5.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3,agent:!1,signal:e},e=>{if(e.statusCode!==200){k(`HTTP ${e.statusCode}: ${e.statusMessage}`),e.resume(),t(null);return}let r=``,i=0;e.setEncoding(`utf8`),e.on(`data`,e=>{if(i+=Buffer.byteLength(e),i>1048576){k(`Response too large`),n.destroy(),t(null);return}r+=e}),e.on(`end`,()=>{try{let e=JSON.parse(r),n=e._meta,i={};for(let[t,n]of Object.entries(e))t!==`_meta`&&(i[t]=n);k5(i)?(k(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),k(`Pricing last updated: ${n?.updated||`unknown`}`),t(i)):(k(`Invalid pricing data structure`),t(null))}catch(e){k(`Failed to parse JSON:`,e),t(null)}}),e.on(`error`,e=>{k(`Response error:`,e),t(null)})});n.on(`error`,e=>{k(`Request error:`,e),t(null)}),n.on(`timeout`,()=>{k(`Request timeout`),n.destroy(),t(null)}),n.end()})}function k5(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`||typeof e.cache_write_5m!=`number`)return!1}return!0}function Rne(e,t){let n=t[e];if(n)return n;let r=e.toLowerCase();for(let[e,n]of Object.entries(t))if(e.toLowerCase()===r)return n;for(let{pattern:e,fallback:n}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=>r.includes(e))&&t[n])return t[n];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}}function zne(e,t){let n=t.message?.usage;if(!n)return 0;let r=Rne(Bne(t),e),i=n.input_tokens||0,a=n.output_tokens||0,o=n.cache_creation_input_tokens||0,s=n.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}function Bne(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`}var A5=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}};function Vne(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 Hne={okMs:60*1e3,failedMs:10*1e3},j5={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function M5(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-1),t.getTime()}function N5(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const Une={entries:0,cost:0,breakdown:N5(),days:new Map};async function Wne(e,t,n,r){let i=zX(new Date(M5(r.now()))),a=e.entries,o=e.cost,s={...e.breakdown},c=null,l=new Map;for(let[t,n]of e.days)t>=i&&l.set(t,{...n});for(let e of t){let t=e.message?.usage;if(!t)continue;a++;let r=e.costUSD??zne(c??=await n.table(),e.raw);o+=r,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=zX(new Date(e.timestamp));if(u<i)continue;let d=l.get(u)??{...LX};d.cost+=r,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,l.set(u,d)}return{entries:a,cost:o,breakdown:s,days:l}}function Gne(e){let t=0,n=0,r=N5(),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)??{...LX};RX(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:j5,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 P5(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function Kne(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!P5(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...LX};RX(r,t),n.set(e,r)}return Object.fromEntries(n)}async function qne(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 F5(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function I5(e,t){(0,Y.runInAction)(()=>e.set(t))}var Jne=class{sessions=Y.observable.map(void 0,{deep:!1});flight=new A5;scans;daySets=new Map;speedFlight=new A5;requestFlight=new A5;staleAgeMs;host;pricing;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;stopSweep=null;closed=!1;clock;constructor(e){this.host=e.host,this.pricing=e.pricing,this.clock=e.clock,this.log=e.logger??Le,this.ledger=e.ledger??new rM(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new Qj({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${z(e.join(`,`))}`,read:e=>this.scan(e),every:()=>e.rescan??Hne,watch:Zj,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=ro(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:I(F5(t.kind===`ok`?t.value.sessionInfo:j5,e))},speed:t=>this.observed(e,r,t),today:async()=>{await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return $a(`unread`);let r=n.failure.get();return r===null?I(F5(n.record?.sessionInfo??j5,t)):R(r,`read`)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=this.clock.monotonic(),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=${z(e)}`,`request`,a,A(this.clock,i)),I5(this.hold(e).failure,a.kind===`failed`?a.reason:null),a})}refreshToday(e){return this.request(e?.session_id??``,e?.transcript_path).today()}declareToday(e,t){if(this.closed)return Xj(R(`usage store closed`,`read`));let n=q0(t,this.host.home),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?I({roots:i.roots,sums:i.sums.read()}):e}}}daysOutside(e,t){let n=this.sessions.get(e);if(n===void 0)return L;let r=n.failure.get();if(r!==null)return R(r,`read`);let i=n.record;return i===void 0||P5(i.transcriptPath,t)?L:I(Object.fromEntries(i.days))}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return L;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return I5(this.hold(e).speed,t),t;let r=Vne(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=I({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return I5(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??$a(`unread`):L}async ingest(e,t,n,r){if(!e)return L;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,I(i);if(!t)return i?I(i):L;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 R(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`,`read`)}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),I(c)):l===void 0?I(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=>d(e,`projects`)+p),i={roots:r,sums:new tw(`today over ${e.join(`,`)}`,()=>Kne(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await X0(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of a2(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 o2(e,r,Une,(e,t)=>Wne(e,t,this.pricing,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 a2(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return I({files:i,...Gne(i),mainStamp:a})}async scan(e){try{let t=M5(this.clock.now()),n=await J0(e),r=[];for(let e of n){let n=await Y0(so(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a=await Y0(co(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:io(a)})}}let i=[],a={hits:0,misses:0};return await qne(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=${z(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?R(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`,`read`):I({sessions:r.length,read:a.misses})}catch(e){return R(`usage scan: ${e instanceof Error?e.message:String(e)}`,`read`)}}sweepStale(){let e=this.clock.now(),t=zX(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()}},L5=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)}})}},R5=class{sessions;flight=new A5;constructor(e,t,n,r,i=Le,a=256){this.empty=e,this.step=t,this.refreshes=n,this.clock=r,this.log=i,this.sessions=new L5(a)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=ro(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})}return this.flight.run(e,()=>this.fold(e,t,r))}async fold(e,t,n){let r=this.clock.monotonic(),i=await o2(t,n,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${z(e)}`,`request`,i,A(this.clock,r)),i.kind===`failed`)return this.store(e,n,i);if(i.kind===`absent`)return this.store(e,n,{kind:`ok`,value:n?.value??this.empty});let{folded:a,longLines:o}=i.value;for(let e of a2(o))this.log(`info`,e);return this.store(e,a,{kind:`ok`,value:a.value})}answer(e){return this.sessions.get(e)?.answer??$a(`unread`)}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function Yne(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 Xne=class{fold;constructor(e){let t=e.logger??Le;this.fold=new R5(void 0,Yne,(e.ledger??new rM(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?I(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,z5(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return I(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,z5(e))}contextFrom(e,t){if(e.kind===`failed`)return R(`context transcript: ${e.reason}`,e.failedAt);let n=e.value;return n===void 0?(k(`No main chain entries with usage data found`),L):(k(`Most recent main chain context: ${n} tokens (limit: ${t})`),I({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function z5(e){return e.context_window?.context_window_size??2e5}const Zne={messageCount:0,nonPrompts:0,recent:[]},Qne=new Set([`turn`,`interrupt`,`claude-code`]);function $ne(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!Qne.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function ere(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 tre=class{fold;constructor(e){let t=e.logger??Le;this.fold=new R5(Zne,$ne,(e.ledger??new rM(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?B5(e,n,await this.fold.read(e,t.transcript_path)):L}metricsOf(e,t){let n=t.cost;if(!n)return L;let r=this.fold.answer(e);return r.kind===`pending`?r:B5(e,n,r)}};function B5(e,t,n){return n.kind===`failed`?R(`metrics (${e}): ${n.reason}`,n.failedAt):I({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:ere(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 nre={command:null,todos:[],pending:[],done:[]};function V5(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 rre(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 ire(e,t){if(t.isSidechain)return e;let n=rre(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=V5(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 are(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>V5(e,t.name),[]),done:e.done}}var ore=class{fold;constructor(e){let t=e.logger??Le;this.fold=new R5(nre,ire,(e.ledger??new rM(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getActivityInfo(e,t){return H5(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:H5(e,t)}};function H5(e,t){return t.kind===`failed`?R(`activity (${e}): ${t.reason}`,t.failedAt):I(are(t.value))}const U5=3e4;var sre=class{names;constructor(e){let t=e.logger??Le;this.names=new Qj({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${z(e.pane)} socket=${z(e.socket)}`,read:t=>cre(e.launcher,t),every:()=>({okMs:U5,failedMs:U5}),watch:Zj,maxEntries:64,logger:t,ledger:e.ledger??new rM(t),clock:e.clock})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function cre(e,t){let n=await Ms(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return R(n.reason,`read`);let r=n.stdout.trim();return r?I(r):L}const W5=6e4,lre={okMs:W5,failedMs:W5};function ure(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function G5(e,t){try{let e=t();return Promise.resolve(e===``?L:I(e))}catch(t){return Promise.resolve(R(`host.${e}: ${String(t)}`,`read`))}}var dre=class{name;user;constructor(e){let t=e.logger??Le,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:()=>lre,watch:Zj,maxEntries:1,logger:t,ledger:e.ledger??new rM(t),clock:e.clock};this.name=new Qj({...n,name:`host.name`,read:()=>G5(`name`,()=>ure(o.hostname()))}),this.user=new Qj({...n,name:`host.user`,read:()=>G5(`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()}},fre=class{known=new L5(64);refreshes;constructor(e,t=Le,n=new rM(t)){this.clock=e,this.refreshes=n.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=pre(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=this.clock.monotonic(),i=WI(e);return this.refreshes.recorded(`path=${z(e)} stamp=${z(t)}`,`request`,i,A(this.clock,r)),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??$a(`unread`)}getStats(){let{refreshes:e,failures:t,abandoned:n,lastMs:r}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,abandoned:n,lastMs:r}}};function pre(e){try{let t=m.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:io(t)}catch(e){return`unread:${e.code??`error`}`}}const mre=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function hre(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 gre=class{known=new L5(256);refreshes;constructor(e,t=Le,n=new rM(t)){this.clock=e,this.refreshes=n.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=ro(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??$a(`unread`)}getStats(){let{refreshes:e,failures:t,abandoned:n,lastMs:r}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,abandoned:n,lastMs:r}}async read(e,t,n){let r=this.clock.monotonic(),i=await _re(t);return this.refreshes.recorded(`sid=${z(e)} stamp=${z(n)}`,`request`,i,A(this.clock,r)),i}};async function _re(e){let t=await vre(e);return t.kind===`ok`?I(Math.floor((t.value+36e5)/1e3)):t}async function vre(e){for(let t of[65536,1048576]){let n=await vo(e,t);if(n.kind!==`ok`)return n;let r=yre(n.value.buf,n.value.fromStart);if(r!=null)return I(r);if(n.value.fromStart)return L}return L}function yre(e,t){let n=e.toString(`utf8`).split(`
499
499
  `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!mre.test(t))continue;let r=hre(t);if(r!=null)return r}return null}const K5=e=>vH(e),q5=e=>s.join(e.storage.folder,K5(e.sessionId)),J5=e=>JSON.stringify([e.folder,e.generation]),Y5=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var bre=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??ac,this.fileEvents=e.fileEvents,this.clock=e.clock,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new Qj({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${z(q5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:()=>null,watch:Zj,maxEntries:256,logger:e.logger,ledger:e.ledger??new rM(e.logger),clock:e.clock})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{m.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`||!oc(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${z(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(J5(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:${J5(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(J5(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=J5(e.key);this.watched.delete(t),e.health={kind:`closed`},e.stopSweep(),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>Y5(e.storage,n);switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.has(s.join(n.folder,s.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(q5(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`&&oc(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${z(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>Y5(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=${z(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>Y5(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(J5(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=_c(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 R(t,`read`);let n=q5(e),r;try{r=await m.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?L:R(`${n}: ${t.message}`,`read`)}if(r.trim()===``)return L;let i=lM(r);return i.kind===`failed`?R(`${n}: ${i.reason}`,i.failedAt):i}async sweep(e){let t=this.clock.monotonic(),n=this.clock.now()-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${z(e.folder)} scanned=${r} removed=${i} took=${A(this.clock,t)}ms`;try{let t=await m.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=s.join(e.folder,a.name);try{let{mtimeMs:r}=await m.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&K5(t.sessionId)===a.name);if(r>=n||o)continue;await m.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 xre(e){let{launcher:t,clock:n,logger:r,ledger:i}=e;return{home:e.host.home,hostService:new dre({clock:n,logger:r,ledger:i}),gitProvider:new Mne({inner:new SJ(t),watchers:e.watchers,clock:n,logger:r,ledger:i}),usageStore:new Jne({host:e.host,pricing:e.pricing,clock:n,logger:r,ledger:i}),contextProvider:new Xne({clock:n,logger:r,ledger:i}),metricsProvider:new tre({clock:n,logger:r,ledger:i}),activityProvider:new ore({clock:n,logger:r,ledger:i}),tmuxService:new sre({launcher:t,clock:n,logger:r,ledger:i}),autoCompact:new fre(n,r,i),cacheExpiry:new gre(n,r,i),managedStorage:new bre({watchers:e.watchers,fileEvents:e.fileEvents,clock:n,logger:r,ledger:i}),faults:new WX,log:e.logger,clock:n}}function*X5(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*Sre(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 Fx(e.presets)){for(let n of Yv(Rx(e,t).node))n.when!==void 0&&(yield n.when);let n=Bx(e,t);for(let e of lv){let t=n[e];uv(t)&&(yield t)}}for(let[,t]of X5(e))for(let[,e]of iy(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of Yx(t))yield e}function Cre(e,t,n){let r=QG(t),i=new Set,a=new Set,o=new Set;for(let e of Sre(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of EC(e,t.helpers))a.add(n);for(let n of NC(e,t.helpers))o.add(n)}for(let[,e]of X5(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 Fx(t.presets))for(let n of Yv(Rx(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=>!rS(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(X5(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 wre(e){return Math.floor(Math.max(e/4,e*di-67108864))}const Tre={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function Z5(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[_H(nC(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[nC(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>rC(e)(t)&&t!==_H(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${RP(e,`<default>`)}: projections=${[...pq(n).keys()].join(`,`)||`-`} instantSegments=${jq(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 Ere=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},Dre=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${Ere(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function Ore(e,t,n){let r=e=>z(e.join(`,`)||`-`);return`config loaded projectDir=${z(e.projectDir)} cwd=${z(e.cwd)} cause=${z(Dre(t))} state=${n} files=${z(RP(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 kre(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function Are(e,t,n){return e+`\0`+t+`\0`+(n??``)}function jre(e,t){return new Set(Fx(e.presets).filter(n=>Rx(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function Mre(e,t){let{loaded:n,dropped:r,unreached:i}=e.state.plugins,a=[...new Set([...e.state.plugins.roots,s.join(e.projectDir,ZH)])];return kj({named:[...dU(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 Nre(e){return e.filter(Boolean).join(`
500
- `)||null}const Q5=e=>e instanceof Error?e.message:String(e);function $5(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function Pre(e){let{loaded:t,chain:n}=e;return Vv({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:$5(e.plugins),source:null,warnings:null})),base:t.base,installed:{...$5(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 Fre(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 e7(e,t,n){let r=[];try{let i=cX(t.locs,t.layers,PX,{warned:e=>r.push(...e)},{repo:t.repo,cwd:e}),a={cwd:e,chain:t,loaded:i,sources:Fre(i.config,n)};return{kind:`resolved`,...a,key:Pre(a),warnings:r}}catch(e){return e instanceof xy&&r.push(...e.warnings),{kind:`failed`,cause:e,warnings:r}}}function t7(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??PX,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new dw(t.clock),m=new jM(t.runs,p,o.globals.default_empty_value??``,t.sessionState),h;try{h=Tq(o,m,n,t.compile??wq(t.links),Lre),f.push(...h.loadWarnings);let r=m.view();f.push(...Oq(o,r,n,a7)),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 xy&&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,authoredRoots:jre(l,u),fileHeldSettings:y$(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>Cre(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 n7(e,t,n,r,i){let a={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:A(i,e.started)},o=t=>Nre([...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:Q5(r.cause),cause:r.cause}}}function Ire(e,t,n,r,i=null){let a=e7(t,n,r.storage);if(a.kind===`failed`)return n7(e,n,[],a,r.clock);let o=i?.loadKey===a.key?{kind:`kept`,state:i}:t7(a,r);return n7(e,n,a.warnings,o,r.clock)}function r7(e,t,n,r,i=null){let a=r.clock.monotonic(),o=hU(r.locations,$U(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 Ire({repos:s,advisories:[SU(r.locations,e,t),bU(o),cU(s)],started:a},t,c,r,i)}function i7(e,t,n){let r=e7(e,{layers:[],home:``,repo:t,locs:n.locations},n.storage),i=r.kind===`failed`?r:t7(r,n);if(i.kind===`failed`)throw Error(`bundled default failed to load: ${Q5(i.cause)}`,{cause:i.cause});return i.state}const Lre=new Set([`directory`]),a7=new Set([`view`]);function Rre(e,t,n,{facts:r,source:i,changed:a,log:o}){let{sessionId:s}=n,c=e.registry.view();Oq(e.config,c,t,a7);let l={sources:e.sources},u;try{u=r.follow(n,l)}catch(e){throw c.dispose(),e}let d=Y.observable.box({facts:n},{deep:!1}),f=e=>{e!==d.get().facts&&(0,Y.runInAction)(()=>{u.follow(e,l),d.set({facts:e})})},p=[],m=()=>{for(let e of p)e();return u.dispose(),c.dispose()},h;try{h=i({sessionId:s,state:e,store:c.variableStore,declared:()=>d.get(),followed:u,onDispose:e=>p.push(e)})}catch(e){throw m(),e}UK(e.compiled,c.variableStore,c,h);let g=(0,Y.reaction)(()=>[h.payload(),h.selections(),c.published(),e.registry.published()],()=>a(s),{equals:Y.compareShallow,fireImmediately:!0,onError:e=>o(`error`,`session view change threw sid=${JSON.stringify(s)}: ${String(e)}`)});return{sessionId:s,state:e,store:c.variableStore,registry:c,source:h,requested:f,facts:()=>d.get().facts,settle:e=>u.settle(e),followed:{stamped:u.stamped,failure:u.failure},lastRenderCellsBySegment:new Map,retire:g,dispose:()=>(g(),m())}}var zre=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??Le,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},m.mkdirSync(ZU(e.stateDir),{recursive:!0});let{dir:n,name:r}=Dj(QU(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)??Aq(t,this.deps.links)}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=Are(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`,Z5(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??i7(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=${F(this.accountedBytes())}/${F(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}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.placeView(i,a),a.requested(n),a;this.placeView(i,void 0);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=Rre(t,e.cwd,n,{facts:this.deps.facts,source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(a,{error:e}),e}return this.openFailures.delete(a),this.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.placeView(a,o),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}placeView(e,t){let n=this.views.get(e);this.views.delete(e),t!==void 0&&this.views.set(e,t),t!==n&&this.observers.onSessionViewMoved?.(e)}sessionView(e){return this.views.get(e)??null}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.placeView(e.sessionId,void 0),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 r7(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=${F(this.accountedBytes())}/${F(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`,kre(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`,Z5(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=Mre(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 Bre=e=>!J1(e)&&!MI(e)&&e!==`update.dismissed`&&e!==sS;var Vre=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:N1(e,Bre,(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)})}};const o7=(e,t)=>e.kind===`ok`?I(t(e.value)):e;function Hre(e){switch(e.kind){case`pending`:case`failed`:return e;case`absent`:return L;case`ok`:return e.value.pullRequest??$a(`unread`)}}const s7=(e,t)=>{let n=Object.entries(e);return n.length===Object.keys(t).length&&n.every(([e,n])=>Object.is(n,Reflect.get(t,e)))};function Ure({pullRequest:e,...t}){return t}function c7(e,t,n,r,i){let{lanes:a}=n,o=a.git,s=(e,t)=>qZ(e,t,i),c=e?.builtins,l={session:s(c?.session,a.usage),today:s(c?.today,n.today),speed:s(c?.speed,a.speed),context:s(c?.context,a.context),metrics:s(c?.metrics,a.metrics),activity:s(c?.activity,a.activity),cache:s(c?.cache,a.cache),autocompact:s(c?.autocompact,a.autoCompact),git:s(c?.git,o7(o,Ure)),pr:s(c?.pr,Hre(o)),tmux:s(c?.tmux,o7(a.tmuxSession,e=>({session:e}))),hostName:s(c?.hostName,a.hostName),hostUser:s(c?.hostUser,a.hostUser)},u=Object.fromEntries([...a.sources].map(([t,n])=>[t,s(e?.sources[t],n)])),d={builtins:l,sources:u,update:r,diagnostics:n.faults};return e!==void 0&&s7(l,e.builtins)&&s7(u,e.sources)&&(0,Y.compareStructural)({update:r,diagnostics:n.faults},{update:e.update,diagnostics:e.diagnostics})?e:{v:1,session:t,seq:e===void 0?1:e.seq+1,...d}}function Wre(e,t,n,r){if(t.kind===`failed`)return Xa(e,t.reason);try{let i=c7(e.line.facts,r,t.readings,t.update,n),a=i===e.line.facts?e.line:{at:n,facts:i};return a===e.line&&e.failure===null?e:{line:a,failure:null}}catch(t){return Xa(e,`stamping the facts document: ${String(t)}`)}}function Gre({providers:e,update:t}){let{clock:n,log:r}=e;return{follow(i,a){let o=i.sessionId,s=new Ej,c=JSON.stringify(o),l=(t,{sources:n})=>{try{let{result:{lanes:i,faults:a},acquired:o,released:l}=s.declare(()=>sZ(e,s,t,n));for(let e of a)r(`error`,`session view declaration threw sid=${c} ${e}`);return o+l>0&&r(`info`,`session view declared sid=${c} acquired=${o} released=${l} held=${s.size}`),i}catch(e){return r(`error`,`session view declaration threw sid=${c}: ${E(e)}`),iZ(R(`view declaration threw: ${String(e)}`,`read`),[...n.keys()])}},u=Y.observable.box({facts:i,lanes:l(i,a)},{deep:!1}),d=(0,Y.computed)(()=>{let{facts:t}=u.get();return{hookData:t.hookData,cwd:t.cwd,hints:t.hints,deps:{...e,lanes:()=>u.get().lanes}}}),f=(0,Y.computed)(()=>cZ(d.get())),p,m=(0,Y.reaction)(()=>{try{return{kind:`read`,readings:f.get(),update:t()}}catch(e){return{kind:`failed`,reason:`reading the owners: ${String(e)}`}}},e=>(0,Y.runInAction)(()=>{let t=p.get(),i=Wre(t,e,st(n),o);i.failure!==null&&i!==t&&r(`error`,`session facts sid=${c}: ${i.failure}`),p.set(i)}),{onError:e=>r(`error`,`session facts threw sid=${c}: ${E(e)}`)});try{let e=st(n);p=Y.observable.box({line:{at:e,facts:c7(void 0,o,f.get(),t(),e)},failure:null},{deep:!1})}catch(e){throw m(),s.close(),e}return{stamped:()=>p.get().line,failure:()=>p.get().failure,follow:(e,t)=>{let n=l(e,t);(0,Y.runInAction)(()=>u.set({facts:e,lanes:n}))},settle:e=>{let t=new Map;return{refreshed:t,landed:yZ(d.get(),e,t)}},dispose:()=>{m(),s.close()}}}}}function Kre(e,t){return t.kind===`failed`?Xa(e,t.reason):e.failure===t.facts&&t.stamped===e.stamped&&t.compose===e.compose&&t.draw===e.draw?e:{stamped:t.stamped,compose:t.compose,draw:t.draw,failure:t.facts}}function qre(e){return({sessionId:t,state:n,store:r,declared:i,followed:a,onDispose:o})=>{let s=n=>e.sessionState.get(t,n),c=r.derive(`session.effective`,`computed`,()=>MZ(n.config,s,e=>n.authoredRoots.has(e))),l=r.derive(`session.compose`,`computed`,()=>{let{facts:t}=i();return{hookData:t.hookData,hints:t.hints,home:e.providers.home}}),u=r.derive(`session.draw`,`computed`,()=>({effective:c.read(),configFacts:{...b$(n.config,n.fileHeldSettings,s),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})),d=Y.observable.box({stamped:a.stamped(),compose:l.read(),draw:u.read(),failure:a.failure()},{deep:!1});o((0,Y.reaction)(()=>{try{return{kind:`read`,stamped:a.stamped(),facts:a.failure(),compose:l.read(),draw:u.read()}}catch(e){return{kind:`failed`,reason:`reading the turn's inputs: ${String(e)}`}}},n=>(0,Y.runInAction)(()=>{let r=d.get(),i=Kre(r,n);n.kind===`failed`&&i!==r&&e.providers.log(`error`,`session turn sid=${JSON.stringify(t)}: ${i.failure}`),d.set(i)}),{onError:n=>e.providers.log(`error`,`session turn threw sid=${JSON.stringify(t)}: ${String(n)}`)}));let f=r.derive(`session.payload`,`computed`,()=>{let{stamped:e,compose:t,draw:n}=d.get();return pZ(e.facts,t,n)});return{payload:()=>f.read(),effective:()=>d.get().draw.effective,facts:()=>d.get().stamped.facts,stamped:()=>d.get().stamped,home:()=>d.get().compose.home,hints:()=>d.get().compose.hints,failure:()=>d.get().failure,selections:()=>d.get().draw.effective}}}const l7=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,u7=`#{session_id} #{client_control_mode} #{pane_id}`;function d7(e){let t=new Set;for(let n of e.split(`
500
+ `)||null}const Q5=e=>e instanceof Error?e.message:String(e);function $5(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function Pre(e){let{loaded:t,chain:n}=e;return Vv({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:$5(e.plugins),source:null,warnings:null})),base:t.base,installed:{...$5(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 Fre(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 e7(e,t,n){let r=[];try{let i=cX(t.locs,t.layers,PX,{warned:e=>r.push(...e)},{repo:t.repo,cwd:e}),a={cwd:e,chain:t,loaded:i,sources:Fre(i.config,n)};return{kind:`resolved`,...a,key:Pre(a),warnings:r}}catch(e){return e instanceof xy&&r.push(...e.warnings),{kind:`failed`,cause:e,warnings:r}}}function t7(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??PX,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new dw(t.clock),m=new jM(t.runs,p,o.globals.default_empty_value??``,t.sessionState),h;try{h=Tq(o,m,n,t.compile??wq(t.links),Lre),f.push(...h.loadWarnings);let r=m.view();f.push(...Oq(o,r,n,a7)),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 xy&&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,authoredRoots:jre(l,u),fileHeldSettings:y$(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>Cre(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 n7(e,t,n,r,i){let a={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:A(i,e.started)},o=t=>Nre([...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:Q5(r.cause),cause:r.cause}}}function Ire(e,t,n,r,i=null){let a=e7(t,n,r.storage);if(a.kind===`failed`)return n7(e,n,[],a,r.clock);let o=i?.loadKey===a.key?{kind:`kept`,state:i}:t7(a,r);return n7(e,n,a.warnings,o,r.clock)}function r7(e,t,n,r,i=null){let a=r.clock.monotonic(),o=hU(r.locations,$U(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 Ire({repos:s,advisories:[SU(r.locations,e,t),bU(o),cU(s)],started:a},t,c,r,i)}function i7(e,t,n){let r=e7(e,{layers:[],home:``,repo:t,locs:n.locations},n.storage),i=r.kind===`failed`?r:t7(r,n);if(i.kind===`failed`)throw Error(`bundled default failed to load: ${Q5(i.cause)}`,{cause:i.cause});return i.state}const Lre=new Set([`directory`]),a7=new Set([`view`]);function Rre(e,t,n,{facts:r,source:i,changed:a,log:o}){let{sessionId:s}=n,c=e.registry.view();Oq(e.config,c,t,a7);let l={sources:e.sources},u;try{u=r.follow(n,l)}catch(e){throw c.dispose(),e}let d=Y.observable.box({facts:n},{deep:!1}),f=e=>{e!==d.get().facts&&(0,Y.runInAction)(()=>{u.follow(e,l),d.set({facts:e})})},p=[],m=()=>{for(let e of p)e();return u.dispose(),c.dispose()},h;try{h=i({sessionId:s,state:e,store:c.variableStore,declared:()=>d.get(),followed:u,onDispose:e=>p.push(e)})}catch(e){throw m(),e}UK(e.compiled,c.variableStore,c,h);let g=(0,Y.reaction)(()=>[h.payload(),h.selections(),c.published(),e.registry.published()],()=>a(s),{equals:Y.compareShallow,fireImmediately:!0,onError:e=>o(`error`,`session view change threw sid=${JSON.stringify(s)}: ${String(e)}`)});return{sessionId:s,state:e,store:c.variableStore,registry:c,source:h,requested:f,facts:()=>d.get().facts,settle:e=>u.settle(e),followed:{stamped:u.stamped,failure:u.failure},lastRenderCellsBySegment:new Map,retire:g,dispose:()=>(g(),m())}}var zre=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??Le,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},m.mkdirSync(ZU(e.stateDir),{recursive:!0});let{dir:n,name:r}=Dj(QU(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)??Aq(t,this.deps.links)}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=Are(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`,Z5(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??i7(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=${F(this.accountedBytes())}/${F(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}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.placeView(i,a),a.requested(n),a;this.placeView(i,void 0);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=Rre(t,e.cwd,n,{facts:this.deps.facts,source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(a,{error:e}),e}return this.openFailures.delete(a),this.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.placeView(a,o),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}placeView(e,t){let n=this.views.get(e);this.views.delete(e),t!==void 0&&this.views.set(e,t),t!==n&&this.observers.onSessionViewMoved?.(e)}sessionView(e){return this.views.get(e)??null}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.placeView(e.sessionId,void 0),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 r7(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=${F(this.accountedBytes())}/${F(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`,kre(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`,Z5(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=Mre(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 Bre=e=>!J1(e)&&!MI(e)&&e!==`update.dismissed`&&e!==sS;var Vre=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:N1(e,Bre,(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)})}};const o7=(e,t)=>e.kind===`ok`?I(t(e.value)):e;function Hre(e){switch(e.kind){case`pending`:case`failed`:return e;case`absent`:return L;case`ok`:return e.value.pullRequest??$a(`unread`)}}const s7=(e,t)=>{let n=Object.entries(e);return n.length===Object.keys(t).length&&n.every(([e,n])=>Object.is(n,Reflect.get(t,e)))};function Ure({pullRequest:e,...t}){return t}function c7(e,t,n,r,i){let{lanes:a}=n,o=a.git,s=(e,t)=>qZ(e,t,i),c=e?.builtins,l={session:s(c?.session,a.usage),today:s(c?.today,n.today),speed:s(c?.speed,a.speed),context:s(c?.context,a.context),metrics:s(c?.metrics,a.metrics),activity:s(c?.activity,a.activity),cache:s(c?.cache,a.cache),autocompact:s(c?.autocompact,a.autoCompact),git:s(c?.git,o7(o,Ure)),pr:s(c?.pr,Hre(o)),tmux:s(c?.tmux,o7(a.tmuxSession,e=>({session:e}))),hostName:s(c?.hostName,a.hostName),hostUser:s(c?.hostUser,a.hostUser)},u=Object.fromEntries([...a.sources].map(([t,n])=>[t,s(e?.sources[t],n)])),d={builtins:l,sources:u,update:r,diagnostics:n.faults};return e!==void 0&&s7(l,e.builtins)&&s7(u,e.sources)&&(0,Y.compareStructural)({update:r,diagnostics:n.faults},{update:e.update,diagnostics:e.diagnostics})?e:{v:1,session:t,seq:e===void 0?1:e.seq+1,...d}}function Wre(e,t,n,r){if(t.kind===`failed`)return Xa(e,t.reason);try{let i=c7(e.line.facts,r,t.readings,t.update,n),a=i===e.line.facts?e.line:{at:n,facts:i};return a===e.line&&e.failure===null?e:{line:a,failure:null}}catch(t){return Xa(e,`stamping the facts document: ${String(t)}`)}}function Gre({providers:e,update:t}){let{clock:n,log:r}=e;return{follow(i,a){let o=i.sessionId,s=new Ej,c=JSON.stringify(o),l=(t,{sources:n})=>{try{let{result:{lanes:i,faults:a},acquired:o,released:l}=s.declare(()=>sZ(e,s,t,n));for(let e of a)r(`error`,`session view declaration threw sid=${c} ${e}`);return o+l>0&&r(`info`,`session view declared sid=${c} acquired=${o} released=${l} held=${s.size}`),i}catch(e){return r(`error`,`session view declaration threw sid=${c}: ${E(e)}`),iZ(R(`view declaration threw: ${String(e)}`,`read`),[...n.keys()])}},u=Y.observable.box({facts:i,lanes:l(i,a)},{deep:!1}),d=(0,Y.computed)(()=>{let{facts:t}=u.get();return{hookData:t.hookData,cwd:t.cwd,hints:t.hints,deps:{...e,lanes:()=>u.get().lanes}}}),f=(0,Y.computed)(()=>cZ(d.get())),p,m=(0,Y.reaction)(()=>{try{return{kind:`read`,readings:f.get(),update:t()}}catch(e){return{kind:`failed`,reason:`reading the owners: ${String(e)}`}}},e=>(0,Y.runInAction)(()=>{let t=p.get(),i=Wre(t,e,st(n),o);i.failure!==null&&i!==t&&r(`error`,`session facts sid=${c}: ${i.failure}`),p.set(i)}),{onError:e=>r(`error`,`session facts threw sid=${c}: ${E(e)}`)});try{let e=st(n);p=Y.observable.box({line:{at:e,facts:c7(void 0,o,f.get(),t(),e)},failure:null},{deep:!1})}catch(e){throw m(),s.close(),e}return{stamped:()=>p.get().line,failure:()=>p.get().failure,follow:(e,t)=>{let n=l(e,t);(0,Y.runInAction)(()=>u.set({facts:e,lanes:n}))},settle:e=>{let t=new Map;return{refreshed:t,landed:yZ(d.get(),e,t)}},dispose:()=>{m(),s.close()}}}}}function Kre(e,t){return t.kind===`failed`?Xa(e,t.reason):e.failure===t.facts&&t.stamped===e.stamped&&t.compose===e.compose&&t.draw===e.draw?e:{stamped:t.stamped,compose:t.compose,draw:t.draw,failure:t.facts}}function qre(e){return({sessionId:t,state:n,store:r,declared:i,followed:a,onDispose:o})=>{let s=n=>e.sessionState.get(t,n),c=r.derive(`session.effective`,`computed`,()=>MZ(n.config,s,e=>n.authoredRoots.has(e))),l=r.derive(`session.compose`,`computed`,()=>{let{facts:t}=i();return{hookData:t.hookData,hints:t.hints,home:e.providers.home}}),u=r.derive(`session.draw`,`computed`,()=>({effective:c.read(),configFacts:{...b$(n.config,n.fileHeldSettings,s),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})),d=Y.observable.box({stamped:a.stamped(),compose:l.read(),draw:u.read(),failure:a.failure()},{deep:!1});o((0,Y.reaction)(()=>{try{return{kind:`read`,stamped:a.stamped(),facts:a.failure(),compose:l.read(),draw:u.read()}}catch(e){return{kind:`failed`,reason:`reading the turn's inputs: ${String(e)}`}}},n=>(0,Y.runInAction)(()=>{let r=d.get(),i=Kre(r,n);n.kind===`failed`&&i!==r&&e.providers.log(`error`,`session turn sid=${JSON.stringify(t)}: ${i.failure}`),d.set(i)}),{onError:n=>e.providers.log(`error`,`session turn threw sid=${JSON.stringify(t)}: ${String(n)}`)}));let f=r.derive(`session.payload`,`computed`,()=>{let{stamped:e,compose:t,draw:n}=d.get();return pZ(e.facts,t,n)});return{payload:()=>f.read(),effective:()=>d.get().draw.effective,facts:()=>d.get().stamped.facts,stamped:()=>d.get().stamped,home:()=>d.get().compose.home,hints:()=>d.get().compose.hints,failure:()=>d.get().failure,selections:()=>d.get().draw.effective,state:()=>({values:e.sessionState.values(t),revision:e.sessionState.revision(t),history:d.get().draw.history,back:d.get().draw.back})}}}const l7=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,u7=`#{session_id} #{client_control_mode} #{pane_id}`;function d7(e){let t=new Set;for(let n of e.split(`
501
501
  `)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function f7(e,t){let n=new Set;for(let r of e.split(`
502
502
  `)){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 Jre(e,t){let n=new Map;for(let t of e.split(`
503
503
  `)){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(`
504
504
  `)){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 Yre=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: ${E(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:f7(t.stdout,d7(n.stdout)),status:Jre(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),!Xre(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 Xre(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 Zre(e){return`ccb`+le(`sha256`).update(e).digest(`hex`).slice(0,12)}const Qre=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function p7(e){if(e===void 0)return`terminal`;let t=U.parse(e);if(t.isDefault)return`terminal`;switch(t.type){case H.STANDARD:{let e=t.number===void 0?void 0:Qre[t.number];if(e!==void 0)return e;break}case H.EIGHT_BIT:if(t.number!==void 0)return`colour${t.number}`;break;case H.TRUECOLOR:{let e=t.fixedValue;if(e!==void 0)return e.hex;break}case H.DEFAULT:case H.WINDOWS:break}throw Error(`frames: no tmux colour for ${t.name}`)}const $re={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 eie(e){return e.replaceAll(`#`,`##`)}function tie({fg:e,bg:t,attrs:n=[]}){let r=n.map(e=>{let t=$re[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${p7(e)}`,`bg=${p7(t)}`,...r].join(`,`)}]`}function nie(e){let t={},n=e=>{let n=tie(e)+eie(e.text);if(e.link===void 0)return n;let r=Zre(e.link);return t[r]=e.link,`#[range=user|${r}]${n}#[norange]`};return{rows:e.rows.map(e=>aF(e).map(n).join(``)),links:t}}function m7(e){return tF(nie,e)}const h7=fb.tmuxStatus.rows,g7=`@cc-candybar-status-prior`,_7=`@cc-candybar-status-wrote`,v7=`@cc-candybar-binding-prior`,y7=`@cc-candybar-renderer`,b7=[`-T`,`root`,`MouseDown1Status`],x7=Array.from({length:h7},(e,t)=>t),S7=e=>`@cc-candybar-row-${e}`,rie=e=>`#[fill=terminal]#{${S7(e)}}`,C7=e=>`status-format[${e}]`;function iie(e){return e===0?`off`:e===1?`on`:String(e)}function w7(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 aie(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 T7(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function E7(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function D7(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function oie(e){return e.map(e=>e.map(D7).join(` `)).join(` ; `)}const O7=`ccb:separator`;function k7(e){return E7(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,O7],e]))}function A7(e,t){let n=e.split(`${O7}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const j7=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],M7=e=>[`show-options`,`-g`,`-q`,`-v`,e],N7=e=>[[`show-options`,`-t`,e],j7(e,`status`),...x7.map(t=>j7(e,C7(t)))];function P7(e){let[t=``,n=``,...r]=e,i=t.split(`
505
505
  `).map(e=>e.split(` `)[0]??``),a={};for(let e of x7)i.includes(C7(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 F7(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,C7(Number(t)),T7(n)])]}const sie=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...N7(e),...x7.map(e=>M7(C7(e))),j7(e,g7),j7(e,_7)];function I7(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:w7(t)}catch(e){return{kind:`theirs`,why:`${g7} 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`}}const L7=(e,t)=>[`set-option`,`-t`,e,y7,t];function cie(e,t,n,r){let[i=``,...a]=t,o=P7(a.slice(0,2+h7)),s=a.slice(2+h7,2+2*h7),[c=``,l=``]=a.slice(2+2*h7);if(c!==``){let t=I7(c,l,n);return t.kind===`theirs`?t:{...t,commands:[L7(e,r)]}}let u=w7(i),d={};for(let e=0;e<u;e++){let t=o.formats===null?s[e]:o.formats[e];t!==void 0&&t!==``&&(d[e]=t)}let f={...d,...Object.fromEntries(Array.from({length:h7-u},(e,t)=>[u+t,rie(t)]))},p={owner:n,base:u,status:o.status,formats:o.formats,wrote:f};return{kind:`lay-out`,prior:p,commands:[[`set-option`,`-t`,e,g7,JSON.stringify(p)],L7(e,r),...F7(e,f)]}}const R7=e=>[...N7(e),j7(e,_7)];function z7(e,t,n){let r=P7(n.slice(0,2+h7)),i=n[2+h7]??``,a=[],o=[];if(aie(r.formats,t.wrote))a.push(...F7(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,C7(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,T7(t.status)]):o.push(`status`)),a.push(...x7.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,S7(t)]),[`set-option`,`-q`,`-u`,`-t`,e,g7],[`set-option`,`-q`,`-u`,`-t`,e,_7],[`set-option`,`-q`,`-u`,`-t`,e,y7]),{commands:a,kept:o}}const lie=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,B7=[[`list-keys`,`-T`,`root`]];function V7(e){let t=lie.exec(e);return t===null?null:{line:t[0],command:t[1]}}const uie=(e,t)=>KS(e,`tmux-status-click`,`${HS([t])}/#{s/%//:pane_id}/#{q:mouse_status_range}`),H7=e=>e?.command.includes(`/tmux-status-click/`)??!1;function U7(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,v7]};return H7(V7(t))?{steps:[e===null?{command:[`unbind-key`,...b7]}:{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 die=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=m7(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,R7(r));if(a===null)continue;let o=z7(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,B7);if(n===null)continue;this.writeBindingRestoreSync(e,t,r.prior,n[0]??``)}}}linkAt(e){let t=fie(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,h7-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#{${g7}}\t#{${_7}}`]);if(n.kind===`ok`){let r=[];for(let i of n.stdout.split(`
506
- `)){let[n,a,o=``]=i.split(` `);if(n===void 0||a===void 0||a===``)continue;let s=I7(a,o,this.deps.owner);s.kind===`ours`?(t.layouts.set(n,{prior:s.prior,rows:[],status:s.status}),r.push(L7(n,this.deps.name))):this.leave(e,t,n,s.why)}await this.write(e,r)}let r=(await this.ask(e,[M7(`@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)} ${v7} 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,sie(n));if(r===null||this.closed)return null;let i=cie(n,r,this.deps.owner,this.deps.name);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),await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} renderer=${this.deps.name} 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,S7(r),e])}),i!==n.status){let e=iie(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,_7,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,oie(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,R7(n));if(i===null)return;let a=z7(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,B7);if(r===null||this.closed)return;let i=V7(r[0]??``);if(n.kind===`none`&&H7(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`&&H7(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...b7,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${D7(`${this.deps.handler} ${uie(this.deps.name,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,B7);if(r===null)return;let i=U7(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=U7(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,k7(t));return n.kind===`ok`?A7(n.stdout,t.length):null}askSync(e,t,n){let r=this.counted(t,e(t,k7(n)));return r.kind===`ok`?A7(r.stdout,n.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,E7(t),n)).kind===`ok`)}writeSync(e,t,n,r){n.length!==0&&(this.writes++,this.counted(t,e(t,E7(n),r)))}};function fie(e){try{return US(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),W7=e=>({arity:e,keep:!1}),pie={"--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":W7(`none`),"--background":W7(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":W7(`optional`),"-c":W7(`none`),"--continue":W7(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":W7(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":W7(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":W7(`none`),"--forward-subagent-text":$(`none`),"--from-pr":W7(`optional`),"-h":W7(`none`),"--help":W7(`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":W7(`none`),"--print":W7(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":W7(`optional`),"--resume":W7(`optional`),"--safe-mode":$(`none`),"--session-id":W7(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":W7(`optional`),"--tmux":W7(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":W7(`none`),"--version":W7(`none`),"-w":W7(`optional`),"--worktree":W7(`optional`)},mie={resume:`--resume`,fresh:`--session-id`};function hie(e){return[mie[e.kind],e.sessionId]}const G7=e=>e.startsWith(`-`)&&e!==`-`;function K7(e,t){let n=q7(t);return n===null?{dir:e??t,args:[]}:e!==null&&gie(e,n.top)?{dir:e,args:[]}:{dir:e===null||q7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const gie=(e,t)=>e===t||e.startsWith(t+s.sep);function _ie(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!G7(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=pie[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=>!G7(e)):o.arity===`variadic`?vie(n.slice(r),e=>!G7(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 q7(e){let t=e.split(s.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(s.sep),repo:t.slice(0,n-1).join(s.sep)||s.sep}}function vie(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const J7=`candybar-band@cc-candybar`,yie=s.join(`bin`,`cc-candybar-native`),bie=LI(`/reload-plugins`),Y7=e=>({kind:`done`,said:e});function X7(e){let t=IQ(e.hints.tmux);if(t.kind===`refused`)throw new Z(t.reason);return t.hint}const xie={band:{on:async(e,t,n)=>{let r=xn(t.bundle);if(r===null)throw new Z(`${fb.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=s.join(r,yie);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 ${J7} from ${r}`,finished:Sie(e,r,n)}},off:async()=>Y7(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:async(e,t,n)=>{let r=X7(e),i=sn(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new Z(`${fb.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:Tie(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:async()=>Y7(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>{let r=X7(e),i=await n.barPanes(r);return i.length>0?Y7(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):Y7(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],Fn(t.home))} under ${r.pane}`)},off:async(e,t,n)=>{let r=IQ(e.hints.tmux);if(r.kind===`refused`)return Y7(`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 Y7(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:async e=>Y7(`the daemon draws ${X7(e).pane}'s bar in its status line`),off:async()=>Y7(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function Sie(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`,J7],r);let i=IQ(e.hints.tmux),a=i.kind===`refused`?i:await LQ(n.claudeInput,i.hint,bie);if(a.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${a.reason} — or type /reload-plugins yourself`);return`installed ${J7} from ${t} and typed /reload-plugins into ${a.pane}`}const Cie=new Set([bo,PP]);function wie(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function Tie(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,cn(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}) — ${fb.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=Aie(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${fb.statusline.label} off and on again`);let s=Eie(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=_ie(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=wie(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])=>Cie.has(e)),m=(e,t)=>dn(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...hie(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=Die(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(K7(null,i.cwd),_))}let y=m(K7(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}\`, ${Oie[g.kind](e.sessionId)}, and its statusline follows lane B`}function Eie(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 Die(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const Oie={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},kie={"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 Aie(e){let t=jQ(e);return t.kind===`ready`?PQ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:MQ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:kie[t.kind]}var jie=class{owed=new Map;setups=new Q8;constructor(e){this.deps=e}clicked(e,t,n,r){let i=pb.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}`),Ps(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=await xie[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 Mie=[`request`,`feed`],Z7=new WeakMap;let Nie=0;const Q7=e=>{let t=Z7.get(e);if(t!==void 0)return t;let n=Nie++;return Z7.set(e,n),n};var Pie=class{records=new Map;constructor(e=512){this.maxRecords=e}of(e,t){return this.records.get($7(e,t))?.warnings??[]}ofSession(e,t,n){let r=Q7(n.config),i=[];for(let n of Mie){let a=this.records.get($7(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=$7(e,t);this.records.delete(a),this.records.set(a,{generation:Q7(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 $7=(e,t)=>`${t}\0${e}`;var Fie=class{queue=new Q8;sessions=new Q8;gathers=new Q8;effects=new Q8;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 XQ(e);let a=this.deps.monotonic();t(Qe(i,a)),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(A(this.deps,c)),this.refuseClosed(e),i())throw new XQ(e);let t=this.deps.monotonic(),l=await o();a(A(this.deps,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--}}performing(e,t){return this.effects.run(e??`clickless`,t)}getStats(){let{holder:e,queued:t}=this;return{holder:e?.verb??null,heldMs:e===null?0:A(this.deps,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 YQ(e)}commit(e){return this.inFlight===e?(this.inFlight=null,e.commit(),!0):!1}},Iie=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)?Eb(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 Lie(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,home:o,gates:s,host:c}=e,l=Jn(o),u=Xn(c,o),d=()=>it(new Date(i.now())),f=new AbortController,p=!1,m=(t,n)=>e.daemonLog.log(t,p?`after close: ${n}`:n),h=new F4(i),g=e.launcher({inherited:c.env,stats:h.launchStats,signal:f.signal,now:d,observeWarnings:e=>{e.kind===`launch-pipes`?m(`warn`,e.text):m(e.fault===null?`info`:`warn`,e.fault===null?`launch lifeline running again`:`launch lifeline ${e.fault}; the next launch starts another`),he.wakeWhere(`data`,()=>!0)}}),_=e.probe(g),v=e.storage(m),y=new F1(v.session),b=new Fie({log:m,monotonic:()=>i.monotonic()}),x=e.sessionWrites(y,b),S=new Q1(x,m,v.history),C=hi({...e.limits({startedAtMs:h.startedAt.getTime(),exit:a,launcher:g,log:m}),limitBytes:n}),ee=new Z4,w=new tne,te=e.doctorStores,ne=new Ij({clock:i,counters:h,logger:m}),T=new rM(m),re=new hc({watchers:ne,logger:m,clock:i}),E=new bM({launcher:g,clock:i,logger:m,ledger:T,watchers:ne,fileEvents:re}),D=xre({launcher:g,host:c,pricing:e.pricing({cacheRoot:kn(o),closing:f.signal,log:m}),watchers:ne,fileEvents:re,clock:i,logger:m,ledger:T}),{gitProvider:ie,usageStore:O,tmuxService:ae,hostService:oe,managedStorage:se}=D,ce=new Vre,le=new Ote,ue=new Iie({clock:i,now:d,close:async(e,t)=>{await M6({kind:`menu-idle`,session:e,idle:t},Ee)},failed:(e,t)=>z6(m,`menu-idle`,`session=${e}`,t)}),de={to:o.name,signer:e.linkSigner},fe=new Us({supersede:(e,t)=>se.supersede(e,t),launch:g.launch,state:y,log:m,now:d,clock:i}),pe=new jie({edge:e.laneEdge(g,e=>he.following(e),f.signal,_),host:{bundle:t.path,node:t.node,home:o,preload:Yo(t.path,c)},state:y,log:m,now:d,defer:e=>void i.defer(e)}),me=new die({edge:{run:(e,t,n)=>Ms(g,{socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>he.subscribe(e,t),sessionInPane:(e,t)=>he.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[...Object.entries(Fn(o)).map(([e,t])=>`${e}=${rn(t)}`),...[...t.node,t.path].map(rn),`url-handle`].join(` `),owner:l.socket,name:o.name,log:m}),he=new zZ({render:(e,t,n)=>pQ(Ee,e,t,n),watch:(e,t)=>(0,Y.reaction)(()=>x.revision(e),t),lanes:e=>hQ(Ee,e),pin:e=>{let t=be.pin(e);return()=>{be.stopDrawing(e,`feed`),t()}},shown:e=>ge.shown(e.hints.tmux),watching:()=>ge.follow(),refreshes:()=>T.totals(),periods:NZ,clock:i,instant:d,log:m}),ge=new Yre({clock:i,listPanes:e=>Ms(g,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,l7]),listClients:e=>Ms(g,{socket:e},`frames.visibility`,[`list-clients`,`-F`,u7]),sockets:()=>new Set(he.watched().flatMap(({req:e})=>_e(e))),onAnswer:(e,t)=>me.answered(e,t),onChange:e=>he.wakeWhere(`visibility`,t=>_e(t).some(t=>e.has(t))),intervalMs:1e3,log:m});function _e({hints:{tmux:e}}){return e==null?[]:[e.socket]}let ve=new Pie,ye=c5(),{cache:be,recorder:xe}=aQ(e=>new zre({clock:i,runs:E,stateDir:l.state,locations:u,sessionState:x,watchers:ne,log:m,storage:se,links:de,gates:s,facts:Gre({providers:D,update:()=>ye.get()}),source:qre({providers:D,sessionState:x,history:e=>S.depth(e),navigation:(e,t)=>ce.depth(e,x,s.state.gateFor(t))})},{budgetBytes:()=>wre(n),observers:{onReload:(e,t,n,r)=>{m(`info`,Ore(e,n,r));for(let e of t)he.wake(e,`reload`)},onViewChanged:e=>he.wake(e,`data`),...e}}),m);re.subscribe(e=>{switch(e.kind){case`period`:ne.judge();return;case`caught-up`:be.reloadEvery({kind:`events-resumed`,since:e.since}),he.wakeWhere(`data`,()=>!0);return;case`moved`:he.wakeWhere(`data`,()=>!0);return}});let Se=60*1e3,Ce=d5({clock:i,targets:t.targets,intervalMs:Se,stat:e.stat,held:()=>we.running(),exit:()=>a(0),log:m}),we=s5({fact:ye,clock:i,launcher:g,probe:_,entryUrl:t.entryUrl,digest:t.digest,actsDir:F8(l.state,t.path),intervalMs:Se,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,gates:s,onApplied:()=>Ce.checkNow(),log:m}),Te={gates:s,sessionState:x,stateDir:l.state,storedRoot:l.storedRoot,locations:u,journalTurns:b,clickLanded:e=>ue.clicked(e,d()),log:m,launcher:g,now:d,applyUpdate:()=>we.act(),doctor:e.doctorEdge(g,e=>{let t=[e.projectDir,e.cwd,e.target.path];be.reload(...t,{kind:`doctor`});let n=be.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}},c),doctorStores:te,probes:ee,clients:w,bundle:t.path,serving:()=>C.serving(),claudeInput:e.claudeInput(g),history:S,navigation:ce,configFor:e=>be.getOrCreate(e.projectDir,e.cwd,e.target.path).state.config,reloadConfig:e=>be.reload(e.projectDir,e.cwd,e.target.path,{kind:`write`}),sourcesFor:e=>be.getOrCreate(e.projectDir,e.cwd,e.target.path).state.sources,links:de,runs:fe,lanes:{of:(e,t)=>gQ(Ee,e,t),clicked:(e,t,n)=>wQ(Ee,e,t,n)},diagnosticCopy:(e,t,n)=>be.drawnCopy(e,t,n)},Ee={home:c.home,storedRoot:l.storedRoot,tmp:c.tmp,launcher:g,log:m,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:te,stats:h,handlerProbes:ee,renderSightings:w,watcherRegistry:ne,refreshLedger:T,fileEvents:re,payloadProviders:D,sessionState:x,sessionGauges:y,rendererName:o.name,draw:(e,t,n,r)=>TQ(Ee,e,t,n,r),effectSessions:le,menuIdle:ue,journalTurns:b,links:de,runs:fe,sourceRuns:E,laneSetups:pe,tmuxStatusLines:me,frameFeeds:he,renderWarnings:ve,renderCache:be,recorder:xe,updateWatch:we,limits:C,verbCtx:Te};return{stats:h,launcher:g,log:m,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(f.signal.throwIfAborted(),g8(Ee,e,t,n,r)),reply:async(e,t,n,r)=>(f.signal.throwIfAborted(),_8(Ee,e,t,n,r)),subscribe:(e,t)=>(f.signal.throwIfAborted(),he.subscribe(e,t)),reloadConfig:e=>{f.signal.throwIfAborted(),Te.reloadConfig(e)},arm(){f.signal.throwIfAborted(),re.start(l.watchProbe),Ce.arm(),we.arm(),C.arm()},close(e){let t=[[`journalTurns close`,()=>b.close()],[`tmuxStatusLines restore`,()=>me.restoreAll(e)],[`launches abort`,()=>f.abort(Error(`the daemon closed`))],[`frameFeeds close`,()=>he.close()],[`menuIdle dispose`,()=>ue.dispose()],[`updateWatch close`,()=>we.close()],[`binaryWatch close`,()=>Ce.close()],[`limits disarm`,()=>C.disarm()],[`recorder close`,()=>xe.close()],[`renderCache close`,()=>be.close()],[`gitService close`,()=>ie.close()],[`usageStore close`,()=>O.close()],[`tmuxService close`,()=>ae.close()],[`hostService close`,()=>oe.close()],[`runs close`,()=>fe.close()],[`sourceRuns close`,()=>E.close()],[`managedStorage close`,()=>se.close()],[`fileEvents close`,()=>re.close()],[`watcherRegistry close`,()=>ne.closeAll()],[`sessionState close`,()=>y.close()]];for(let[e,n]of t)try{n()}catch(t){m(`warn`,`${e} failed: ${t.message}`)}return p=!0,g.settled()}}}function Rie(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 zie=class{clearTimer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t,n=500,r=Le){this.filePath=e,this.clock=t,this.debounceMs=n,this.logger=r,this.writingPath=`${e}.writing`}load(){let e;try{e=m.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 Rie(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=A(this.clock,n);try{await m.promises.mkdir(s.dirname(this.filePath),{recursive:!0});let o=await m.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}let c=!1;if(t===this.generation)try{await m.promises.rename(i,this.filePath),c=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){c||await m.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${c} took=${A(this.clock,n)}ms held=${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{m.mkdirSync(s.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);m.writeFileSync(n,r,{mode:384}),m.chmodSync(n,384),m.rmSync(this.writingPath,{force:!0}),m.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,A(this.clock,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=${A(this.clock,n)}ms held=${r}ms`)}};function Bie(e,t,n){return{session:new zie(e.sessionState,n,500,t),history:b0(e.settingsHistory,e.storedRoot,t)}}function e9(e,t,n){for(let r of(t??``).split(s.delimiter)){if(!s.isAbsolute(r))continue;let t=s.join(r,e);if(n(t))return t}return null}function t9(e,t){try{return m.accessSync(e,t),m.statSync(e).isFile()}catch{return!1}}function Vie(e){try{return m.realpathSync(e)}catch{return s.resolve(e)}}function Hie(e,t,n){let r=e9(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const n9=2e3;async function r9(e,t,n,r){let i=await Ms(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function i9(e,t){if(t.ok)return t.stdout;let n=mt(t,t.stdout);throw Error(`${e} failed (${j(t)}${n===``?``:`: ${n}`})`)}function Uie(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 Wie=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function Gie(e,t){return e.split(`
506
+ `)){let[n,a,o=``]=i.split(` `);if(n===void 0||a===void 0||a===``)continue;let s=I7(a,o,this.deps.owner);s.kind===`ours`?(t.layouts.set(n,{prior:s.prior,rows:[],status:s.status}),r.push(L7(n,this.deps.name))):this.leave(e,t,n,s.why)}await this.write(e,r)}let r=(await this.ask(e,[M7(`@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)} ${v7} 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,sie(n));if(r===null||this.closed)return null;let i=cie(n,r,this.deps.owner,this.deps.name);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),await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} renderer=${this.deps.name} 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,S7(r),e])}),i!==n.status){let e=iie(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,_7,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,oie(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,R7(n));if(i===null)return;let a=z7(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,B7);if(r===null||this.closed)return;let i=V7(r[0]??``);if(n.kind===`none`&&H7(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`&&H7(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...b7,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${D7(`${this.deps.handler} ${uie(this.deps.name,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,B7);if(r===null)return;let i=U7(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=U7(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,k7(t));return n.kind===`ok`?A7(n.stdout,t.length):null}askSync(e,t,n){let r=this.counted(t,e(t,k7(n)));return r.kind===`ok`?A7(r.stdout,n.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,E7(t),n)).kind===`ok`)}writeSync(e,t,n,r){n.length!==0&&(this.writes++,this.counted(t,e(t,E7(n),r)))}};function fie(e){try{return US(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),W7=e=>({arity:e,keep:!1}),pie={"--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":W7(`none`),"--background":W7(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":W7(`optional`),"-c":W7(`none`),"--continue":W7(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":W7(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":W7(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":W7(`none`),"--forward-subagent-text":$(`none`),"--from-pr":W7(`optional`),"-h":W7(`none`),"--help":W7(`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":W7(`none`),"--print":W7(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":W7(`optional`),"--resume":W7(`optional`),"--safe-mode":$(`none`),"--session-id":W7(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":W7(`optional`),"--tmux":W7(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":W7(`none`),"--version":W7(`none`),"-w":W7(`optional`),"--worktree":W7(`optional`)},mie={resume:`--resume`,fresh:`--session-id`};function hie(e){return[mie[e.kind],e.sessionId]}const G7=e=>e.startsWith(`-`)&&e!==`-`;function K7(e,t){let n=q7(t);return n===null?{dir:e??t,args:[]}:e!==null&&gie(e,n.top)?{dir:e,args:[]}:{dir:e===null||q7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const gie=(e,t)=>e===t||e.startsWith(t+s.sep);function _ie(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!G7(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=pie[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=>!G7(e)):o.arity===`variadic`?vie(n.slice(r),e=>!G7(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 q7(e){let t=e.split(s.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(s.sep),repo:t.slice(0,n-1).join(s.sep)||s.sep}}function vie(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const J7=`candybar-band@cc-candybar`,yie=s.join(`bin`,`cc-candybar-native`),bie=LI(`/reload-plugins`),Y7=e=>({kind:`done`,said:e});function X7(e){let t=IQ(e.hints.tmux);if(t.kind===`refused`)throw new Z(t.reason);return t.hint}const xie={band:{on:async(e,t,n)=>{let r=xn(t.bundle);if(r===null)throw new Z(`${fb.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=s.join(r,yie);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 ${J7} from ${r}`,finished:Sie(e,r,n)}},off:async()=>Y7(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:async(e,t,n)=>{let r=X7(e),i=sn(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new Z(`${fb.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:Tie(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:async()=>Y7(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>{let r=X7(e),i=await n.barPanes(r);return i.length>0?Y7(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):Y7(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],Fn(t.home))} under ${r.pane}`)},off:async(e,t,n)=>{let r=IQ(e.hints.tmux);if(r.kind===`refused`)return Y7(`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 Y7(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:async e=>Y7(`the daemon draws ${X7(e).pane}'s bar in its status line`),off:async()=>Y7(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function Sie(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`,J7],r);let i=IQ(e.hints.tmux),a=i.kind===`refused`?i:await LQ(n.claudeInput,i.hint,bie);if(a.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${a.reason} — or type /reload-plugins yourself`);return`installed ${J7} from ${t} and typed /reload-plugins into ${a.pane}`}const Cie=new Set([bo,PP]);function wie(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function Tie(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,cn(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}) — ${fb.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=Aie(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${fb.statusline.label} off and on again`);let s=Eie(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=_ie(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=wie(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])=>Cie.has(e)),m=(e,t)=>dn(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...hie(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=Die(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(K7(null,i.cwd),_))}let y=m(K7(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}\`, ${Oie[g.kind](e.sessionId)}, and its statusline follows lane B`}function Eie(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 Die(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const Oie={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},kie={"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 Aie(e){let t=jQ(e);return t.kind===`ready`?PQ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:MQ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:kie[t.kind]}var jie=class{owed=new Map;setups=new Q8;constructor(e){this.deps=e}clicked(e,t,n,r){let i=pb.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}`),Ps(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=await xie[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 Mie=[`request`,`feed`],Z7=new WeakMap;let Nie=0;const Q7=e=>{let t=Z7.get(e);if(t!==void 0)return t;let n=Nie++;return Z7.set(e,n),n};var Pie=class{records=new Map;constructor(e=512){this.maxRecords=e}of(e,t){return this.records.get($7(e,t))?.warnings??[]}ofSession(e,t,n){let r=Q7(n.config),i=[];for(let n of Mie){let a=this.records.get($7(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=$7(e,t);this.records.delete(a),this.records.set(a,{generation:Q7(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 $7=(e,t)=>`${t}\0${e}`;var Fie=class{queue=new Q8;sessions=new Q8;gathers=new Q8;effects=new Q8;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 XQ(e);let a=this.deps.monotonic();t(Qe(i,a)),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(A(this.deps,c)),this.refuseClosed(e),i())throw new XQ(e);let t=this.deps.monotonic(),l=await o();a(A(this.deps,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--}}performing(e,t){return this.effects.run(e??`clickless`,t)}getStats(){let{holder:e,queued:t}=this;return{holder:e?.verb??null,heldMs:e===null?0:A(this.deps,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 YQ(e)}commit(e){return this.inFlight===e?(this.inFlight=null,e.commit(),!0):!1}},Iie=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}drawn(e,t,n,r){let i=this.since(e,t),a=r(i);return this.observe(e,t,a.frame.rows.some(e=>e.kind===`menu`),n),{...a,idleSince:i}}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)?Eb(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 Lie(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,home:o,gates:s,host:c}=e,l=Jn(o),u=Xn(c,o),d=()=>it(new Date(i.now())),f=new AbortController,p=!1,m=(t,n)=>e.daemonLog.log(t,p?`after close: ${n}`:n),h=new F4(i),g=e.launcher({inherited:c.env,stats:h.launchStats,signal:f.signal,now:d,observeWarnings:e=>{e.kind===`launch-pipes`?m(`warn`,e.text):m(e.fault===null?`info`:`warn`,e.fault===null?`launch lifeline running again`:`launch lifeline ${e.fault}; the next launch starts another`),he.wakeWhere(`data`,()=>!0)}}),_=e.probe(g),v=e.storage(m),y=new F1(v.session),b=new Fie({log:m,monotonic:()=>i.monotonic()}),x=e.sessionWrites(y,b),S=new Q1(x,m,v.history),C=hi({...e.limits({startedAtMs:h.startedAt.getTime(),exit:a,launcher:g,log:m}),limitBytes:n}),ee=new Z4,w=new tne,te=e.doctorStores,ne=new Ij({clock:i,counters:h,logger:m}),T=new rM(m),re=new hc({watchers:ne,logger:m,clock:i}),E=new bM({launcher:g,clock:i,logger:m,ledger:T,watchers:ne,fileEvents:re}),D=xre({launcher:g,host:c,pricing:e.pricing({cacheRoot:kn(o),closing:f.signal,log:m}),watchers:ne,fileEvents:re,clock:i,logger:m,ledger:T}),{gitProvider:ie,usageStore:O,tmuxService:ae,hostService:oe,managedStorage:se}=D,ce=new Vre,le=new Ote,ue=new Iie({clock:i,now:d,close:async(e,t)=>{await M6({kind:`menu-idle`,session:e,idle:t},Ee)},failed:(e,t)=>z6(m,`menu-idle`,`session=${e}`,t)}),de={to:o.name,signer:e.linkSigner},fe=new Us({supersede:(e,t)=>se.supersede(e,t),launch:g.launch,state:y,log:m,now:d,clock:i}),pe=new jie({edge:e.laneEdge(g,e=>he.following(e),f.signal,_),host:{bundle:t.path,node:t.node,home:o,preload:Yo(t.path,c)},state:y,log:m,now:d,defer:e=>void i.defer(e)}),me=new die({edge:{run:(e,t,n)=>Ms(g,{socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>he.subscribe(e,t),sessionInPane:(e,t)=>he.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[...Object.entries(Fn(o)).map(([e,t])=>`${e}=${rn(t)}`),...[...t.node,t.path].map(rn),`url-handle`].join(` `),owner:l.socket,name:o.name,log:m}),he=new zZ({render:(e,t,n)=>pQ(Ee,e,t,n),watch:(e,t)=>(0,Y.reaction)(()=>x.revision(e),t),lanes:e=>hQ(Ee,e),pin:e=>{let t=be.pin(e);return()=>{be.stopDrawing(e,`feed`),t()}},shown:e=>ge.shown(e.hints.tmux),watching:()=>ge.follow(),refreshes:()=>T.totals(),periods:NZ,clock:i,instant:d,log:m}),ge=new Yre({clock:i,listPanes:e=>Ms(g,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,l7]),listClients:e=>Ms(g,{socket:e},`frames.visibility`,[`list-clients`,`-F`,u7]),sockets:()=>new Set(he.watched().flatMap(({req:e})=>_e(e))),onAnswer:(e,t)=>me.answered(e,t),onChange:e=>he.wakeWhere(`visibility`,t=>_e(t).some(t=>e.has(t))),intervalMs:1e3,log:m});function _e({hints:{tmux:e}}){return e==null?[]:[e.socket]}let ve=new Pie,ye=c5(),{cache:be,recorder:xe}=aQ(e=>new zre({clock:i,runs:E,stateDir:l.state,locations:u,sessionState:x,watchers:ne,log:m,storage:se,links:de,gates:s,facts:Gre({providers:D,update:()=>ye.get()}),source:qre({providers:D,sessionState:x,history:e=>S.depth(e),navigation:(e,t)=>ce.depth(e,x,s.state.gateFor(t))})},{budgetBytes:()=>wre(n),observers:{onReload:(e,t,n,r)=>{m(`info`,Ore(e,n,r));for(let e of t)he.wake(e,`reload`)},onViewChanged:e=>he.wake(e,`data`),...e}}),m);re.subscribe(e=>{switch(e.kind){case`period`:ne.judge();return;case`caught-up`:be.reloadEvery({kind:`events-resumed`,since:e.since}),he.wakeWhere(`data`,()=>!0);return;case`moved`:he.wakeWhere(`data`,()=>!0);return}});let Se=60*1e3,Ce=d5({clock:i,targets:t.targets,intervalMs:Se,stat:e.stat,held:()=>we.running(),exit:()=>a(0),log:m}),we=s5({fact:ye,clock:i,launcher:g,probe:_,entryUrl:t.entryUrl,digest:t.digest,actsDir:F8(l.state,t.path),intervalMs:Se,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:e.fetch,gates:s,onApplied:()=>Ce.checkNow(),log:m}),Te={gates:s,sessionState:x,stateDir:l.state,storedRoot:l.storedRoot,locations:u,journalTurns:b,clickLanded:e=>ue.clicked(e,d()),log:m,launcher:g,now:d,applyUpdate:()=>we.act(),doctor:e.doctorEdge(g,e=>{let t=[e.projectDir,e.cwd,e.target.path];be.reload(...t,{kind:`doctor`});let n=be.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}},c),doctorStores:te,probes:ee,clients:w,bundle:t.path,serving:()=>C.serving(),claudeInput:e.claudeInput(g),history:S,navigation:ce,configFor:e=>be.getOrCreate(e.projectDir,e.cwd,e.target.path).state.config,reloadConfig:e=>be.reload(e.projectDir,e.cwd,e.target.path,{kind:`write`}),sourcesFor:e=>be.getOrCreate(e.projectDir,e.cwd,e.target.path).state.sources,links:de,runs:fe,lanes:{of:(e,t)=>gQ(Ee,e,t),clicked:(e,t,n)=>wQ(Ee,e,t,n)},diagnosticCopy:(e,t,n)=>be.drawnCopy(e,t,n)},Ee={home:c.home,storedRoot:l.storedRoot,tmp:c.tmp,launcher:g,log:m,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:te,stats:h,handlerProbes:ee,renderSightings:w,watcherRegistry:ne,refreshLedger:T,fileEvents:re,payloadProviders:D,sessionState:x,sessionGauges:y,rendererName:o.name,draw:(e,t,n,r)=>TQ(Ee,e,t,n,r),effectSessions:le,menuIdle:ue,journalTurns:b,links:de,runs:fe,sourceRuns:E,laneSetups:pe,tmuxStatusLines:me,frameFeeds:he,renderWarnings:ve,renderCache:be,recorder:xe,updateWatch:we,limits:C,verbCtx:Te};return{stats:h,launcher:g,log:m,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(f.signal.throwIfAborted(),g8(Ee,e,t,n,r)),reply:async(e,t,n,r)=>(f.signal.throwIfAborted(),_8(Ee,e,t,n,r)),subscribe:(e,t)=>(f.signal.throwIfAborted(),he.subscribe(e,t)),reloadConfig:e=>{f.signal.throwIfAborted(),Te.reloadConfig(e)},arm(){f.signal.throwIfAborted(),re.start(l.watchProbe),Ce.arm(),we.arm(),C.arm()},close(e){let t=[[`journalTurns close`,()=>b.close()],[`tmuxStatusLines restore`,()=>me.restoreAll(e)],[`launches abort`,()=>f.abort(Error(`the daemon closed`))],[`frameFeeds close`,()=>he.close()],[`menuIdle dispose`,()=>ue.dispose()],[`updateWatch close`,()=>we.close()],[`binaryWatch close`,()=>Ce.close()],[`limits disarm`,()=>C.disarm()],[`recorder close`,()=>xe.close()],[`renderCache close`,()=>be.close()],[`gitService close`,()=>ie.close()],[`usageStore close`,()=>O.close()],[`tmuxService close`,()=>ae.close()],[`hostService close`,()=>oe.close()],[`runs close`,()=>fe.close()],[`sourceRuns close`,()=>E.close()],[`managedStorage close`,()=>se.close()],[`fileEvents close`,()=>re.close()],[`watcherRegistry close`,()=>ne.closeAll()],[`sessionState close`,()=>y.close()]];for(let[e,n]of t)try{n()}catch(t){m(`warn`,`${e} failed: ${t.message}`)}return p=!0,g.settled()}}}function Rie(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 zie=class{clearTimer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t,n=500,r=Le){this.filePath=e,this.clock=t,this.debounceMs=n,this.logger=r,this.writingPath=`${e}.writing`}load(){let e;try{e=m.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 Rie(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=A(this.clock,n);try{await m.promises.mkdir(s.dirname(this.filePath),{recursive:!0});let o=await m.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}let c=!1;if(t===this.generation)try{await m.promises.rename(i,this.filePath),c=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){c||await m.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${c} took=${A(this.clock,n)}ms held=${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{m.mkdirSync(s.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);m.writeFileSync(n,r,{mode:384}),m.chmodSync(n,384),m.rmSync(this.writingPath,{force:!0}),m.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,A(this.clock,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=${A(this.clock,n)}ms held=${r}ms`)}};function Bie(e,t,n){return{session:new zie(e.sessionState,n,500,t),history:b0(e.settingsHistory,e.storedRoot,t)}}function e9(e,t,n){for(let r of(t??``).split(s.delimiter)){if(!s.isAbsolute(r))continue;let t=s.join(r,e);if(n(t))return t}return null}function t9(e,t){try{return m.accessSync(e,t),m.statSync(e).isFile()}catch{return!1}}function Vie(e){try{return m.realpathSync(e)}catch{return s.resolve(e)}}function Hie(e,t,n){let r=e9(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const n9=2e3;async function r9(e,t,n,r){let i=await Ms(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function i9(e,t){if(t.ok)return t.stdout;let n=mt(t,t.stdout);throw Error(`${e} failed (${j(t)}${n===``?``:`: ${n}`})`)}function Uie(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 Wie=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function Gie(e,t){return e.split(`
507
507
  `).flatMap(e=>{let[n,...r]=e.trim().split(` `);return Wie.exec(r.join(` `))?.[1]===t?[n]:[]})}const Kie=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function qie(e,t,n){for(let r of I0(F0(e),t)){if(r.command.split(` `).some(e=>Kie.test(e)))return!0;if(r.pid===n)return!1}return!1}const Jie=[`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(`
508
508
  `);async function Yie(e,t){if(process.platform===`linux`)return{executable:await m.promises.readlink(`/proc/${t}/exe`),argv:(await m.promises.readFile(`/proc/${t}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await m.promises.readFile(`/proc/${t}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let n=i9(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,Jie,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function a9(e,t,n){return i9(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function o9(e,t){let n=await Ms(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 a9(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function Xie(e,t){let{panePid:n,cwd:r,foreground:i}=await o9(e,t),a=await a9(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await Yie(e,i),s=F0(a).get(i)?.ppid;if(s===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);return{pid:i,executable:await m.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:s,fromShell:i!==n,attached:qie(a,i,n)}}function Zie(e,t,n,r,i){let a=e=>et(r,e,n);return{claudeInput:HQ(e),barPanes:async t=>Gie(await r9(e,t,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_start_command}`]),t.pane),openBarPane:async(t,n,r)=>(await r9(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 r9(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void i9(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:S0(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>m.existsSync(e),presence:Yz,paneClaude:t=>Xie(e,t),paneDir:async(t,n)=>{let i=r.monotonic()+n9;for(;;){let o=await o9(e,t);if(o.foreground===n){if(o.cwd===``)throw Error(`tmux read no directory for pane ${t.pane}`);return o.cwd}if(r.monotonic()>i)throw Error(`the shell in pane ${t.pane} (pid ${n}) did not take its terminal back within ${n9/1e3} s`);await a(100)}},launcherNode:e=>Hie(e,e=>t9(e,m.constants.X_OK),Vie),onPath:(e,t)=>{let n=e9(e,t,e=>t9(e,m.constants.X_OK));return n===null?null:m.realpathSync(n)},followed:async(e,n,i)=>{let o=r.monotonic()+i;for(;!t(e).has(n);){if(r.monotonic()>o)return!1;await a(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`?Uie(i.stdout):null;return a===null?(i9(`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.monotonic()+t;for(;i.alive(e);){if(r.monotonic()>n)return!1;await a(100)}return!0},typeShellLine:async(t,n)=>void await r9(e,t,BQ(t.pane,`cc-candybar-lane`,[]),n)}}const Qie=/^[0-9a-f]{64}$/;function s9(e,t){return ue(`sha256`,e).update(JSON.stringify([t.sessionId,t.action,t.declaration,t.evaluated])).digest()}function $ie(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);return{sign:t=>s9(e,t).toString(`hex`),verify:(t,n)=>Qie.test(n)?pe(Buffer.from(n,`hex`),s9(e,t)):!1}}function c9(e){return s.join(e,`link.key`)}function l9(e){let t,n=()=>t??=eae(e);return{sign:e=>n().sign(e),verify:(e,t)=>n().verify(e,t)}}function eae(e){let t;try{t=m.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;tae(e),t=m.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 $ie(t)}function tae(e){m.mkdirSync(s.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${de(6).toString(`hex`)}`;m.writeFileSync(t,de(32),{mode:384,flag:`wx`});try{m.linkSync(t,e)}catch(e){if(e.code!==`EEXIST`)throw e}finally{m.unlinkSync(t)}}function nae(e,t,n){return{daemonLog:t,launcher:e=>Zt(e,n),storage:t=>Bie(e,t,n),sessionWrites:e=>e,doctorStores:n4(e.state),doctorEdge:m4,claudeInput:HQ,probe:Ss,laneEdge:(e,t,r,i)=>Zie(e,t,r,n,i),linkSigner:l9(c9(e.state)),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>xi(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),fetch,pricing:e=>Nne({...e,clock:n}),stat:m.statSync}}const rae=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function u9(e){if(e===void 0)return;let t=U.parse(e);if(t.isDefault)return;let n=t.fixedValue;if(n!==void 0)return n.hex;let r=t.type===H.STANDARD&&t.number!==void 0?rae[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const iae={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 aae({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=u9(t),o=u9(n),s={};for(let e of r){let t=iae[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 oae(e){return{ok:!0,band:e.rows.map(e=>aF(e).map(aae))}}function sae(e){return tF(oae,e)}const cae={band:e=>JSON.stringify(sae(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:m7(e)})};function d9(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 lae(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,l();let o=i===null?void 0:()=>e.exit(i);try{t.end(Er(n),e=>{e??a(),o?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),o?.()}},s=!1,c=!0,l=e.clock.after(200,()=>{s=!0,e.stats.requestsTimedOut++,c&&o({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,uQ)}),u=Or(r=>{let i=xr(r);c=i.kind===`request`,e.handle(i,()=>s,n,()=>c&&t.destroyed).then(e=>{c&&(e.kind===`reply`?o(e.resp,e.exitAfterFlush,e.delivered):e.kind===`subscribe`?d(e.sessionId,e.lane):f(e.start))}).catch(t=>{e.log(`error`,`handler threw: ${E(t)}`),c&&o(dQ(t),null,uQ)}).finally(()=>{c||(l(),a())})},t=>{e.log(`warn`,`frame parse failed: ${t.message}`),o({ok:!1,error:t.message,code:`BAD_REQUEST`,daemonV:3},null,uQ)}),d=(n,i)=>{if(r||t.destroyed)return;l(),a(),t.off(`data`,u);let o=d9(t),s=e.subscribe(n,{lane:i,frame:(e,t)=>o(Dr(cae[i](e,t))),refused:e=>t.end(Er(e)),drawing:()=>!0});r=!0,t.on(`close`,s)},f=n=>{if(r||t.destroyed)return;l(),t.off(`data`,u);let i=new AbortController;t.on(`close`,()=>i.abort()),n(i.signal).then(e=>o(e.resp,e.exitAfterFlush,e.delivered),t=>{e.log(`error`,`held request threw: ${E(t)}`),o(dQ(t),null,uQ)})};t.on(`data`,u),t.on(`error`,t=>{e.log(`warn`,`socket error: ${t.message}`)}),t.on(`close`,()=>{c&&(l(),a())})}const f9=`CC_CANDYBAR_PARENT_PID`;function uae(e){let t=e[f9];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${f9} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function dae(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor;return{disarm:e.clock.every(e.intervalMs??250,()=>{e.probe.alive(t)||e.onOrphaned(`spawner pid ${t} gone`)},{unref:!0})}}let p9=null,m9=null,h9=null,g9=null;function _9(){if(g9===null)throw Error(`runDaemon has not started`);return g9}function v9(e,t){_9().log.log(e,t)}function fae(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:Cn(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function pae(e){let n=Jn(e.home);g9={world:e,paths:n,log:new yee(n.log,e.clock)},t.on(`uncaughtException`,e=>{v9(`error`,`uncaughtException: ${e.stack||e.message}`),S9(1)}),t.on(`unhandledRejection`,e=>{v9(`error`,`unhandledRejection: ${String(e)}`),S9(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{v9(`info`,`received ${e}, shutting down`),S9(0)});mae().catch(y9)}function y9(e){v9(`error`,`refusing to boot: ${E(e)}`),S9(1)}async function mae(){let{world:e,paths:n,log:r}=_9(),{host:i,home:a}=e,o=si(i.env);a.kind===`main`&&a.legacySocket!==null&&v9(`warn`,`CC_CANDYBAR_SOCKET=${a.legacySocket} is honoured for one more release; a renderer is named by CC_CANDYBAR_HOME and CC_CANDYBAR_NAME instead`),p9=await lee(t.pid,Ss(e.launcher).startTime);let s=await pee(hee(e,p9,Hn(i),n.socket!==Pn(Re)));if(!s.decision.allow){v9(`warn`,`fork-bomb breaker: ${s.decision.reason}; refusing to boot`),S9(1);return}m9=s.registryPath,m.mkdirSync(n.state,{recursive:!0}),Ln(n.socket);let c=Lie({...nae(n,r,e.clock),bundle:fae(),host:i,home:a,memoryLimitBytes:o,registryUrl:i.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:Jz(),exit:S9});h9=c,dae({clock:e.clock,anchor:uae(i.env),probe:Ss(e.launcher),onOrphaned:e=>{v9(`info`,`parent watchdog: ${e}; shutting down`),S9(0)}}),b9(c,me.createServer(e=>lae(c,e)),n.socket,!1)}function b9(e,n,r,i){n.removeAllListeners(`error`),n.removeAllListeners(`listening`),n.once(`error`,a=>{if(a.code!==`EADDRINUSE`){v9(`error`,`server error: ${a.message}`),S9(1);return}if(i){v9(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}hae(e,n,r).catch(y9)}),n.listen(r,()=>gae(e,r))}async function hae(e,n,r){let i=await ps(ms(Rn(r)),(t,n)=>Cs(t,n,Ss(e.launcher)));if(i.kind===`attach-and-exit`){v9(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}v9(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{m.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){v9(`error`,`cannot unlink stale socket ${r}: ${e.message}`),S9(1);return}}b9(e,n,r,!0)}function gae(e,n){let r=_s(n);if(r.kind!==`present`){v9(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),S9(0);return}vae(n);try{m.chmodSync(n,384)}catch(e){v9(`warn`,`chmod socket failed: ${e.message}`)}v9(`info`,`daemon up: pid=${t.pid} v=3 sock=${n} heapCap=${F(he.getHeapStatistics().heap_size_limit)}MB memoryLimit=${F(e.memoryLimitBytes)}MB`),Ai(_9().paths.spawnBackoff),e.arm(),_ae(n,r.identity)}function _ae(e,n){bs({bound:n,myPid:t.pid,readIdentity:()=>_s(e),readLease:()=>ms(Rn(e)),shutdown:e=>S9(e),log:v9,clock:_9().world.clock}).arm()}function vae(e){let n=hs(Rn(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:p9});n!==null&&v9(`warn`,`lease write failed: ${n}`)}const yae=e=>(t,n,r)=>bee(e,{socket:t},`tmux-status`,n,r);let x9=!1;function S9(e){x9||(x9=!0,_9().world.clock.after(500,()=>t.kill(t.pid,`SIGKILL`)),h9?.close(yae(_9().world.launcher)),gs(_9().paths.lease,t.pid),m9!==null&&mee(m9,t.pid,Ts,e=>m.unlinkSync(e)),t.exit(e))}function bae(e,t){let n=[],r=10;for(let t=0;t<e.length;t++){let i=e[t];if(i===`--seconds`){let n=e[++t];if(n===void 0)return{ok:!1,problem:`--seconds needs a number after it`};let i=Cr(Number(n));if(!i.ok)return{ok:!1,problem:`--seconds ${JSON.stringify(n)} ${i.problem}`};r=i.seconds}else if(i!==void 0&&!i.startsWith(`-`))n.push(i);else return{ok:!1,problem:`unexpected argument ${JSON.stringify(i)}`}}let[i,a,...o]=n;return i===void 0||a===void 0||o.length>0?{ok:!1,problem:`usage: cc-candybar record <session-id> <path> [--seconds N]`}:{ok:!0,args:{session:i,path:f(t,a),seconds:r}}}function xae(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`record: ${Rr(e)}\n`,code:1};let{path:n,lines:r,answers:i,daemonClosed:a}=e.value,o=`the daemon closed before ${t}s ran out`;return i===0?{stdout:``,stderr:a?`record: ${n}: ${o}, and no request had been answered, so there is nothing to replay. No file was left.\n`:`record: ${n}: no request was answered in ${t}s, so there is nothing to replay: the session was idle, or its statusline is not drawn by this daemon. No file was left.\n`,code:1}:{stdout:`${n}: ${r} lines, ${i} answers\n`,stderr:a?`record: ${o}: the file holds what came before.\n`:``,code:0}}async function Sae(e,t,n){let r=bae(t,n);if(!r.ok)return{stdout:``,stderr:`record: ${r.problem}\n`,code:2};let{session:i,path:a,seconds:o}=r.args;return xae(await jr(e,()=>({kind:`record`,session:i,path:a,seconds:o}),{connectMs:200,budgetMs:o*1e3+2e3},e=>`recorded`in e?e.recorded:void 0),o)}const Cae={connectMs:200,budgetMs:500};async function wae(e,t,n){return Tae(t,await Eae(e,t),n.includes(`--json`))}function Tae(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
509
509
  `:Dae(t.value),stderr:``,code:0}:{stdout:``,stderr:`${e}: ${Rr(t)}\n`,code:1}}function Eae(e,t){return jr(e,()=>({kind:`debug`,what:t}),Cae,e=>`debug`in e?e.debug:void 0)}function Dae(e){switch(e.what){case`vars`:return Oae(e.vars);case`segments`:return kae(e.segments);case`config`:return Aae(e.config);default:return e}}function Oae(e){if(e.length===0)return`no variables (DSL not active)