@promptctl/cc-candybar 1.212.1 → 1.212.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +36 -36
  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 w,rmSync as T,statSync as E,unlinkSync as ee,writeFileSync as D}from"node:fs";import{StringDecoder as te}from"node:string_decoder";import{inspect as O,parseArgs as k,types as ne}from"node:util";import{clearImmediate as A,setImmediate as re}from"node:timers";import ie,{createHash as ae,createHmac as oe,randomBytes as se,randomUUID as ce,timingSafeEqual as le}from"node:crypto";import ue from"node:net";import{spawn as de,spawnSync as fe}from"node:child_process";import pe from"node:v8";import{open as me,readFile as he,readdir as ge,stat as _e}from"node:fs/promises";import{get as ve}from"node:https";import{WriteStream as ye}from"node:tty";import{createInterface as be}from"node:readline";var xe=Object.create,Se=Object.defineProperty,Ce=Object.getOwnPropertyDescriptor,we=Object.getOwnPropertyNames,Te=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty,De=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Oe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=we(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ee.call(e,s)&&s!==n&&Se(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ce(t,s))||r.enumerable});return e},ke=(e,t,n)=>(n=e==null?{}:xe(Te(e)),Oe(t||!e||!e.__esModule?Se(n,`default`,{value:e,enumerable:!0}):n,e));let Ae=!1;const je=()=>Ae;function Me(e){Ae=e}function Ne(e){return je()?`[DEBUG] ${e()}\n`:``}function Pe(e,...t){je()&&console.error(`[DEBUG] ${e}`,...t)}function Fe(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const Ie=(e,t)=>Pe(t),Le=`main`,Re=`CC_CANDYBAR_HOME`,ze=`CC_CANDYBAR_NAME`,Be=`CC_CANDYBAR_RUNTIME_DIR`,Ve=/^[a-z0-9][a-z0-9-]*$/;function He(e,t){if(!Ve.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 Ue(e){let t=He(e,ze);if(t===`main`)throw Error(`${ze} may not be ${JSON.stringify(Le)}: that is the main renderer's name, which is what an unset ${Re} and ${ze} mean`);return t}function We(e){return e===`main`?Le:He(e,`a link's renderer name`)}function Ge(e){return e===`main`?`socket`:`${e}.sock`}function Ke(e,t){let n=e[t];return n&&n.length>0?n:void 0}function qe(){let e=process.getuid();return s.join(`/tmp`,`cc-candybar-${e}`)}function Je(e){let t=Ke(e.env,Be);if(t===void 0)return qe();if(!s.isAbsolute(t))throw Error(`${Be} must be an absolute path, got ${JSON.stringify(t)}`);return t}function Ye(e){let{env:t}=e,n=Ke(t,Re),r=Ke(t,ze),i=Ke(t,`CC_CANDYBAR_SOCKET`)??null,a=Je(e);if(n!==void 0&&r!==void 0){if(!s.isAbsolute(n))throw Error(`${Re} must be an absolute path, got ${JSON.stringify(n)}`);if(i!==null)throw Error(`CC_CANDYBAR_SOCKET is set beside ${Re} and ${ze}: a named renderer's socket is its name's, so unset it`);return{kind:`named`,name:Ue(r),runtime:a,root:n}}if(n!==void 0||r!==void 0){let[e,t]=n===void 0?[ze,Re]:[Re,ze];throw Error(`${e} is set without ${t}: a renderer's home is both, or neither for the main renderer`)}return{kind:`main`,name:Le,runtime:a,roots:{state:Ke(t,`XDG_STATE_HOME`)??s.join(e.home,`.local`,`state`),cache:Ke(t,`XDG_CACHE_HOME`)??s.join(e.home,`.cache`),config:Ke(t,`XDG_CONFIG_HOME`)??s.join(e.home,`.config`)},legacySocket:i}}function Xe(e,t){return e+t}function Ze(e,t){return Math.round(t-e)}function Qe(e,t){return Ze(t,e.monotonic())}const $e={now:()=>Date.now(),monotonic:()=>performance.now(),bootTime:()=>Date.now()-o.uptime()*1e3,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=re(e);return()=>A(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){return`${e}.${process.pid}.${ce()}.tmp`}function lt(e,t){return ne.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!v(t)?`working directory does not exist: ${t}`:e.message:String(e)}const ut={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function dt(e,t,n){let r=ut[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 ft(e,t){return{...e.inherited,...t.envOverlay}}function pt(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 mt=e=>{let t=[];for(let n of e){if(t.length===200)return`${t.join(``)}…`;t.push(n)}return e};function ht(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 mt(n);let i=Math.max(n.lastIndexOf(`
3
3
  `),n.lastIndexOf(`\r`))+1;return`${mt(n.slice(0,r).trim())} … ${mt(n.slice(i).trim())}`}function gt(e,t=``){let n=ht(e,e.stderr);return`${pt(e)}${t}${n===``?``:`: ${n}`}`}const _t=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function vt(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 yt(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function bt(e,t,n){let r=xt(e,t,n);return r===null?(e.lastStartAt.set(t,e.scope.clock.monotonic()),null):(e.scope.stats?.onRefused(t),r)}function xt(e,t,n){if(e.scope.signal.aborted)return _t(e.scope.signal);if(n?.aborted)return _t(n);let r=dt(e.lastStartAt,t,e.scope.clock.monotonic());return r.allowed?null:vt(t,r.minIntervalMs,r.sinceLastMs)}const St=`\$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 Ct(e,t){t!==e.fault&&(e.fault=t,e.scope.observeWarnings({kind:`lifeline`,fault:t}))}function wt(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),Ct(e,n))}const Tt=e=>`programs launched now would outlive their launcher if it died: its launch lifeline ${e}, and the next launch starts another`,Et=e=>e===`cut`?`output cut at the ${Ft}-byte bound, so the program holding it now fails its writes`:`output failed to read`,Dt=`a launched program's pipe outlived its launch: `;function Ot(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:`${Dt}${[...i].map(([e,t])=>{let[n,r]=e.split(`\0`);return`${t}× ${r} ${Et(n)}`}).join(`; `)}`,at:e.scope.now(),answered:!1,counts:i},e.scope.observeWarnings({kind:`launch-pipes`,text:`${Dt}${n} ${Et(t)}`})}function kt(e,t){let n=e.pipeEvent;n===null||!rt(n,t)||(e.pipeEvent={...n,answered:!0})}function At(e,t,n){let r=e.pipeEvent,i=r===null?`over`:nt(r,60,t,n);return[...e.fault===null?[]:[{kind:`lifeline`,message:Tt(e.fault)}],...r===null||i===`over`?[]:[{kind:`launch-pipes`,message:r.text,event:r,hold:i}]]}function jt(e){let{stats:t,clock:n}=e.scope;t?.onStart(`lifeline`);let r=n.monotonic(),i;try{i=e.spawner.spawn(`awk`,[St],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(i){return t?.onEnd(`lifeline`,Qe(n,r)),Ct(e,`did not start: ${lt(i,void 0)}`),null}t?.onEnd(`lifeline`,Qe(n,r));let a=i.stdin;if(a==null)return i.once(`error`,t=>Ct(e,`did not start: ${t.message}`)),null;i.once(`spawn`,()=>{e.lifeline?.process===i&&Ct(e,null)}),i.once(`error`,t=>wt(e,i,`failed: ${t.message}`)),i.once(`exit`,(t,n)=>wt(e,i,`exited ${n??t}`)),a.on(`error`,t=>wt(e,i,`pipe failed: ${t.message}`)),yt(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 Mt(e,t){e.liveGroups.add(t),e.lifeline??=jt(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function Nt(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function Pt(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}const Ft=16*1024*1024,It=`output exceeded ${Ft} bytes`,Lt=e=>`timed out after ${e/1e3} s`;function Rt(e,t,n,r){let{stats:i}=e.scope,a=new te(`utf8`),o=``,s=0,c=0,l=r,u=`closed`;return n?.on(`error`,n=>{i?.onPipeError(t),l===null?Ot(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(),Ot(e,`cut`,t);return}let d=Math.max(0,Ft-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||zt(e,t,n,()=>u)}}}function zt(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 Bt=()=>`closed`;function Vt(e,t){e.on(`error`,()=>{}),e.end(t)}async function Ht(e,t){let{stats:n,clock:r}=e.scope,i=bt(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:ft(e.scope,t),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(e){n?.onEnd(t.category,Qe(r,a)),i({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:lt(e,t.cwd)});return}let c=s.pid;c!==void 0&&Mt(e,c);let l=new Promise(e=>s.once(`exit`,e)),u=s.stdin;s.stdin=null;let d=null,f={full:()=>ee(`output-limit`),failed:e=>{d??=e.message,ee(`pipe-error`)}},p=Rt(e,t.category,s.stdout,f),m=Rt(e,t.category,s.stderr,f),h=()=>({stdout:p.take(),stderr:m.take()}),g=!1,_=null,v=null,y=null,b=null,x=()=>ee(`aborted`),S=()=>{t.signal?.removeEventListener(`abort`,x),e.inFlight.delete(x)},C=i=>{g||(g=!0,_?.(),v?.(),y?.(),S(),c!==void 0&&Nt(e,c),n?.onEnd(t.category,Qe(r,a)),s.off(`close`,te),s.off(`error`,D),p.drain(),m.drain(),u!==null&&!u.destroyed&&!u.writableFinished&&zt(e,t.category,u,Bt),i())},w=e=>C(()=>i(e)),T=(n,r)=>{try{o.signalGroup(n,r)}catch(n){e.unreaped.set(s,t.category),l.then(()=>e.unreaped.delete(s)),w({ok:!1,reason:`signal-refused`,...h(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},E=()=>te(s.exitCode,s.signalCode);if(c!==void 0){let e=t=>{if(!g){if(o.groupGone(c)){r.defer(E);return}y=r.after(t,()=>e(Math.min(t*2,1e3)))}};l.then(()=>r.defer(()=>e(25)))}let ee=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(E);return}b=e,_?.(),S();let t=s.pid;t!==void 0&&(v=r.after(250,()=>{T(t,`SIGKILL`),l.then(()=>r.defer(E))}),T(t,`SIGTERM`))},D=e=>{w({ok:!1,reason:`spawn-error`,...h(),exitCode:null,signal:null,error:lt(e,t.cwd)})};s.on(`error`,D);let te=(e,n)=>{if(b!==null){w({ok:!1,reason:b,...h(),exitCode:e,signal:n,...b===`timeout`?{error:Lt(t.timeoutMs??0)}:b===`output-limit`?{error:It}:b===`pipe-error`?{error:`a pipe failed to read: ${d}`}:{}});return}if(e===0){w({ok:!0,...h(),exitCode:e});return}w({ok:!1,reason:n?`signal`:`non-zero`,...h(),exitCode:e,signal:n})};s.on(`close`,te),t.timeoutMs&&t.timeoutMs>0&&(_=r.after(t.timeoutMs,()=>ee(`timeout`))),t.signal?.addEventListener(`abort`,x,{once:!0}),e.inFlight.add(x),u!==null&&Vt(u,t.stdinInput)})}function Ut(e,t){let{stats:n,clock:r}=e.scope,i=bt(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:ft(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,Qe(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`?Lt(t.timeoutMs??0):lt(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,Qe(r,a)),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:lt(e,t.cwd)}}}function j(e,t){let{stats:n,clock:r}=e.scope,i=bt(e,t.category);if(i!==null)return i;let a=r.monotonic();n?.onStart(t.category);let o=Wt(e,t);return n?.onEnd(t.category,Qe(r,a)),o}function Wt(e,t){let n;try{n=e.spawner.spawn(t.bin,t.args??[],{cwd:t.cwd,env:ft(e.scope,t),detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:lt(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 Gt=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`;function Kt(e,t,n){let{stats:r,clock:i}=e.scope,a=bt(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:ft(e.scope,t),detached:!0,stdio:[`pipe`,`ignore`,`ignore`]})}catch(e){return r?.onEnd(t.category,Qe(i,o)),{ok:!1,reason:`spawn-error`,error:lt(e,t.cwd)}}r?.onEnd(t.category,Qe(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 qt(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 Jt(e,t,n,r,i){let a=Yt(r,i);if(a.verdict===`gone`)return a;let o=e.signalJob(n,`SIGTERM`);return o&&t.after(250,()=>e.signalJob(n,`SIGKILL`),{unref:!0}),{...a,signalled:o}}function Yt(e,t){let n=ct(e);try{return D(n,`${Gt(t)}\n`),b(n,e),{verdict:`stands`}}catch(t){let n=t.code;return n===`ENOENT`?{verdict:`gone`}:n===`EEXIST`?{verdict:`preceded`}:{verdict:`unrecorded`,error:`${e}: ${n??t.message}`}}finally{v(n)&&T(n,{force:!0})}}function M(e,t,n){return Zt(e,t,n).launcher}function Xt(e,t,n){let{launcher:r,state:i}=Zt(e,t,n);return{...r,launchSync:e=>Ut(i,e)}}function Zt(e,t,n){let r={clock:t,launch:e=>yt(i,Ht(i,e)),launchDetachedSync:e=>j(i,e),launchJobSync:(e,t)=>Kt(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>Jt(n,t,e,r,i),launcherWarnings:(e,t)=>At(i,e,t),answeredPipeEvent:e=>kt(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&&wt(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:Tt(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()),Pt(i)},{once:!0}),{launcher:r,state:i}}const Qt=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [ 123]\d \d\d:\d\d:\d\d \d{4}$/,$t=e=>typeof e==`string`&&Qt.test(e)?e:void 0,en=2e3;async function tn(e,t){return an(await t(nn(e)))}const nn=(e,t=en)=>({bin:`ps`,args:[`-o`,`lstart=`,`-p`,String(e)],category:`process-fingerprint`,timeoutMs:t,envOverlay:{LC_ALL:`C`,TZ:`UTC`}});function rn(e,t){if(t.kind===`unavailable`)return{pid:e,startTime:null,why:t.detail};let n=$t(t.token);return n===void 0?{pid:e,startTime:null,why:`ps printed ${JSON.stringify(t.token)}, not a start in the form \`ps -o lstart=\` prints`}:{pid:e,startTime:n}}function an(e){if(e.ok){let t=e.stdout.trim();return t.length>0?{kind:`start`,token:t}:{kind:`unavailable`,detail:`ps produced no start-time`}}return{kind:`unavailable`,detail:`ps ${pt(e)}`}}function on(e){return{alive:e=>{try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}},startTime:t=>tn(t,e.launch)}}async function sn(e,t,n){if(t===null)return n.alive(e);let r=await n.startTime(e);switch(r.kind){case`start`:return r.token===t;case`unavailable`:return n.alive(e)}}async function cn(e,t){let n=await t(e);return n.kind===`start`?n.token:null}const ln=new Set([`ECONNREFUSED`,`ENOENT`,`ENOTSOCK`]),un=e=>({cause:ln.has(e.code??``)?`unreachable`:`io_error`,message:e.message}),dn={dial(e){let t=ue.createConnection({path:e}),n=!1;return{settled:new Promise(e=>{let r=r=>{t.off(`connect`,i),n=!0,e({ok:!1,failure:un(r)})},i=()=>{t.off(`error`,r),n=!0,e({ok:!0,conn:t})};t.once(`error`,r),t.once(`connect`,i)}),abandon:()=>{n||(t.removeAllListeners(),t.destroy())}}}},fn=e=>e.isSymbolicLink()?`symlink`:e.isDirectory()?`directory`:e.isFile()?`file`:`other`,pn=e=>({kind:fn(e),size:Number(e.size),mtimeMs:Number(e.mtimeNs)/1e6,mode:Number(e.mode),dev:e.dev,ino:e.ino,birthtimeNs:e.birthtimeNs}),mn={watchReach:process.platform===`darwin`?`tree`:`directory`,statSync:e=>pn(m.statSync(e,{bigint:!0})),lstatSync:e=>pn(m.lstatSync(e,{bigint:!0})),readlinkSync:e=>m.readlinkSync(e),realpathSync:e=>m.realpathSync.native(e),mkdirSync:e=>void m.mkdirSync(e,{recursive:!0}),opendirSync:e=>m.opendirSync(e).closeSync(),readFileSync:e=>m.readFileSync(e,`utf8`),readdirSync:e=>m.readdirSync(e,{withFileTypes:!0}).map(e=>({name:e.name,kind:fn(e)})),writeFileSync:(e,t,{mode:n,flush:r})=>m.writeFileSync(e,t,{mode:n,flush:r}),renameSync:(e,t)=>m.renameSync(e,t),rmSync:e=>{try{m.rmSync(e,{force:!0})}catch(e){let t=e;throw t.code===`ERR_FS_EISDIR`&&(t.code=`EISDIR`),e}},stat:async e=>pn(await m.promises.stat(e,{bigint:!0})),readFile:e=>m.promises.readFile(e,`utf8`),writeFile:(e,t)=>m.promises.writeFile(e,t),readdir:async e=>(await m.promises.readdir(e,{withFileTypes:!0})).map(e=>({name:e.name,kind:fn(e)})),unlink:e=>m.promises.unlink(e),watch:(e,{recursive:t},n)=>{let r=m.watch(e,{persistent:!1,recursive:t},(e,t)=>n(e,t));return{close:()=>r.close(),onError:e=>void r.on(`error`,e)}}};function hn(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const gn={spawn:(e,t,n)=>de(e,t,n),spawnSync:(e,t,n)=>fe(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!hn(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}}},_n=(e,t)=>M(e,t,gn),vn=(e,t)=>Xt(e,t,gn);function yn(){let e=$e,t=vn({inherited:process.env},e),n={env:process.env,home:o.homedir(),tmp:o.tmpdir()};return{host:n,home:bn(n),launcher:t,clock:e,dialer:dn,parent:e=>rn(process.ppid,an(t.launchSync(nn(process.ppid,e)))),filesystem:mn}}function bn(e){try{return Ye(e)}catch(e){process.stderr.write(`cc-candybar: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}}const xn=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Sn(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Cn(e){return xn.test(e)?e:Sn(e)}function wn(e){return`${e.dir===void 0?``:`cd ${Cn(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Cn(t)} `).join(``)}${[e.program,...e.args].map(Cn).join(` `)}`}const Tn=`cc-extra`;function N(e){return s.join(s.dirname(e),Tn,`src`,`bun-attach.js`)}function En(e){return s.join(s.dirname(e),`bun-graph.js`)}const Dn=`attach-preload.cjs`;function On(e){return s.join(s.dirname(e),Dn)}function kn(e,t){return wn({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const An=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function jn(e,t){return t.isSymbolicLink()?Buffer.from(m.readlinkSync(e)):m.readFileSync(e)}function Mn(e,t,n=An){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(`/`),jn(r,i)]]})}function Nn(e){let t=ie.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Pn(e){return Nn(Mn(e,e))}const Fn=[`Cargo.toml`,`Cargo.lock`,`src`];function In(e){return Nn(Mn(e,e,e=>Fn.includes(e)))}const Ln=e=>e.slice(0,7),Rn=`1.212.1`;function zn(e){let t=s.dirname(s.dirname(e));return m.existsSync(s.join(t,`src`))?t:null}function Bn(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Rn,digest:e}}function Vn(){return`d7b9f976a89cc20e9288ae510126f81aedf9af1dd9162a16ab7a7f3e3688dbe3`}function Hn(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 Un(e,t){try{let n=zn(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Pn(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:Hn(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function Wn(e,t){try{return e.statSync(t).kind===`directory`?e.realpathSync(t):null}catch{return null}}function Gn(e,t){let n=Wn(e,t),r=s.dirname(t);if(n!==null||r===t)return{dir:n??t,rest:[]};let i=Gn(e,r);return{dir:i.dir,rest:[...i.rest,s.basename(t)]}}function Kn(e,t){let{dir:n,rest:r}=Gn(e,t);return s.join(n,...r)}function qn(e){return e.kind===`main`?s.join(e.roots.state,`cc-candybar`):s.join(e.root,`state`)}function Jn(e){return e.kind===`main`?s.join(e.roots.cache,`cc-candybar`):s.join(e.root,`cache`)}function Yn(e){return e.kind===`main`?s.join(e.roots.config,`cc-candybar`):s.join(e.root,`config`)}function Xn(e){return Qn(e.kind===`main`?Yn(e):e.root)}const Zn=e=>Kn(mn,e);function Qn(e){return{dir:e,onDisk:Zn}}function $n(e){return e.kind===`main`&&e.legacySocket!==null?e.legacySocket:s.join(e.runtime,Ge(e.name))}function er(e){return s.join(qe(),Ge(e))}function tr(e){return e.kind===`main`?{[Re]:``,[ze]:``,[Be]: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??``}:{[Re]:e.root,[ze]:e.name,[Be]:e.runtime,CC_CANDYBAR_SOCKET:``}}function nr(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 rr(e){nr(s.dirname(e));for(let t of[e,ir(e)])try{if(m.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function ir(e){return`${e}.lease`}function ar(e){return ir($n(e))}function or(e){return s.join(qn(e),`session-state.json`)}function sr(e){return s.join(qn(e),`settings-history.json`)}function cr(e){return e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR||s.join(qe(),`daemons`)}function lr(e){return s.join(qn(e),`spawn.lock`)}function ur(e){return s.join(qn(e),`spawn.cooldown`)}function dr(e){return s.join(qn(e),`spawn.backoff`)}function fr(e){return s.join(qn(e),`watch-probe`)}function pr(e){return s.join(qn(e),`daemon.log`)}function mr(e){return s.join(qn(e),`link-ids`)}function hr(e){return{socket:$n(e),lease:ar(e),state:qn(e),log:pr(e),sessionState:or(e),settingsHistory:sr(e),storedRoot:Xn(e),watchProbe:fr(e),spawnBackoff:dr(e),linkIds:mr(e)}}function gr(e){return Ke(e.env,`XDG_DATA_HOME`)??s.join(e.home,`.local`,`share`)}function _r(e,t){let{env:n}=e,r=`/usr/local/share:/usr/share`,i=process.platform===`darwin`?`${s.join(Ke(n,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${r}`:r;return{homeDir:e.home,configDir:Yn(t),dataHome:gr(e),dataDirs:(Ke(n,`XDG_DATA_DIRS`)??i).split(`:`).filter(e=>e!==``)}}function vr(e,t){return yr(e,t).at(-1)}function yr(e,t){let{hops:n,stopped:r}=br(e,t);if(r!==null)throw r;return n}function br(e,t){let n=[t];try{for(let t=0;t<Sr;t++){let t=xr(e,n[n.length-1]);if(t===null)return{hops:n,stopped:null};n.push(t)}return{hops:n,stopped:Error(`${t}: more than ${Sr} symbolic links`)}}catch(e){return{hops:n,stopped:e}}}function xr(e,t){try{return e.lstatSync(t).kind===`symlink`?s.resolve(e.realpathSync(s.dirname(t)),e.readlinkSync(t)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const Sr=40;function Cr(e,t,n,r){let i=vr(e,t);e.mkdirSync(s.dirname(i));let a=ct(i),o=r??Tr(e,i);try{e.writeFileSync(a,n,{mode:o,flush:!0}),e.renameSync(a,i)}catch(t){throw e.rmSync(a),t}}function wr(e,t,n){Cr(mn,e,t,n)}function Tr(e,t){try{return e.statSync(t).mode}catch(e){if(e.code===`ENOENT`)return;throw e}}function Er(e,t,n,r,i){let a=e.dial(t),o=!1;return new Promise(e=>{let t=r.after(n,()=>{o=!0,a.abandon(),e({ok:!1,failure:{cause:`timeout`}})},i);a.settled.then(n=>{t(),o&&n.ok&&n.conn.destroy(),e(n)})})}const Dr=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Or(e){return Object.fromEntries(Dr.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const kr=[`native`,`node`,`frames`];function Ar(e,t){return{kind:e,bundle:t,source:null}}const jr=[`ansi`,`frame`],Mr=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,parent:!0,client:!0});function Nr(e){let t=Hr(e.termCols),n=Hr(e.termRows),r=Ur(e.ssh),i=Br(e.tmux),a=zr(e.configEnv),o=zr(e.claudeConfigDir),s=Rr(e.terminalEnv),c=Wr(e.parent),l=ni(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&&{parent:c},...l!==void 0&&{client:l}}}function Pr(e,t){return Mr.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Fr(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 Ir={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Lr(e){let t=Object.keys(Ir).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Ir[t](n.join(`, `))]});return t.length===0?null:t.join(`
4
+ `),withdraw:()=>l.end()})}function qt(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 Jt(e,t,n,r,i){let a=Yt(r,i);if(a.verdict===`gone`)return a;let o=e.signalJob(n,`SIGTERM`);return o&&t.after(250,()=>e.signalJob(n,`SIGKILL`),{unref:!0}),{...a,signalled:o}}function Yt(e,t){let n=ct(e);try{return D(n,`${Gt(t)}\n`),b(n,e),{verdict:`stands`}}catch(t){let n=t.code;return n===`ENOENT`?{verdict:`gone`}:n===`EEXIST`?{verdict:`preceded`}:{verdict:`unrecorded`,error:`${e}: ${n??t.message}`}}finally{v(n)&&T(n,{force:!0})}}function M(e,t,n){return Zt(e,t,n).launcher}function Xt(e,t,n){let{launcher:r,state:i}=Zt(e,t,n);return{...r,launchSync:e=>Ut(i,e)}}function Zt(e,t,n){let r={clock:t,launch:e=>yt(i,Ht(i,e)),launchDetachedSync:e=>j(i,e),launchJobSync:(e,t)=>Kt(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>Jt(n,t,e,r,i),launcherWarnings:(e,t)=>At(i,e,t),answeredPipeEvent:e=>kt(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&&wt(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:Tt(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()),Pt(i)},{once:!0}),{launcher:r,state:i}}const Qt=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [ 123]\d \d\d:\d\d:\d\d \d{4}$/,$t=e=>typeof e==`string`&&Qt.test(e)?e:void 0,en=2e3;async function tn(e,t){return an(await t(nn(e)))}const nn=(e,t=en)=>({bin:`ps`,args:[`-o`,`lstart=`,`-p`,String(e)],category:`process-fingerprint`,timeoutMs:t,envOverlay:{LC_ALL:`C`,TZ:`UTC`}});function rn(e,t){if(t.kind===`unavailable`)return{pid:e,startTime:null,why:t.detail};let n=$t(t.token);return n===void 0?{pid:e,startTime:null,why:`ps printed ${JSON.stringify(t.token)}, not a start in the form \`ps -o lstart=\` prints`}:{pid:e,startTime:n}}function an(e){if(e.ok){let t=e.stdout.trim();return t.length>0?{kind:`start`,token:t}:{kind:`unavailable`,detail:`ps produced no start-time`}}return{kind:`unavailable`,detail:`ps ${pt(e)}`}}function on(e){return{alive:e=>{try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}},startTime:t=>tn(t,e.launch)}}async function sn(e,t,n){if(t===null)return n.alive(e);let r=await n.startTime(e);switch(r.kind){case`start`:return r.token===t;case`unavailable`:return n.alive(e)}}async function cn(e,t){let n=await t(e);return n.kind===`start`?n.token:null}const ln=new Set([`ECONNREFUSED`,`ENOENT`,`ENOTSOCK`]),un=e=>({cause:ln.has(e.code??``)?`unreachable`:`io_error`,message:e.message}),dn={dial(e){let t=ue.createConnection({path:e}),n=!1;return{settled:new Promise(e=>{let r=r=>{t.off(`connect`,i),n=!0,e({ok:!1,failure:un(r)})},i=()=>{t.off(`error`,r),n=!0,e({ok:!0,conn:t})};t.once(`error`,r),t.once(`connect`,i)}),abandon:()=>{n||(t.removeAllListeners(),t.destroy())}}}},fn=e=>e.isSymbolicLink()?`symlink`:e.isDirectory()?`directory`:e.isFile()?`file`:`other`,pn=e=>({kind:fn(e),size:Number(e.size),mtimeMs:Number(e.mtimeNs)/1e6,mode:Number(e.mode),dev:e.dev,ino:e.ino,birthtimeNs:e.birthtimeNs}),mn={watchReach:process.platform===`darwin`?`tree`:`directory`,statSync:e=>pn(m.statSync(e,{bigint:!0})),lstatSync:e=>pn(m.lstatSync(e,{bigint:!0})),readlinkSync:e=>m.readlinkSync(e),realpathSync:e=>m.realpathSync.native(e),mkdirSync:e=>void m.mkdirSync(e,{recursive:!0}),opendirSync:e=>m.opendirSync(e).closeSync(),readFileSync:e=>m.readFileSync(e,`utf8`),readdirSync:e=>m.readdirSync(e,{withFileTypes:!0}).map(e=>({name:e.name,kind:fn(e)})),writeFileSync:(e,t,{mode:n,flush:r})=>m.writeFileSync(e,t,{mode:n,flush:r}),renameSync:(e,t)=>m.renameSync(e,t),rmSync:e=>{try{m.rmSync(e,{force:!0})}catch(e){let t=e;throw t.code===`ERR_FS_EISDIR`&&(t.code=`EISDIR`),e}},stat:async e=>pn(await m.promises.stat(e,{bigint:!0})),readFile:e=>m.promises.readFile(e,`utf8`),writeFile:(e,t)=>m.promises.writeFile(e,t),readdir:async e=>(await m.promises.readdir(e,{withFileTypes:!0})).map(e=>({name:e.name,kind:fn(e)})),unlink:e=>m.promises.unlink(e),watch:(e,{recursive:t},n)=>{let r=m.watch(e,{persistent:!1,recursive:t},(e,t)=>n(e,t));return{close:()=>r.close(),onError:e=>void r.on(`error`,e)}}};function hn(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const gn={spawn:(e,t,n)=>de(e,t,n),spawnSync:(e,t,n)=>fe(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!hn(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}}},_n=(e,t)=>M(e,t,gn),vn=(e,t)=>Xt(e,t,gn);function yn(){let e=$e,t=vn({inherited:process.env},e),n={env:process.env,home:o.homedir(),tmp:o.tmpdir()};return{host:n,home:bn(n),launcher:t,clock:e,dialer:dn,parent:e=>rn(process.ppid,an(t.launchSync(nn(process.ppid,e)))),filesystem:mn}}function bn(e){try{return Ye(e)}catch(e){process.stderr.write(`cc-candybar: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}}const xn=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Sn(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Cn(e){return xn.test(e)?e:Sn(e)}function wn(e){return`${e.dir===void 0?``:`cd ${Cn(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Cn(t)} `).join(``)}${[e.program,...e.args].map(Cn).join(` `)}`}const Tn=`cc-extra`;function N(e){return s.join(s.dirname(e),Tn,`src`,`bun-attach.js`)}function En(e){return s.join(s.dirname(e),`bun-graph.js`)}const Dn=`attach-preload.cjs`;function On(e){return s.join(s.dirname(e),Dn)}function kn(e,t){return wn({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const An=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function jn(e,t){return t.isSymbolicLink()?Buffer.from(m.readlinkSync(e)):m.readFileSync(e)}function Mn(e,t,n=An){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(`/`),jn(r,i)]]})}function Nn(e){let t=ie.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Pn(e){return Nn(Mn(e,e))}const Fn=[`Cargo.toml`,`Cargo.lock`,`src`];function In(e){return Nn(Mn(e,e,e=>Fn.includes(e)))}const Ln=e=>e.slice(0,7),Rn=`1.212.2`;function zn(e){let t=s.dirname(s.dirname(e));return m.existsSync(s.join(t,`src`))?t:null}function Bn(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Rn,digest:e}}function Vn(){return`dd2d98adebb6de919a0420aa47ef35f7e08c09256b9023926a96c13818674a4d`}function Hn(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 Un(e,t){try{let n=zn(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Pn(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:Hn(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function Wn(e,t){try{return e.statSync(t).kind===`directory`?e.realpathSync(t):null}catch{return null}}function Gn(e,t){let n=Wn(e,t),r=s.dirname(t);if(n!==null||r===t)return{dir:n??t,rest:[]};let i=Gn(e,r);return{dir:i.dir,rest:[...i.rest,s.basename(t)]}}function Kn(e,t){let{dir:n,rest:r}=Gn(e,t);return s.join(n,...r)}function qn(e){return e.kind===`main`?s.join(e.roots.state,`cc-candybar`):s.join(e.root,`state`)}function Jn(e){return e.kind===`main`?s.join(e.roots.cache,`cc-candybar`):s.join(e.root,`cache`)}function Yn(e){return e.kind===`main`?s.join(e.roots.config,`cc-candybar`):s.join(e.root,`config`)}function Xn(e){return Qn(e.kind===`main`?Yn(e):e.root)}const Zn=e=>Kn(mn,e);function Qn(e){return{dir:e,onDisk:Zn}}function $n(e){return e.kind===`main`&&e.legacySocket!==null?e.legacySocket:s.join(e.runtime,Ge(e.name))}function er(e){return s.join(qe(),Ge(e))}function tr(e){return e.kind===`main`?{[Re]:``,[ze]:``,[Be]: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??``}:{[Re]:e.root,[ze]:e.name,[Be]:e.runtime,CC_CANDYBAR_SOCKET:``}}function nr(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 rr(e){nr(s.dirname(e));for(let t of[e,ir(e)])try{if(m.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function ir(e){return`${e}.lease`}function ar(e){return ir($n(e))}function or(e){return s.join(qn(e),`session-state.json`)}function sr(e){return s.join(qn(e),`settings-history.json`)}function cr(e){return e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR||s.join(qe(),`daemons`)}function lr(e){return s.join(qn(e),`spawn.lock`)}function ur(e){return s.join(qn(e),`spawn.cooldown`)}function dr(e){return s.join(qn(e),`spawn.backoff`)}function fr(e){return s.join(qn(e),`watch-probe`)}function pr(e){return s.join(qn(e),`daemon.log`)}function mr(e){return s.join(qn(e),`link-ids`)}function hr(e){return{socket:$n(e),lease:ar(e),state:qn(e),log:pr(e),sessionState:or(e),settingsHistory:sr(e),storedRoot:Xn(e),watchProbe:fr(e),spawnBackoff:dr(e),linkIds:mr(e)}}function gr(e){return Ke(e.env,`XDG_DATA_HOME`)??s.join(e.home,`.local`,`share`)}function _r(e,t){let{env:n}=e,r=`/usr/local/share:/usr/share`,i=process.platform===`darwin`?`${s.join(Ke(n,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${r}`:r;return{homeDir:e.home,configDir:Yn(t),dataHome:gr(e),dataDirs:(Ke(n,`XDG_DATA_DIRS`)??i).split(`:`).filter(e=>e!==``)}}function vr(e,t){return yr(e,t).at(-1)}function yr(e,t){let{hops:n,stopped:r}=br(e,t);if(r!==null)throw r;return n}function br(e,t){let n=[t];try{for(let t=0;t<Sr;t++){let t=xr(e,n[n.length-1]);if(t===null)return{hops:n,stopped:null};n.push(t)}return{hops:n,stopped:Error(`${t}: more than ${Sr} symbolic links`)}}catch(e){return{hops:n,stopped:e}}}function xr(e,t){try{return e.lstatSync(t).kind===`symlink`?s.resolve(e.realpathSync(s.dirname(t)),e.readlinkSync(t)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const Sr=40;function Cr(e,t,n,r){let i=vr(e,t);e.mkdirSync(s.dirname(i));let a=ct(i),o=r??Tr(e,i);try{e.writeFileSync(a,n,{mode:o,flush:!0}),e.renameSync(a,i)}catch(t){throw e.rmSync(a),t}}function wr(e,t,n){Cr(mn,e,t,n)}function Tr(e,t){try{return e.statSync(t).mode}catch(e){if(e.code===`ENOENT`)return;throw e}}function Er(e,t,n,r,i){let a=e.dial(t),o=!1;return new Promise(e=>{let t=r.after(n,()=>{o=!0,a.abandon(),e({ok:!1,failure:{cause:`timeout`}})},i);a.settled.then(n=>{t(),o&&n.ok&&n.conn.destroy(),e(n)})})}const Dr=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Or(e){return Object.fromEntries(Dr.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const kr=[`native`,`node`,`frames`];function Ar(e,t){return{kind:e,bundle:t,source:null}}const jr=[`ansi`,`frame`],Mr=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,parent:!0,client:!0});function Nr(e){let t=Hr(e.termCols),n=Hr(e.termRows),r=Ur(e.ssh),i=Br(e.tmux),a=zr(e.configEnv),o=zr(e.claudeConfigDir),s=Rr(e.terminalEnv),c=Wr(e.parent),l=ni(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&&{parent:c},...l!==void 0&&{client:l}}}function Pr(e,t){return Mr.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Fr(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 Ir={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Lr(e){let t=Object.keys(Ir).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Ir[t](n.join(`, `))]});return t.length===0?null:t.join(`
5
5
  `)}function Rr(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Dr.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 zr(e){return typeof e==`string`&&s.isAbsolute(e)?e:void 0}function Br(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 Vr=1e4;function Hr(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>Vr?Vr:t}function Ur(e){return typeof e==`boolean`?e:void 0}function Wr(e){if(typeof e!=`object`||!e)return;let{pid:t,startTime:n,why:r}=e;if(!Number.isSafeInteger(t)||t<=0)return;if(n===null)return typeof r==`string`&&r!==``?{pid:t,startTime:null,why:r}:void 0;let i=$t(n);return i===void 0?void 0:{pid:t,startTime:i}}const Gr=new Set([...[],1]);function Kr(e){return typeof e==`object`&&e&&e.kind===`url`?{kind:`url`,frame:e}:{kind:`request`,req:e}}const qr=Math.floor((2**31-1)/1e3)-60;function Jr(e){return typeof e==`number`&&e>0&&e<=qr?{ok:!0,seconds:e}:{ok:!1,problem:`is not a span of seconds above 0 and at most ${qr}`}}var Yr=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}},Xr=class extends Error{constructor(e){super(e===`connect`?`CONNECT_TIMEOUT`:`TIMEOUT`),this.phase=e,this.name=`ClientTimeoutError`}};function Zr(e){return Qr(JSON.stringify(e))}function Qr(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function $r(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 Yr(`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 Yr(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function ei(e,t,n){let r=null,i=$r(e=>void(r??={ok:!0,frame:e}),e=>void(r??={ok:!1,err:e})),a=o=>{i(o),r!==null&&(e.off(`data`,a),r.ok?t(r.frame):n(r.err))};e.on(`data`,a)}function ti(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 Xr(`deadline`))})}),l=$r(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(Zr(t))})}function ni(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=zr(n);return kr.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function ri(e,t,n,r){let i=await Er(e.dialer,$n(e.home),n.connectMs,e.clock);return i.ok?ai(i.conn,e.clock,t,n,r):ii(i.failure)}function ii(e){return e.cause===`timeout`?{kind:`busy`,phase:`connect`,message:new Xr(`connect`).message}:{kind:`transient`,cause:e.cause,message:e.message}}async function ai(e,t,n,r,i){try{let a=t.now()+r.budgetMs,o=n(a),s=await ti(e,{v:3,...o},a,t);return ci(o.kind,s,i)}catch(e){return li(e)}finally{e.destroy()}}function oi(e,t){return typeof e==`string`?e:t}function si(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function ci(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=oi(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:si(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 li(e){if(e instanceof Yr||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 Xr?{kind:`busy`,phase:e.phase,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function ui(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 di(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 fi(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 pi={connectMs:50,budgetMs:150},mi={connectMs:50,budgetMs:350};function hi(e){let t=e.output;return typeof t==`string`?t:void 0}function gi(e){return ci(`render`,e,hi)}function _i(e,t,n,r,i,a=pi){return ri(e,e=>({kind:`render`,hookData:t,args:n,cwd:r,deadline:e,...i}),a,hi)}function vi(e,t,n){return ri(e,()=>({kind:`pane-session`,socket:t,pane:n}),mi,e=>`paneSession`in e?e.paneSession:void 0)}function yi(e,t){return ri(e,()=>({kind:`click`,url:t}),mi,hi)}const bi=5e3;async function xi(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 Si=`/usr/bin/footprint`;function Ci(e,t,n){return t===`darwin`?[Di(e,Si,[`-p`,String(n)]),Di(e,`/usr/bin/vmmap`,[`--summary`,String(n)])]:t===`linux`?[Oi(`/proc/self/smaps_rollup`),Oi(`/proc/self/status`)]:[]}function wi(e,t,n){return t===`darwin`?Ti(n,t=>e.launch({bin:Si,args:t,timeoutMs:bi,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function Ti(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 ${gt(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 Di(e,t,n){return{name:`${t} ${n.join(` `)}`,read:async()=>{let r=await e.launch({bin:t,args:[...n],timeoutMs:bi,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:gt(r)}}}}function Oi(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 ki=`CC_CANDYBAR_RSS_LIMIT_MB`;function Ai(e){let t=e[ki];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${ki} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function ji(e){return Ai(e)*2}const Mi=1024*1024,P=e=>Math.round(e/Mi);function Ni(e){return Ai(e)*Mi}const Pi={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function Fi(e,t){return e>t}function Ii(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 Li=.75;function Ri(e,t){return e>t*Li}function zi(e,t,n){let{prefix:r,suffix:i}=Pi[t];return s.join(e,`${r}${n}${i}`)}function Bi(e){for(let t of Object.keys(Pi)){let{prefix:n,suffix:r}=Pi[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function Vi(e){let t=e.limitBytes??1024*Mi,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=Ii(await e.memoryCharge(a),i),l={kind:`measured`,charge:c,rss:a,heapTotal:s};if(i=l,e.log(`info`,`memory ${Wi(l,t)}`),o||c.bytes<=t)return!1;r=!0,e.log(`warn`,`${Hi(c)} > limit ${P(t)} MB (rss ${P(a)} MB, v8 heap ${P(s)} MB); recording memory then shutting down`);let u=`${new Date(e.clock.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return await Gi(e.log,`memory report`,async()=>{let t=zi(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 Gi(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=zi(e.snapshotDir,`heapSnapshot`,u);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),await Gi(e.log,`artifact rotation`,async()=>{for(let{artifacts:t}of Ki(e.listArtifacts()).slice(n))for(let n of Object.values(t))await Gi(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0)}function u(){return i.kind===`measured`&&Ri(i.charge.bytes,t)?`${Hi(i.charge)} approaching limit ${P(t)} MB (v8 heap ${P(i.heapTotal)} MB)`:null}function d(){let n;try{n={kind:`ok`,value:Ki(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 Hi(e){return e.kind===`charged`?`${e.measure} ${P(e.bytes)} MB`:`rss ${P(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${P(e.gap)} MB gap`} (standing in: ${e.unread})`}function Ui(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function Wi({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${P(e.gap)}MB`:``;return`measure=${Ui(e)} charge=${P(e.bytes)}MB rss=${P(t)}MB heap=${P(n)}MB limit=${P(r)}MB${i}`}async function Gi(e,t,n){try{await n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function Ki(e){let t=new Map;for(let n of e){let e=s.basename(n),r=Bi(e);if(r===null)continue;let{prefix:i,suffix:a}=Pi[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(Pi);return[...t].sort(([e],[t])=>Fi(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function qi(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:wi(n.launcher,process.platform,process.pid),captureMemoryReport:()=>xi(Ci(n.launcher,process.platform,process.pid)),writeMemoryReport:(e,t)=>m.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>pe.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=>Bi(e)!==null).map(e=>s.join(i,e))},removeFile:e=>m.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}function Ji(e,n={}){let{home:r,clock:i}=e;if(la(r)!==null)return;let a=n.spawn??(()=>tee(e)),o=oa(r,i);if(o.kind===`contended`){let e=eee(r,i);e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),Yi(r,i,a));return}if(o.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${o.reason}) — spawning unlocked\n`),Yi(r,i,a);return}try{Yi(r,i,a)}finally{ca()}}function Yi(e,t,n){na(e,t)&&Xi(n)}function eee(e,t){try{let n=m.statSync(lr(e));return t.now()-n.mtimeMs}catch{return null}}function Xi(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 Zi(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function Qi(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function $i(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 ea(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 ta(e){try{m.unlinkSync(e)}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function na(e,n){let r=ur(e),i=dr(e),a=$i(i),o=Zi(ra(r,n),Qi(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`),ia(r,n),ea(i,Math.min(a+1,5)),!0)}function ra(e,t){try{return t.now()-m.statSync(e).mtimeMs}catch{return null}}function ia(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 aa=null;function oa(e,n){let r=lr(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 aa={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(!sa(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 sa(e,t){try{let n=m.statSync(e);return t.now()-n.mtimeMs>1e4}catch{return!0}}function ca(){if(!aa)return;let{fd:e,path:t}=aa;aa=null;try{m.closeSync(e)}catch{}try{m.unlinkSync(t)}catch{}}function la(e){try{return m.mkdirSync(qn(e),{recursive:!0}),null}catch(t){return`mkdir ${qn(e)}: ${t.message}`}}function ua(e,t){return[`--max-old-space-size=${ji(t)}`,e,`daemon`]}function tee({host:e,launcher:n}){let r=t.execPath,i=t.argv[1];return i?n.launchDetachedSync({bin:r,args:ua(i,e.env),category:`daemon-spawn`}).ok:!1}const da=`cc-candybar`,fa=`CCCandybarURLHandler`,pa=e=>e.startsWith(`${da}://`),ma=`closed`,ha=`open`,ga=`🍫`;function _a(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 va(e,t,n,r){let i=_a(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function ya(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function ba(e,t,n,r,i){return{kind:`segment`,name:e,opens:{ref:t,body:n,placement:r},...i!==void 0&&{when:i}}}function xa(e,...t){return`{{ and ${[e,...t].map(Sa).join(` `)} }}`}function Sa(e){return`(eq .${e.variable} "${ya(e.member)}")`}function Ca(e,t,n){return`{{ ${wa(e,Ta(t),Ta(n))} }}`}function wa(e,t,n){return`action "${e}" ${t} ${n}`}function Ta(e){return`"${ya(e)}"`}function Ea(e,t){return{kind:`state`,key:e,default:t}}function Da(e,t){return{set:e,cycle:[ma,t]}}function Oa(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 ka=De(((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]/})),Aa=De(((e,t)=>{let n=ka();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)}}})),ja=De(((e,t)=>{let n=Aa(),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(),ee[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===`
@@ -51,23 +51,23 @@ import{createRequire as e}from"node:module";import t from"node:process";import{U
51
51
  `).forEach((e,i)=>{i>0&&n.push([]);let a=n.at(-1);a.push({end:(a.at(-1)?.end??0)+B(e),free:!t[r]})})}),n.map(e=>t=>{let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i].end<=t?n=i+1:r=i}return e[n].free})}function*gm(e,t,n,r,i){if(n+r===0)return yield*e;let a=e.filter(e=>e.text!==``),o=e=>` `.repeat(e),s=G.getLineLength(a);if(s===0)return yield new G(o(n+r),i);let c=a.length-1,l=n>0&&a[0].cellLength>0&&t(0),u=r>0&&a[c].cellLength>0&&t(s-1),d=+!!l,f=u?c:c+1;if(d>f){yield new G(o(n)+a[0].text+o(r),i);return}n>0&&(yield new G(o(n)+(l?a[0].text:``),i)),yield*a.slice(d,f),r>0&&(yield new G((u?a[c].text:``)+o(r),i))}const _m=Object.freeze({name:`join`});function vm(e,t,n,r){let i=e.join(t,n,r);return{render:e=>G.anchorLines([[...hp(i,e)]],_m)[0]}}function ym(e){return{render:t=>G.anchorLines([[...hp(e,t)]],e)[0]}}var bm=class{items;joiner;constructor(e,t){this.items=e,this.joiner=t}*render(e){let t=this.items;if(t.length===0)return;let n={...e,justify:void 0};yield*hp(vm(this.joiner,null,t[0],{index:0}),n);for(let e=0;e<t.length;e++){let r=t[e];yield*hp(ym(r),n);let i=e+1<t.length?t[e+1]:null;yield*hp(vm(this.joiner,r,i,{index:e+1}),n)}yield G.line()}measure(e){let t=0;for(let n of hp(this,e))t+=n.cellLength;return{minimum:t,maximum:t}}};const xm=[`seam`,`lead`,`tail`];function*Sm(e){yield e,`mix`in e&&(yield*Sm(e.mix[0]),yield*Sm(e.mix[1]))}const Cm=e=>typeof e.glyph==`string`?[e.glyph]:e.glyph.oneOf,wm=(e,t,n,r)=>{let i=Cm(e);return i[Math.floor(parseInt(Xp(`${t}:${n}:${r}`),16)/2**32*i.length)]},Tm=e=>B(Cm(e)[0]??``);function Em(e,t,n){if(e===`ground`)return n(`mixes ground, whose colour is unknown`);let r=typeof e==`object`&&e?e:{};if((r.edge===`left`||r.edge===`right`)&&(r.part===`bg`||r.part===`fg`))return r.edge===t&&n(`names the ${t} neighbour, which this part is drawn without`),Object.freeze({edge:r.edge,part:r.part});if(typeof r.role==`string`)return Object.freeze({role:r.role});if(Array.isArray(r.mix)&&r.mix.length===3){let[e,i,a]=r.mix;return(typeof a!=`number`||!(a>=0&&a<=1))&&n(`mixes at ${String(a)}, outside 0..1`),Object.freeze({mix:Object.freeze([Em(e,t,n),Em(i,t,n),a])})}return n(`has a colour that is not a Paint: ${JSON.stringify(e)}`)}const Dm=(e,t,n)=>e===`ground`?e:Em(e,t,n),Om={seam:void 0,lead:`left`,tail:`right`},km={seam:`seam`,lead:`caps`,tail:`caps`};function Am(e,t,n,r){let i=e.glyph,a=typeof i==`object`&&i?i.oneOf:void 0;typeof i!=`string`&&!(Array.isArray(a)&&a.every(e=>typeof e==`string`))&&r(`has a glyph that is neither a string nor a oneOf of strings: ${JSON.stringify(i)}`),e.fg===`ground`&&e.bg===`ground`&&r(`has ground on both sides`);let o=Cm(e);return o.length===0&&r(`has an empty oneOf`),o.some(t=>B(t)!==Tm(e))&&r(`has oneOf members of different widths`),t===`ascii`&&!o.every(np)&&r(`is not ASCII`),Object.freeze({glyph:typeof e.glyph==`string`?e.glyph:Object.freeze({oneOf:Object.freeze([...o])}),fg:Dm(e.fg,Om[n],r),bg:Dm(e.bg,Om[n],r)})}function jm(e,t,n,r){let i=e,a=km[n];if(typeof i?.[t]!=`object`||i[t]===null)throw Error(`${a}: has no ${t} form`);let o=i[t][n];if(!Array.isArray(o))throw Error(`${a}: ${t} ${n} is not a list of cells`);return Object.freeze(o.map((e,i)=>{let o=e=>{throw Error(`${a}: ${t} ${n}[${i}] ${e}`)};return typeof e==`object`&&e?r(e,o):o(`is not a cell`)}))}const Mm=(e,t)=>(n,r)=>Am(n,e,t,r),Nm=(e,t)=>(n,r)=>{if(!(`cap`in n))return Am(n,e,t,r);let{cap:i}=n;return Object.keys(n).length!==1&&r(`names a cap and draws cells of its own; a cell is one or the other`),i===`lead`||i===`tail`?Object.freeze({cap:i}):r(`names a cap that is neither lead nor tail: ${JSON.stringify(i)}`)};function Pm(e){let t=t=>Object.freeze({seam:jm(e,t,`seam`,Nm(t,`seam`))});return Object.freeze({glyph:t(`glyph`),ascii:t(`ascii`)})}function Fm(e){let t=t=>Object.freeze({lead:jm(e,t,`lead`,Mm(t,`lead`)),tail:jm(e,t,`tail`,Mm(t,`tail`))});return Object.freeze({glyph:t(`glyph`),ascii:t(`ascii`)})}function Im(e,t){return{seam:e.seam.flatMap(e=>`cap`in e?t[e.cap]:[e]),lead:t.lead,tail:t.tail}}const Lm=(e,t)=>new Set([e.fg,e.bg].flatMap(e=>e===`ground`?[]:[...Sm(e)].flatMap(e=>`edge`in e&&e.edge===t?[e.part]:[]))),Rm=(e,t)=>e.some(e=>[e.fg,e.bg].some(e=>e!==`ground`&&[...Sm(e)].some(e=>`edge`in e&&e.edge===t&&e.part===`bg`)));function zm(e){let t=t=>e[t].map(e=>({cell:e,parts:{left:Lm(e,`left`),right:Lm(e,`right`)}}));return{shape:e,reads:{seam:{left:Rm(e.seam,`left`),right:Rm(e.seam,`right`)},lead:Rm(e.lead,`right`),tail:Rm(e.tail,`left`)},cells:{seam:t(`seam`),lead:t(`lead`),tail:t(`tail`)}}}function Bm(e){return e!==void 0&&!e.isDefault?e:void 0}function Vm(e){return e.flattenAlpha(Ul)}function Hm(e,t){if(e.isDefault||t.isDefault)return!0;let[n,r]=[e.fixedValue,t.fixedValue];return n!==void 0&&r!==void 0?Xu.fromRgba(n).deltaE(Xu.fromRgba(r))>=.04:e.number===void 0?e.name!==t.name:e.number!==t.number}const Um=.001;function*Wm(e){for(let t=1;t*Um<=1;t++)for(let n of[e.l+t*Um,e.l-t*Um])n>=0&&n<=1&&(yield new Xu(n,e.c,e.h))}function Gm(e,t,n){if(e===void 0||t===void 0)return e;let r=(e,n)=>new W({color:e,bgcolor:t}).drawnColors(n),{color:i,bgcolor:a}=r(e,n);if(Hm(i,a))return e;let o=r(e).color,s=i.fixedValue===void 0?H.STANDARD:H.TRUECOLOR;for(let e of Wm(Xu.fromRgba(o.getTruecolor()))){let t=r(U.fromRgba(e.toRgba()).downgrade(s),n).color;if(Hm(t,a))return t}throw Error(`no colour on the lightness ray of ${e.name} stands off ${t.name} at depth ${H[n]}`)}function Km(e,t,n){if(`edge`in e){let n=t[e.edge];if(e.part===`fg`)return n?.color;let r=Bm(n?.bgcolor);return r&&Vm(r)}if(`role`in e)return ip(n,e.role).color;let[r,i,a]=e.mix,o=Km(r,t,n),s=Km(i,t,n);return o&&s&&U.blend(o,s,a)}function qm(e,t,n){if(e.fg===`ground`)return new W({color:e.bg===`ground`?void 0:Km(e.bg,t,n),reverse:!0});let r=e.bg===`ground`?void 0:Km(e.bg,t,n);return new W({color:Gm(Km(e.fg,t,n),r,n.colorSystem??H.TRUECOLOR),bgcolor:r})}var Jm=class e{cell;parts;neighbours;edges;options;reads;follows;style;constructor(e,t,n,r,i){this.cell=e,this.parts=t,this.neighbours=n,this.edges=r,this.options=i;let a=e=>{if(t[e].size===0)return null;let[i,a]=[n[e],r[e]];if(i===null||a===void 0)throw Error(`a join cell paints with its ${e} neighbour's edge, and the join has no ${e} neighbour`);return{owner:i,edge:a}};this.reads={left:a(`left`),right:a(`right`)},this.follows=this.reads.left!==null||this.reads.right!==null,this.style=qm(e,r,i)}rederived(t,n,r){let i=e=>t[e]?.color!==void 0&&this.parts[e].has(`fg`)||t[e]?.bgcolor!==void 0&&this.parts[e].has(`bg`);if(!i(`left`)&&!i(`right`))return;let a=(e,t)=>t===void 0?e:new W({color:t.color??e?.color,bgcolor:t.bgcolor??e?.bgcolor}),o={left:a(this.edges.left,t.left),right:a(this.edges.right,t.right)},s=new e(this.cell,this.parts,this.neighbours,o,{...this.options,colorSystem:r}),c=e=>({...e,owner:e.owner===this?s:e.owner,inner:e.inner&&c(e.inner)});return{colors:s.style,style:n.withAnchor(n.anchor&&c(n.anchor))}}};function Ym(e){for(let t=e;t;t=t.inner)if(t.owner instanceof Jm)return t.owner}const Xm=e=>xm.flatMap(t=>e[t].flatMap(Cm)).join(``);var Zm=class{seam;caps;_forms;constructor(e,t){this.seam=Pm(e),this.caps=Fm(t),this._forms={glyph:zm(Im(this.seam.glyph,this.caps.glyph)),ascii:zm(Im(this.seam.ascii,this.caps.ascii))}}join(e,t,{index:n}){let r=this._forms;return{*render(i){let{cells:a,reads:o}=rp(i,r.glyph,r.ascii,e=>Xm(e.shape)),s={left:e?.edgeStyle(`right`,i),right:t?.edgeStyle(`left`,i)},c=Bm(s.left?.bgcolor),l=Bm(s.right?.bgcolor),u=e!==null&&(!o.seam.left||c!==void 0),d=t!==null&&(!o.seam.right||l!==void 0),f=d&&(!o.lead||l!==void 0),p=u&&(!o.tail||c!==void 0),m={left:e,right:t},h=e=>a[e].map(({cell:t,parts:r},a)=>{let o=new Jm(t,r,m,s,i);return new G(wm(t,e,n,a),o.style.withAnchor({owner:o,row:0,col:0,inner:void 0}))});if(!u||!d){(f||p)&&(yield*h(f?`lead`:`tail`));return}yield*h(`seam`)}}}};const Qm={edge:`left`,part:`bg`},$m={edge:`right`,part:`bg`},eh={edge:`left`,part:`fg`},Lee={mix:[Qm,$m,1/2]},th=`ground`,Ree={cap:`lead`},zee={cap:`tail`},nh=(e,t)=>({glyph:e,ascii:t}),rh={glyph:``,ascii:`>`},ih={glyph:``,ascii:`/`},ah={glyph:``,ascii:`\\`},oh={glyph:``,ascii:`}`},sh={glyph:``,ascii:`#`},ch={glyph:``,ascii:`]`},lh={glyph:``,ascii:`)`},uh=e=>({seam:[{glyph:e,fg:Qm,bg:$m}]}),dh=e=>nh(uh(e.glyph),uh(e.ascii));function fh(e){let t=e=>({mix:[Qm,$m,e]});return{seam:[{glyph:e,fg:Qm,bg:t(1/3)},{glyph:e,fg:t(1/3),bg:t(2/3)},{glyph:e,fg:t(2/3),bg:$m}]}}const ph=e=>({seam:[zee,...e,Ree]}),mh=(e,t)=>({seam:[{glyph:e,fg:t,bg:Lee}]}),hh=e=>mh({oneOf:e},Qm),gh={seam:[{glyph:` | `,fg:{role:`strip.separator`},bg:th}]},_h={glyph:` `,fg:eh,bg:th},vh=e=>({glyph:e,fg:{role:`strip.rail`},bg:th}),yh=Object.freeze({powerline:Pm(dh(rh)),prism:Pm(nh(fh(rh.glyph),fh(rh.ascii))),slant:Pm(dh(ih)),backslant:Pm(dh(ah)),flame:Pm(dh(oh)),pixel:Pm(dh(sh)),ice:Pm(dh(ch)),bubble:Pm(dh(lh)),capsule:Pm(nh(ph([_h]),ph([_h]))),wrapper:Pm(nh(ph([]),ph([]))),metro:Pm(nh(ph([vh(`──`)]),ph([vh(`--`)]))),stitch:Pm(nh(mh(`┊`,eh),mh(`:`,eh))),torn:Pm(nh(hh([`▚▞`,`▞▚`,`▘▗`,`▝▖`,`▖▝`,`▗▘`]),hh([`/\\`,`\\/`]))),plain:Pm(nh(gh,gh))}),bh=e=>nh({lead:[{glyph:e.glyph,fg:th,bg:$m}],tail:[{glyph:e.glyph,fg:Qm,bg:th}]},{lead:[],tail:[{glyph:e.ascii,fg:Qm,bg:th}]}),xh=(e,t)=>({lead:[{glyph:e,fg:$m,bg:th}],tail:[{glyph:t,fg:Qm,bg:th}]}),Sh={lead:[],tail:[]},Ch=Object.freeze({powerline:Fm(bh(rh)),slant:Fm(bh(ih)),backslant:Fm(bh(ah)),flame:Fm(bh(oh)),pixel:Fm(bh(sh)),ice:Fm(bh(ch)),bubble:Fm(bh(lh)),capsule:Fm(nh(xh(``,``),xh(`(`,`)`))),wrapper:Fm(nh(xh(``,``),xh(`<`,`>`))),flat:Fm(nh(Sh,Sh))}),wh=Object.freeze({powerline:new Zm(yh.powerline,Ch.powerline),prism:new Zm(yh.prism,Ch.powerline),slant:new Zm(yh.slant,Ch.slant),backslant:new Zm(yh.backslant,Ch.backslant),flame:new Zm(yh.flame,Ch.flame),pixel:new Zm(yh.pixel,Ch.pixel),ice:new Zm(yh.ice,Ch.ice),bubble:new Zm(yh.bubble,Ch.bubble),capsule:new Zm(yh.capsule,Ch.capsule),wrapper:new Zm(yh.wrapper,Ch.wrapper),metro:new Zm(yh.metro,Ch.capsule),stitch:new Zm(yh.stitch,Ch.flat),torn:new Zm(yh.torn,Ch.flat),plain:new Zm(yh.plain,Ch.flat)});function Th(e,t){let n=t.reducedMotion?e.style?.reduced():e.style;return n===e.style?e:new G(e.text,n,e.control)}function Eh(e,t){if(e.isControl)return``;let{text:n,style:r}=Th(e,t);if(n.length===0||r===void 0)return n;let i=t.colorSystem===null?``:r.toSgrCodes(t.colorSystem),a=i.length>0?`\x1b[${i}m${n}\x1b[0m`:n,o=t.hyperlinks?r.link:void 0;return o===void 0?a:`${$p(o)}${a}]8;;\\`}function Dh(e,t){let n=[];for(let r of e)n.push(Eh(r,t));return n.join(``)}function Oh(e){return e.end=``,e.plain=e.plain.replaceAll(`
52
52
  `,` `),e.expandTabs()}const kh={lastChange:-1/0,nextChange:1/0};var Ah=class{renderable;effect;t;key;theme;constructor(e,t,n){this.renderable=e,this.effect=t,this.t=kf(`Effected`,n.t),this.key=n.key,this.theme=n.theme}render(e){return this.moved(e).segments}moved(e){let t=hp(this.renderable,e);if(e.colorSystem===null)return{segments:t,hold:kh};let n=e.colorSystem??H.TRUECOLOR,r=Ph(t,n,this.theme),i=Lh(r),a=Tp(this.effect(Bh(r,()=>i,n,this.theme)),this.t,e);return{segments:this._recolored(i,a.value,n),hold:Ep(a,this.t)}}*_recolored(e,t,n){let r=e.map(({look:e,glyphs:n})=>{if(e===void 0)return;let r=Ym(e.style.anchor);if(r?.follows===!0)return{joined:r};let i={fg:e.pair.fg,bg:e.pair.bg,attributes:e.attributes},{terminal:a,reverse:o}=e.pair;return{painted:n.map(({cell:e})=>e===void 0?i:qh(t(i,{...e,seed:Mh(this.key,e.row,e.col),terminal:a,reverse:o})))}}),i=Rh(e,r);for(let[a,{segment:o,look:s,glyphs:c}]of e.entries()){let e=r[a];s===void 0||e===void 0?yield o:`joined`in e?yield this._rejoined(o,s,e.joined,c,i,t,n):yield*this._repainted(o,s,c,e.painted,n)}}*_repainted(e,t,n,r,i){let{style:a,wire:o,slots:s,pair:c,attributes:l}=t,u=[];for(let[e,{glyph:t}]of n.entries()){let n=r[e],a=Hh(n,c.reverse),l=u[u.length-1],d=l!==void 0&&Qh(l.colors,a)?l.drawn:this.respec(o,s,a,i);l!==void 0&&Wh(l.drawn,d)&&Xh(l.attributes,n.attributes)?(l.text+=t,l.cells+=B(t),l.colors=a):u.push({text:t,cells:B(t),colors:a,attributes:n.attributes,drawn:d})}if(u.every(e=>Wh(e.drawn,o)&&Xh(e.attributes,l))){yield e;return}let d=0;for(let e of u){let t=a.shiftedBy(d),n=Xh(e.attributes,l)?t:t.withAttributes(Yh(e.attributes)),r=Wh(e.drawn,o)?n:n.add(W.fromColor(e.drawn.color,e.drawn.bgcolor));yield new G(e.text,r),d+=e.cells}}_rejoined(e,t,n,r,i,a,o){let s=r.flatMap(({cell:e})=>e===void 0?[]:[e]),[c]=s;if(c===void 0)return e;let{theme:l}=this,u=new Set,d=(e,t)=>{if(!e?.isDefault)return e;let n=U.fromRgba(e.getTruecolor(l,t));return u.add(n),n},f=(e,t)=>{let n=Uh(e,t,o,l);return n.fg===void 0&&n.bg===void 0?void 0:{color:d(n.fg,!0),bgcolor:d(n.bg,!1)}},p=e=>{let t=e.drawnColors(o),n={fg:(t.color??Nh).getTruecolor(l,!0),bg:(t.bgcolor??Nh).getTruecolor(l,!1)},r={fg:t.color?.isDefault??!0,bg:t.bgcolor?.isDefault??!0};return f(n,qh(a({...n,attributes:Yh(e)},{...c,seed:Mh(this.key,c.row,c.col),terminal:r,reverse:!1})))},m=e=>{let t=n.reads[e];if(t===null)return;let r=i(s,e,t.owner);return r===void 0?p(t.edge):f(r.look.slots,Hh(r.moved,r.look.pair.reverse))},h=n.rederived({left:m(`left`),right:m(`right`)},t.style,o);if(h===void 0)return e;let{colors:g,style:_}=h,v=n.style,y=g.drawnColors(o),{wire:b,slots:x}=t,S=this.respec(b,x,{fg:g.color?.getTruecolor(l,!0)??x.fg,bg:g.bgcolor?.getTruecolor(l,!1)??x.bg},o),C=(e,t,n,r,i)=>{if(Zh(e,t))return n;if(e===void 0)throw Error(`a seam cell resolved to ${t?.name??`nothing`} when drawn and to nothing after an effect moved its neighbours`);return u.has(e)?i:r},w={color:C(g.color,v.color,b.color,y.color,S.color),bgcolor:C(g.bgcolor,v.bgcolor,b.bgcolor,y.bgcolor,S.bgcolor)};return new G(e.text,Wh(w,b)?_:_.add(W.fromColor(w.color,w.bgcolor)))}measure(e){return Sp.get(e,this.renderable)}respec(e,t,n,r){let i=Uh(t,n,r,this.theme);return{color:i.fg??e.color,bgcolor:i.bg??e.bgcolor}}},jh=class e{renderable;effect;key;theme;constructor(e,t,n){this.renderable=e,this.effect=t,this.key=n.key,this.theme=n.theme}at(e){return new Ah(this.renderable,this.effect,{t:e,key:this.key,theme:this.theme})}nextChange(e){return e}lastChange(e){return e}reduced(){let{effect:t}=this;return new e(this.renderable,e=>t(e).reduced(),this)}render(e){let{segments:t,hold:n}=this.at(kp(e)).moved(e);return Op(t,n)}measure(e){return Sp.get(e,this.renderable)}static shows(e,t,n,r){let i=Hh(e,e.reverse),a=Uh(i,Hh(t,e.reverse),n,r);return Hh({fg:a.fg?.getTruecolor(r,!0)??i.fg,bg:a.bg?.getTruecolor(r,!1)??i.bg},e.reverse)}};function Mh(e,t,n){return Number.parseInt(Xp(`${e}:${t}:${n}`),16)/4294967296}const Nh=U.default();function Ph(e,t,n){return[...e].map(e=>{if(e.isControl)return{segment:e,look:void 0};let r=e.style??W.null(),i=r.drawnColors(t),a={fg:(i.color??Nh).getTruecolor(n,!0),bg:(i.bgcolor??Nh).getTruecolor(n,!1)},o=r.reverse===!0,s=Hh({fg:i.color?.isDefault??!0,bg:i.bgcolor?.isDefault??!0},o);return{segment:e,look:{style:r,wire:i,slots:a,pair:{...Hh(a,o),terminal:s,reverse:o},attributes:Yh(r),seam:zf(r.anchor,_m)}}})}function Fh(e){let t=0,n=0;return e.map(e=>{if(e.isControl)return[];let r=e.style?.anchor,i=0;return[...Ml(e.text)].map(e=>{let a=e===`
53
53
  `?void 0:{row:t,col:n,anchor:r&&Rf(r,i)},o=B(e);return[t,n]=e===`
54
- `?[t+1,0]:[t,n+o],i+=o,{glyph:e,cell:a,width:o}})})}function Ih(e){return e.trim()!==``}function Lh(e){let t=Fh(e.map(({segment:e})=>e));return e.map((e,n)=>({...e,glyphs:t[n]}))}function Rh(e,t){let n,r=()=>{let n=new Map;return e.forEach(({look:e,glyphs:r},i)=>{let a=t[i];if(e===void 0||a===void 0||!(`painted`in a))return;let o=a.painted;r.forEach(({cell:t},r)=>{if(t===void 0)return;let i=n.get(t.row)??[];i.push({col:t.col,anchor:t.anchor,look:e,moved:o[r]}),n.set(t.row,i)})}),n};return(e,t,i)=>{let a=(n??=r()).get(e[0].row)??[],o=e[0].col,s=e[e.length-1].col;if(t===`right`)return a.find(e=>e.col>s&&zf(e.anchor,i));for(let e=a.length-1;e>=0;e--){let t=a[e];if(t.col<o&&zf(t.anchor,i))return t}}}function zh(e){return[e.underline,e.underline2,e.strike,e.overline,e.frame,e.encircle].some(e=>e===!0)}function Bh(e,t,n,r){let i=r.backgroundColor.hex,a,o=()=>t().flatMap(({look:e,glyphs:t})=>{if(e===void 0)return[];let n=e.pair.bg.hex!==i||zh(e.style);return t.flatMap(({glyph:t,cell:r,width:i})=>r===void 0?[]:[{cell:{...r,width:i,pair:e.pair,seam:e.seam},shows:Ih(t)||n}])}),s=()=>a??=o(),c,l,u=e.flatMap(({segment:e,look:t})=>t!==void 0&&Ih(e.text)&&!t.seam?[t.pair]:[]),d=[...new Map(u.map(e=>[`${e.fg.hex}/${e.bg.hex}/${e.terminal.fg}/${e.terminal.bg}/${e.reverse}`,e])).values()],f=e=>d.flatMap(t=>t.terminal[e]?[]:[t[e].hex]);return{all:()=>c??=s().map(({cell:e})=>e),cells:()=>l??=s().flatMap(({cell:e,shows:t})=>t?[e]:[]),pairs:d,colors:new Set([...f(`fg`),...f(`bg`)]),fills:new Set(f(`bg`)),depth:n,theme:r}}function Vh(e,...t){let n=new Set(t),r=e=>{for(let t=e.anchor;t;t=t.inner)if(n.has(t.owner))return!0;return!1},i=e=>({...e,all:()=>e.all().filter(r),cells:()=>e.cells().filter(r)});return t=>K.map(e(i(t)),e=>(t,n)=>r(n)?e(t,n):t)}function Hh(e,t){return t?{fg:e.bg,bg:e.fg}:e}function Uh(e,t,n,r){let i=t.bg.compositeOver(Ul),a=t.fg.compositeOver(i);return{fg:U.matchMove(e.fg,a,n,r,!0),bg:U.matchMove(e.bg,i,n,r,!1)}}function Wh(e,t){return Gh(e.color,t.color,!0)&&Gh(e.bgcolor,t.bgcolor,!1)}function Gh(e,t,n){return e===t||Kh(e,n)===Kh(t,n)}function Kh(e,t){return e?.getAnsiCodes(t).join(`;`)??``}function qh(e){if(e.attributes===void 0)throw TypeError(`an effect frame returns the look it was handed with its changes, { ...look, fg, bg }: this one returned no attributes`);return e}const Jh=Vf.filter(e=>e!==`reverse`);function Yh(e){return Object.fromEntries(Jh.map(t=>[t,e[t]]))}function Xh(e,t){return e===t||Jh.every(n=>e[n]===t[n])}function Zh(e,t){return e===t||e!==void 0&&t!==void 0&&e.type===t.type&&e.name===t.name}function Qh(e,t){return $h(e.fg,t.fg)&&$h(e.bg,t.bg)}function $h(e,t){return e.red===t.red&&e.green===t.green&&e.blue===t.blue&&e.alpha===t.alpha}const eg=(()=>{let e=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];return[...e,...e]})(),tg=e=>e*e*e*(e*(e*6-15)+10),ng=(e,t,n)=>e+n*(t-e);function rg(e,t,n,r){let i=e&15,a=i<8?t:n,o=i<4?n:i===12||i===14?t:r;return(i&1?-a:a)+(i&2?-o:o)}function ig(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=Math.floor(n),o=r&255,s=i&255,c=a&255;e-=r,t-=i,n-=a;let l=tg(e),u=tg(t),d=tg(n),f=eg[o]+s,p=eg[f]+c,m=eg[f+1]+c,h=eg[o+1]+s,g=eg[h]+c,_=eg[h+1]+c;return ng(ng(ng(rg(eg[p],e,t,n),rg(eg[g],e-1,t,n),l),ng(rg(eg[m],e,t-1,n),rg(eg[_],e-1,t-1,n),l),u),ng(ng(rg(eg[p+1],e,t,n-1),rg(eg[g+1],e-1,t,n-1),l),ng(rg(eg[m+1],e,t-1,n-1),rg(eg[_+1],e-1,t-1,n-1),l),u),d)}function ag(e,t,n,r){let i=0,a=1,o=0;for(let s=0;s<r;s++){let r=2**s;i+=a*ig(e*r,t*r,n*r),o+=a,a/=2}return i/o}function og(e,t){let n=Math.sin(e*12.9898+t*78.233)*43758.5453;return n-Math.floor(n)}function sg(e,t,n){let r=Math.min(1,Math.max(0,(n-e)/(t-e)));return r*r*(3-2*r)}const cg=Array.from({length:48},(e,t)=>(t+1)/48);function lg(e,t){return Math.min(Gl(e.fg,e.bg),4.5)-(t===H.TRUECOLOR?.01:0)}const ug=[`fg`,`bg`];function dg({pairs:e,depth:t,theme:n},r,i){let a=(e,t)=>e.terminal[t]?void 0:e[t].hex,o=new Map(e.flatMap(e=>ug.flatMap(t=>{let n=a(e,t);return n===void 0?[]:[[n,e[t]]]}))),s=new Map([...r].filter(e=>!o.has(e)).map(e=>[e,1])),c=e=>Xu.fromRgba(o.get(e)).l;for(let l of[...r].filter(e=>o.has(e)).sort((e,t)=>c(t)-c(e))){let r=e.flatMap(e=>{let t=ug.find(t=>a(e,t)===l);if(t===void 0)return[];let n=a(e,t===`fg`?`bg`:`fg`);return[[e,t,n===void 0?0:s.get(n)??0]]}),o=e=>r.every(([r,a,o])=>{let s=lg(r,t),c=(t,n)=>vg(i,r[t],(t===a?e:o)*n);return cg.every(e=>{let i=jh.shows(r,{fg:c(`fg`,e),bg:c(`bg`,e)},t,n);return Gl(i.fg,i.bg)>=s})}),[c,u]=o(1)?[1,1]:[0,1];for(let e=0;e<20&&u-c>.001;e++){let e=(c+u)/2;[c,u]=o(e)?[e,u]:[c,e]}s.set(l,c)}return s}function fg(e,t){let n=new _l;return gg(hg(e,r=>{let i=t??r.colors,a=[pg(r),`|`,...i].join(` `);return n.get(r.theme,()=>new gl).get(a,()=>dg(r,i,e.touch))}))}function pg({depth:e,pairs:t}){return[e,...t.map(mg)].join(` `)}function mg({fg:e,bg:t,terminal:n,reverse:r}){return`${e.hex}/${t.hex}/${n.fg}/${n.bg}/${r}`}function hg(e,t){return n=>{let r=t(n);return K.continuous(t=>{let i=e.field(t,n);return(t,n)=>{let a=Math.round(Cg(i(n))*48)/48,o=(t,n)=>vg(e.touch,t,(n?0:r.get(t.hex)??0)*a);return{...t,fg:o(t.fg,n.terminal.fg),bg:o(t.bg,n.terminal.bg)}}})}}function gg(e){return t=>_g(t.depth)?K.constant(e=>e):e(t)}function _g(e){switch(e){case H.DEFAULT:case H.STANDARD:case H.WINDOWS:return!0;case H.EIGHT_BIT:case H.TRUECOLOR:return!1}}function vg(e,t,n){return n===0?t:e(t,n)}function yg(e){if(!(Number.isFinite(e.seconds)&&e.seconds>0))throw RangeError(`curve: seconds must be a positive number of seconds, got ${e.seconds}`);if(!(e.swing>=0&&e.swing<=1))throw RangeError(`curve: swing must be in [0, 1], got ${e.swing}`)}function bg(e,t){if(!Number.isFinite(t))throw RangeError(`${e} z must be a finite place in the noise, got ${t}`)}const xg={shimmer:{seconds:109,ease:wf.linear,swing:.9},pulse:{seconds:43,ease:wf.linear,swing:.85},sparkle:{seconds:139,ease:wf.linear,swing:.95},wheel:{seconds:907,ease:wf.linear,swing:1},fade:{seconds:20,ease:wf[`ease-in-out`],swing:1},dissolve:{seconds:30,ease:wf[`ease-in-out`],swing:1}},Sg={sun:new V(255,228,176),firefly:new V(222,245,140)},Cg=e=>Math.min(1,Math.max(0,e));function wg(e,t,n){if(!(n>=0&&n<=1))throw RangeError(`blend: w must be in [0, 1]; got ${n}`);let r=Math.PI/180,i=(1-n)*e.c*Math.cos(e.h*r)+n*t.c*Math.cos(t.h*r),a=(1-n)*e.c*Math.sin(e.h*r)+n*t.c*Math.sin(t.h*r);return new Xu((1-n)*e.l+n*t.l,Math.hypot(i,a),Math.atan2(a,i)/r,e.alpha)}function Tg(e){let t=Xu.fromRgba(e);return(e,n)=>{let r=Xu.fromRgba(e);return wg(r,new Xu(Math.max(r.l,t.l),t.c,t.h,t.alpha),n).toRgba()}}const Eg=(e,t)=>t*e[e.length-1][0];function Dg(e,t,n){let r=t/n,i=e.findIndex(([e])=>r<e);if(!(r>0)||i<0)return 0;let[a,o]=i===0?[0,0]:e[i-1],[s,c]=e[i];return n*(o+(c-o)*(1-Math.cos(Math.PI*(r-a)/(s-a)))/2)}function Og(e,t,n){let r=Eg(e,n),i=t=>{let r=0;for(let i=0;i<24;i++)r+=Dg(e,(i+.5)/24*t,n);return r*t};return i(Math.min(Math.max(t,0),r))/i(r)}const kg=[[.24,1],[.6,0]];function Ag(e,t,n){yg(e),bg(`pulse`,n);let r=.9+.2*og(n,3.1),i=t=>.1*ig(t/(3*e.seconds),.5,.5+n),a=i(0);return{touch:Tg(t),field:t=>{let o=r*t/e.seconds+i(t)-a,s=Math.floor(o),c=.7+.3*sg(-.5,.5,ig(s*.37,2.1,n)),l=.5-.5*Math.cos(2*Math.PI*(o-s)),u=e.swing*e.ease(c*l);return()=>u}}}const jg=e=>Math.abs(e)>=1?0:(1-e*e)**3;function Mg(e,t,n,r){yg(e),bg(`shimmer`,r);let i=e.seconds,a=i/2,o=e=>sg(-.4,.4,ig(e/7,3.3,5.5+r)),s=.7,c=.51,l=.4,u=(e,n,u)=>{let d=o(e),f=(og(e,7.5+r)<.35+.6*d)*(.3+.7*d*(.6+.4*og(e,8.5+r))),p=i*u/80*(c+l*og(e,5.5+r)),m=Cg((n-(e+s*og(e,6.5+r))*a)/p);return{strength:f,centre:m*u-t+.06*u*Math.sin(Math.PI*m)*ig(m,2.7,e+r)}},d=(e,t)=>{let n=s+(c+l)*i*t/80/a,r=Math.floor(e/a),o=[];for(let i=Math.max(0,Math.ceil(r-n));i<=r;i++)o.push(u(i,e,t));return o},f=(e,t,n)=>Math.exp(-((ig(e,t,n)/.8)**2));return{touch:Tg(n),field:(n,i)=>{let[a,o]=zg(i.cells().map(e=>e.col)),s=d(n,o-a+1+2*t);return i=>{let o=0;for(let{strength:e,centre:n}of s)o=Math.max(o,e*jg((i.col-a-n)/t));let c=i.row+r,l=.8*ig(i.col*.05,c*.3+1.3,n*.02),u=(f(i.col*.21+l,c*.9,n*.022)*f(i.col*.33+9.1-l,c*.7,n*.018+4.2))**2;return e.swing*e.ease(o*(.1+.6*u))}}}}function Ng(e,t,n){yg(e),bg(`sparkle`,n);let r=e.seconds,i=22.1,a=3.1,o=(e,t,i,a,o)=>{let s=e*4.9+t*31.7+.3+n,c=e+.5+.7*ig(e*1.7+.2,.3+t*2.9,.5+n),l=i+og(e+t*1013,.7+n)*r,u=Math.floor(l/r),d=og(u,s+1)<.15?0:1,f=.5+.5*og(u,s+2),p=og(u,s+3)*(1-Eg(kg,f)),m=l/r-u-p;return{x:a+c*8+5*(2*og(u,s+4)-1)+5*f*(2*og(u,s+5)-1)*Og(kg,m,f)+1.5*ig(s,.1,i*.035),y:o+t*3+.6*ig(s,2.2,i*.035),glow:d*Dg(kg,m,f)}};return{touch:Tg(t),field:(t,n)=>{let r=n.cells(),[s,c]=zg(r.map(e=>e.col)),[l,u]=zg(r.map(e=>e.row)),d=e=>(e-s)/8-.5,f=e=>(e-l)/3,[p,m]=[Math.ceil(d(s-i)),Math.floor(d(c+i))],[h,g]=[Math.ceil(f(l-a)),Math.floor(f(u+a))],_=Array.from({length:g-h+1},(e,n)=>Array.from({length:m-p+1},(e,r)=>o(p+r,h+n,t,s,l)));return t=>{let n=0,[r,o]=[Math.max(p,Math.ceil(d(t.col-i))),Math.min(m,Math.floor(d(t.col+i)))],[s,c]=[Math.max(h,Math.ceil(f(t.row-a))),Math.min(g,Math.floor(f(t.row+a)))];for(let e=s;e<=c;e++)for(let i=r;i<=o;i++){let r=_[e-h][i-p];n=Math.max(n,r.glow*jg(Math.hypot(t.col-r.x,2*(t.row-r.y))/5))}return e.swing*e.ease(n)}}}}function Pg(e,t){return n=>{let r=Xu.fromRgba(n.theme.backgroundColor);return K.continuous(i=>{let a=e(i,n);return(e,n)=>{let i=t*(1-Cg(a(n)));if(i===0)return e;let o=wg(Xu.fromRgba(e.bg),r,i);return{...e,fg:wg(Xu.fromRgba(e.fg),o,i).toRgba(),bg:o.toRgba()}}})}}function Fg(e){return t=>Cg(.5+1.1*ag(t.col*.09+1.4*ig(t.col*.035,t.row*.2+2.6,e+.5),t.row*.45,e,3))}var Ig=class{effect;schedule;constructor(e,t){this.effect=e,this.schedule=t}done(e){return K.done(this.schedule,e)}};function Lg(e,t){let n=K.of({...K.sequence(K.continuous(()=>void 0),e,K.constant(void 0)),reduced:()=>K.cut(void 0,void 0)}),r=new Ig(i=>{let a=t(i);return K.of({at:e=>a.at(e),nextChange:e=>r.done(e)?1/0:a.nextChange(e),lastChange:e=>r.done(e)?n.lastChange(e):a.lastChange(e),reduced:()=>K.cut(a.at(0),a.at(e))})},n);return r}function Rg(e,t){return(n,r)=>{let[i,a]=zg(r.map(t)),o=(a>i?.55:0)*e.seconds,s=Lf.once(0,e.seconds-o);return e=>{let r=a>i?Cg((t(e)-i)/(a-i)):0;return{along:r,progress:s(n-r*o)}}}}function zg(e){let t=e[0]??0,n=t;for(let r of e)t=Math.min(t,r),n=Math.max(n,r);return[t,n]}function Bg(e,t){yg(e),bg(`fadeIn`,t);let n=Rg(e,Fg(1.7+t));return Lg(e.seconds,Pg((t,r)=>{let i=n(t,r.cells());return t=>e.ease(i(t).progress)},e.swing))}const Vg={depth:.4,from:.5,to:.95,maskFrom:.35,maskTo:.75,late:.6};function Hg(e,t){yg(e),bg(`dissolveOut`,t);let n=Fg(9.3+t),r=Rg(e,Fg(4.2+t)),{depth:i,from:a,to:o,maskFrom:s,maskTo:c,late:l}=Vg;return Lg(e.seconds,Pg((t,u)=>{let d=r(t,u.cells());return t=>{let{along:r,progress:u}=d(t),f=e.ease(u),p=Cg((f-a)/(o-a)),m=i*sg(s,c,n(t))*(1-l+l*r)*Math.sin(Math.PI*p)**2;return 1-f+m}},e.swing))}const Ug=[211,337],Wg=(e,t)=>({row:e.row,centre:e.col+t/2});function Gg(e){let{colors:t}=e,n=(e,t)=>`${e}:${t}`,r=new Map,i=new Set,a=e=>{if(e.seam)return;let n=(e,n)=>!e&&t.has(n)?n:void 0;return n(e.pair.terminal.bg,e.pair.bg.hex)??n(e.pair.terminal.fg,e.pair.fg.hex)},o=[],s=new Map;for(let t of e.all()){r.set(n(t.row,t.col),t);let e=a(t);for(let r=t.col;r<t.col+t.width;r++)t.seam&&i.add(n(t.row,r)),e!==void 0&&(s.set(n(t.row,r),o.length),o.push({row:t.row,col:r,hex:e}))}let c=o.map((e,t)=>t),l=e=>{for(;c[e]!==e;)c[e]=c[c[e]],e=c[e];return e},u=(e,t,r)=>{let i=s.get(n(t,r));i!==void 0&&o[i].hex===o[e].hex&&(c[l(e)]=l(i))};o.forEach(({row:e,col:t},n)=>{u(n,e,t-1),u(n,e-1,t)});let d=new Map;o.forEach(({row:e,col:t,hex:n},r)=>{let i=l(r),a=d.get(i);a===void 0?d.set(i,{hex:n,top:e,bottom:e,left:t,right:t}):[a.top,a.bottom,a.left,a.right]=[Math.min(a.top,e),Math.max(a.bottom,e),Math.min(a.left,t),Math.max(a.right,t)]});let f=(e,t)=>{let r=s.get(n(e,t));return r===void 0?void 0:d.get(l(r))},p=e=>({row:(e.top+e.bottom)/2,centre:(e.left+e.right+1)/2}),m=(e,t,r)=>{let a=t;for(;i.has(n(e,a));)a+=r;return f(e,a)};return(e,t)=>{let i=r.get(n(e.row,e.col)),a=i?.width??1,o=(i?.seam===!0?[m(e.row,e.col-1,-1),m(e.row,e.col+a,1)]:[]).find(e=>e?.hex===t)??f(e.row,e.col);return o===void 0?Wg(e,a):p(o)}}function Kg(e,t){yg(e),bg(`wheel`,t);let n=e.seconds,r=({row:e,centre:n},r)=>ig(r/Ug[0],n/24+5.9,t+e/24+2.3)+.5*ig(r/Ug[1],n/24+97.3,t+e/24+7.1),i=(t,i)=>360*i/n+e.swing*180*((r(t,i)-r(t,0))/1.5),a=new _l;return gg(e=>{let{colors:t,fills:n,depth:r,theme:o}=e,s=(e,n)=>!e&&t.has(n.hex),c=(e,t,r)=>n.has(e.hex)||!r?e.hex:t.hex,l=(e,t)=>`${e.hex} ${t}`,u=a.get(o,()=>new gl).get(pg(e),()=>Qg(e.pairs,r,(e,t)=>{let n=t===`fg`?`bg`:`fg`;return s(e.terminal[t],e[t])?l(e[t],c(e[t],e[n],s(e.terminal[n],e[n]))):void 0})),d=t_(r,o),f=Gg(e);return K.continuous(e=>{let t=new Map,n=(t,n,a)=>{let o=qg(t,i(a,e));return n_(o.looks,t,r===H.TRUECOLOR?o.either.map($g):d,u.get(l(t,n))??Yg)},a=(e,r,i)=>{let a=`${l(e,r)} ${i.row}:${i.centre}`,o=t.get(a)??n(e,r,i);return t.set(a,o),o};return(e,t)=>{let n={fg:s(t.terminal.fg,e.fg),bg:s(t.terminal.bg,e.bg)},r=(e,n,r,i)=>n?a(e,c(e,r,i),f(t,e.hex)):e;return{...e,fg:r(e.fg,n.fg,e.bg,n.bg),bg:r(e.bg,n.bg,e.fg,n.fg)}}})})}function qg(e,t){if(t===0)return{looks:e,either:[e]};let n=Xu.fromRgba(e),r=Wl(e),i=e=>new Xu(e,n.c,n.h+t,n.alpha).toRgba(),[a,o]=[0,1];for(let e=0;e<24;e++){let e=(a+o)/2;[a,o]=Wl(i(e))<r?[e,o]:[a,e]}return{looks:i(o),either:[i(a),i(o)]}}const Jg=e=>Math.log(Gl(e,new V(0,0,0))),Yg={lo:-1/0,hi:1/0},Xg={lo:1/0,hi:-1/0},Zg=Math.log(1.031);function Qg(e,t,n){let r=new Map;for(let i of e.filter(e=>lg(e,t)>1)){let e=(Math.log(Gl(i.fg,i.bg))-Math.log(lg(i,t)))/ug.filter(e=>n(i,e)!==void 0).length;for(let t of ug){let a=n(i,t);if(a===void 0)continue;let[o,s]=[Jg(i[t]),Jg(i[t===`fg`?`bg`:`fg`])],{lo:c,hi:l}=r.get(a)??Yg;r.set(a,o>=s?{lo:Math.max(c,o-e),hi:l}:{lo:c,hi:Math.min(l,o+e)})}}return new Map([...r].map(([e,{lo:t,hi:n}])=>[e,n-t<Zg?Xg:{lo:t,hi:n}]))}const $g=e=>({color:e,looks:Xu.fromRgba(e),stop:Jg(e)}),e_=new _l;function t_(e,t){return e_.get(U.indexed(e,t),e=>e.map(([,e])=>$g(e)))}function n_(e,t,n,{lo:r,hi:i}){return r_(e,[$g(t),...n.filter(({stop:e})=>e>=r&&e<=i)]).color}function r_(e,t){let n=Xu.fromRgba(e),r;for(let e of t){let t=n.deltaE(e.looks);(r===void 0||t<r[1])&&(r=[e,t])}return r?.[0]}function i_({attribute:e,off:t,on:n}){let r=If([t,n]),i=[e=>e,t=>({...t,attributes:{...t.attributes,[e]:!0}})];return()=>K.map(r,e=>i[e])}const a_={blink:{attribute:`conceal`,off:.5,on:.5},boldPulse:{attribute:`bold`,off:.7,on:.3}},o_={loops:{shimmer:(e,t=xg.shimmer)=>fg(Mg(t,24,Sg.sun,e.z)),pulse:(e,t=xg.pulse)=>fg(Ag(t,Sg.sun,e.z)),sparkle:(e,t=xg.sparkle)=>fg(Ng(t,Sg.firefly,e.z)),wheel:(e,t=xg.wheel)=>Kg(t,e.z)},transitions:{fade:(e,t=xg.fade)=>Bg(t,e.z),dissolve:(e,t=xg.dissolve)=>Hg(t,e.z)},attributes:{blink:()=>i_(a_.blink),boldPulse:()=>i_(a_.boldPulse)}};function s_(e,t){let n=0,r=Fh(e).map(e=>e.map(({glyph:e,cell:r})=>({glyph:e,cell:r&&{...r,glyph:e,index:n++,seed:Mh(t,r.row,r.col)}})));return{placed:r,cells:r.flatMap(e=>e.flatMap(({cell:e})=>e===void 0?[]:[e]))}}function c_(e,t){let n=e.map(e=>e.map(({glyph:e,cell:n})=>n===void 0?e:f_(t,n)));return p_(e.flat(),n.flat()),n}function l_(e,t,n){let{placed:r,cells:i}=s_([new G(e.plain)],n.key);return K.map(t({cells:i,asciiOnly:n.asciiOnly}),t=>u_(e,r[0],c_(r,t)[0]))}function u_(e,t,n){if(n.every((e,n)=>e===t[n].glyph))return e;let r=[0],i=[0];t.forEach(({glyph:e},t)=>{r.push(r[t]+e.length),i.push(i[t]+n[t].length)});let a=e=>{let a=0;for(;a+1<r.length&&r[a+1]<=e;)a++;return a===t.length?i[a]:i[a]+Math.min(e-r[a],n[a].length)},o=e.blankCopy(n.join(``));for(let t of e.spans)o.stylize(t.style,a(t.start),a(t.end));return o}const d_=vl(/[\n\t]/);function f_(e,t){let n=e(t);if(n===t.glyph)return n;if(B(n)!==B(t.glyph)||d_.test(n)||im(n)!==n)throw RangeError(`a glyph effect turned ${JSON.stringify(t.glyph)} at row ${t.row}, column ${t.col} into ${JSON.stringify(n)}: it must be ${B(t.glyph)} cell(s) wide, with no line break or control character`);return n}function p_(e,t){let n=n=>e[n]?.cell===void 0?``:t[n];t.forEach((t,r)=>{let{glyph:i,cell:a}=e[r];if(a===void 0||t===i)return;let[o,s]=[n(r-1),n(r+1)];if(Ml(o+t+s).length!==Ml(o).length+Ml(t).length+Ml(s).length)throw RangeError(`a glyph effect turned ${JSON.stringify(i)} at row ${a.row}, column ${a.col} into ${JSON.stringify(t)}, which joins the cell beside it into one character`)})}function m_(e){return` `.repeat(B(e))}function h_(e){let t=new Map;for(let n of e.filter(e=>Ih(e.glyph)))t.set(n.row,{first:t.get(n.row)?.first??n.index,last:n.index});let n=new Map;for(let r of e){let e=t.get(r.row);e!==void 0&&r.index>=e.first&&r.index<=e.last&&B(r.glyph)>0&&n.set(r.index,n.size)}return{length:n.size,place:n}}function g_(e,t){return Math.min(e,Math.max(0,Math.floor(e*t)))}function __(e){let t=If([e]);return(n,r)=>K.of({at:r=>n(Math.round(t.lastChange(r)/e)),nextChange:e=>t.nextChange(e),lastChange:e=>t.lastChange(e),reduced:()=>K.constant(r)})}const v_=e=>e.glyph;function y_(e){let t=Lf.once(0,e.seconds),n=af(e.ease);return Lg(e.seconds,({cells:e})=>{let{length:r,place:i}=h_(e);return K.continuous(e=>{let a=g_(r,n(t(e)));return e=>(i.get(e.index)??-1)<a?e.glyph:m_(e.glyph)})})}const b_=[...`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#$%&*+<=>?@`],x_=1/15;function S_(e,t){bg(`scramble`,t);let n=Lf.once(0,e.seconds),r=af(e.ease),i=__(x_)(e=>e,0);return Lg(e.seconds,({cells:e})=>{let{length:a,place:o}=h_(e);return K.continuous(e=>{let s=g_(a,r(n(e))),c=i.at(e);return e=>!Ih(e.glyph)||(o.get(e.index)??-1)<s?e.glyph:C_(e,t,c)})})}function C_(e,t,n){let r=r=>b_[Math.floor(og(e.seed*7919+r,t+n*.618)*b_.length)];return Array.from({length:B(e.glyph)},(e,t)=>r(t)).join(``)}function w_(e){let t=Lf.once(0,e.seconds),n=af(e.ease);return Lg(e.seconds,({cells:e})=>{let{length:r,place:i}=h_(e);return K.continuous(e=>{let a=r-g_(r,n(t(e)));return e=>(i.get(e.index)??-1)<a?e.glyph:m_(e.glyph)})})}const T_=.3;function E_(e,t){bg(`scrambleOut`,t);let n=Lf.once(0,e.seconds),r=af(e.ease),i=__(x_)(e=>e,0);return Lg(e.seconds,({cells:e})=>{let{length:a,place:o}=h_(e);return K.continuous(e=>{let s=r(n(e)),c=g_(a,s/(1-T_)),l=g_(a,(s-T_)/(1-T_)),u=i.at(e);return e=>{let n=o.get(e.index)??1/0;return n<l?m_(e.glyph):!Ih(e.glyph)||n>=c?e.glyph:C_(e,t,u)}})})}function D_(e){let t=[...e].map(e=>e===e.toUpperCase()?e.toLowerCase():e.toUpperCase()).join(``);return B(t)===B(e)?t:e}function O_({step:e,width:t},n){if(Df(`caseWave step`,e),!(Number.isInteger(t)&&t>0))throw RangeError(`caseWave width must be a positive whole number of columns, got ${t}`);bg(`caseWave`,n);let r=__(e);return({cells:e})=>{let i=e.reduce((e,t)=>Math.max(e,t.col+B(t.glyph)),0)+t,a=Math.floor(og(n,2.3)*i);return r(e=>{let n=((e+a)%i+i)%i;return e=>e.col<n&&e.col+B(e.glyph)>n-t?D_(e.glyph):e.glyph},v_)}}function k_(e,t){let n=e=>{let t=Ml(e);if(t.length===0||t.some(e=>B(e)!==1))throw RangeError(`particles needs one-cell glyphs, got ${JSON.stringify(e)}`);return t},[r,i]=[n(e.glyphs),n(e.ascii)];if(!np(e.ascii))throw RangeError(`particles ascii must be ASCII, got ${JSON.stringify(e.ascii)}`);if(!(e.density>=0&&e.density<=1))throw RangeError(`particles density must be in [0, 1], got ${e.density}`);if(!Number.isInteger(e.drift))throw RangeError(`particles drift must be a whole number of rows, got ${e.drift}`);if(!(e.life>0))throw RangeError(`particles life must be a positive number of steps, got ${e.life}`);Df(`particles step`,e.step),bg(`particles`,t);let a=__(e.step);return({asciiOnly:n})=>{let o=rp({asciiOnly:n},r,i,e=>e.join(``));return a(n=>{let r=Number.isFinite(e.life)?Math.floor(n/e.life):0,i=e.drift*n;return n=>{if(Ih(n.glyph)||B(n.glyph)===0)return n.glyph;let a=n.row-i,s=t+1.37*n.col+.71*r;return og(a,s)<e.density?o[Math.floor(og(a,s+3.1)*o.length)]+m_(n.glyph).slice(1):n.glyph}},v_)}}const A_={typewriter:{seconds:2,ease:wf.linear},scramble:{seconds:2.5,ease:wf[`ease-in`]},backspace:{seconds:1.5,ease:wf.linear},scrambleOut:{seconds:2.5,ease:wf[`ease-out`]},wave:{step:.06,width:3},rain:{glyphs:`│╎`,ascii:`|:`,density:.06,step:.08,drift:1,life:1/0},stars:{glyphs:`·+*`,ascii:`.+*`,density:.04,step:1.5,drift:0,life:1}},j_={loops:{wave:e=>O_(A_.wave,e.z),rain:e=>k_(A_.rain,e.z),stars:e=>k_(A_.stars,e.z)},transitions:{typewriter:(e,t=A_.typewriter)=>y_(t),scramble:(e,t=A_.scramble)=>S_(t,e.z),backspace:(e,t=A_.backspace)=>w_(t),scrambleOut:(e,t=A_.scrambleOut)=>E_(t,e.z)}};var M_=class{beat;width;_shown;constructor(e){this.beat=If(e.map(e=>e.seconds));let t=e.map(e=>Oh(e.text.copy())),n=t.map(e=>e.cellLength);this.width=Math.max(...n),this._shown=t.map((e,t)=>(e.noWrap=!0,e.overflow=`crop`,e.padRight(this.width-n[t])))}at(e){return this._shown[this.beat.at(e)].copy()}nextChange(e){return this.beat.nextChange(e)}lastChange(e){return this.beat.lastChange(e)}reduced(){return K.map(this.beat.reduced(),e=>this._shown[e].copy())}render(e){return Mp(this,e)}measure(){return{minimum:this.width,maximum:this.width}}};function N_(e,t,n){let r=Tp(e,t,n),i=r.value.copy();return i.style=Yf(i.style,Dp(Ep(r,t))),i}function P_(e,t){let n=[...hp(e,t)],r=0;for(let e of n)r+=e.cellLength;return{segments:n,width:r}}const F_={segments:[],width:0},I_={left:()=>0,justify:()=>0,center:e=>Math.floor(e/2),right:e=>e};function L_(e,t){return I_[e](t)}function R_(e,t,n,r){let i=Math.max(0,r-1),a=e===`justify`&&!t&&i>0&&n>0?n:0,o=i>0?Math.floor(a/i):0,s=a-o*i;return Array.from({length:i},(e,t)=>o+ +(t<s))}var z_=class{items;joiner;gap;align;constructor(e,t){this.items=e,this.joiner=t?.joiner,this.gap=t?.gap??0,this.align=t?.align??`left`}*render(e){let t=this.items;if(t.length===0)return;let n=Math.max(1,e.maxWidth),r=this.gap,i=this.joiner,a=t.map(t=>P_(ym(t),e)),o=n=>i?P_(vm(i,null,t[n],{index:n}),e):F_,s=n=>i?P_(vm(i,t[n],null,{index:n+1}),e):F_,c=(n,r)=>i?P_(vm(i,t[n],t[r],{index:r}),e):F_,l=[],u=null,d=r>0?{segments:[new G(` `.repeat(r))],width:r}:F_;for(let e=0;e<t.length;e++){let t=a[e];if(u===null){let n=o(e),r=s(e),i=n.width>0?[n,t]:[t],a=[i.length-1];u={blocks:i,width:n.width+t.width,lastIndex:e,itemBlockIndices:a},u.endCap=r;continue}let i=u.lastIndex,f=c(i,e),p=s(e),m=(r>0?r:0)+f.width+(r>0?r:0)+t.width;if(u.width+m+p.width<=n)r>0&&u.blocks.push(d),f.width>0&&u.blocks.push(f),r>0&&u.blocks.push(d),u.blocks.push(t),u.itemBlockIndices.push(u.blocks.length-1),u.width+=m,u.lastIndex=e,u.endCap=p;else{let n=u.endCap;n.width>0&&u.blocks.push(n),u.width+=n.width,l.push(u);let r=o(e),i=s(e),a=r.width>0?[r,t]:[t],c=[a.length-1];u={blocks:a,width:r.width+t.width,lastIndex:e,itemBlockIndices:c},u.endCap=i}}let f=u;{let e=f.endCap;e.width>0&&f.blocks.push(e),f.width+=e.width,l.push(f)}let p=this.align;for(let e=0;e<l.length;e++){let t=l[e],r=e===l.length-1,i=Math.max(0,n-t.width),a=L_(p,i),o=R_(p,r,i,t.itemBlockIndices.length),s=new Map;t.itemBlockIndices.forEach((e,t)=>s.set(e,t)),a>0&&(yield new G(` `.repeat(a)));for(let e=0;e<t.blocks.length;e++){let n=s.get(e);if(n!==void 0&&n>0){let e=o[n-1];e>0&&(yield new G(` `.repeat(e)))}yield*t.blocks[e].segments}yield G.line()}}measure(e){let t=this.items;if(t.length===0)return{minimum:0,maximum:0};let n=0,r=0;for(let i=0;i<t.length;i++){let a=P_(t[i],e).width,o=this.joiner?P_(vm(this.joiner,null,t[i],{index:i}),e).width:0,s=this.joiner?P_(vm(this.joiner,t[i],null,{index:i+1}),e).width:0;n=Math.max(n,a+o+s),r+=a,i>0&&(r+=this.gap*2,this.joiner&&(r+=P_(vm(this.joiner,t[i-1],t[i],{index:i}),e).width))}return this.joiner&&(r+=P_(vm(this.joiner,null,t[0],{index:0}),e).width,r+=P_(vm(this.joiner,t[t.length-1],null,{index:t.length}),e).width),{minimum:n,maximum:r}}};function B_(){let e=new WeakMap;return(t,n,r)=>{let i=e.get(t);i===void 0&&(i=new Map,e.set(t,i));let a=i.get(n);if(a!==void 0)return a;let o=r();return i.set(n,o),o}}const V_=(e,t)=>e===t;function H_(e){let t=Object.keys(e);return(n,r)=>t.every(t=>e[t](n[t],r[t]))}const U_=e=>(t,n)=>t.length===n.length&&t.every((t,r)=>e(t,n[r])),W_=[`primary`,`secondary`,`accent`],G_=[`darken-3`,`darken-2`,`darken-1`,`base`,`lighten-1`,`lighten-2`,`lighten-3`],K_={"darken-3":`-darken-3`,"darken-2":`-darken-2`,"darken-1":`-darken-1`,base:``,"lighten-1":`-lighten-1`,"lighten-2":`-lighten-2`,"lighten-3":`-lighten-3`,muted:`-muted`},q_=(e,t)=>`${e}${K_[t]}`,J_=(e,t,n,r)=>Uv(e,n,r),Y_=(e,t,n,r)=>Gv(e,e.get(`text-${t}`),n,r),X_=e=>({tones:[G_[e],G_[e+2],G_[e+1]],text:J_,activated:`muted`}),Z_=e=>({tones:[G_[3-e],G_[3+e],G_[3]],text:J_,activated:`muted`}),Q_=e=>({tones:[G_[3-e],G_[3+e]],text:J_,activated:`muted`}),$_={wide:Z_(2),widest:Z_(3),pair:Q_(2),"pair-wide":Q_(3)},ev=Object.keys($_),tv={muted:{tones:[`muted`,`base`],text:Y_,activated:`lighten-2`},deepest:X_(0),deeper:X_(1),middle:X_(2),brighter:X_(3),brightest:X_(4),...$_},nv=(e,t)=>e[t%e.length],rv=`accent`,iv=1/0,av={keystones:[],open:[`accent`,`primary`,`secondary`]},ov={door:[`bar-start`],start:[`line-start`],end:[`line-end`],ends:[`line-start`,`line-end`]},sv={primary:[`primary`],secondary:[`secondary`],alternate:[`primary`,`secondary`]};function cv(){let e=Object.entries(ov).flatMap(([e,t])=>Object.entries(sv).map(([n,r])=>[`${e}-${n}`,{hues:[`secondary`],run:iv,keystones:t,open:r}]));return Object.fromEntries(e)}const lv=cv(),uv={accent:{hues:[`secondary`,`accent`],run:iv,...av},duo:{hues:[`primary`,`secondary`],run:iv,...av},mono:{hues:[`primary`],run:iv,...av},alt:{hues:[`secondary`,`accent`],run:3,...av},...lv},dv=Object.keys(lv),fv={error:[`bright_red`,`red`],warning:[`bright_yellow`,`yellow`],success:[`bright_green`,`green`]},pv=(e,t,n)=>zv(e,t,t.variation.hues.flatMap(r=>{let i=mv(e,r,t.shade,n);return t.shade.tones.map((e,t)=>({hue:r,shade:i[t%i.length]}))}),n);function mv(e,t,n,r){return _v(e,`${t}|${n.tones.join(`,`)}|${r}`,()=>{let i=vv(e,t,r),a=gv(n.tones.length,new Set(G_.map(i)).size),[o,...s]=n.tones,c=[o];for(let e of s)c.length<a&&c.every(t=>i(t)!==i(e))&&c.push(e);return hv(Array.from({length:a-c.length}).reduce(a=>{let o=yv(e,t,n.tones,a.map(i),r);return o===void 0?a:[...a,o]},c))})}const hv=e=>{if(e.length<3)return e;let t=G_,[n,...r]=[...e].sort((e,n)=>t.indexOf(e)-t.indexOf(n));return[n,r.at(-1),...r.slice(0,-1)]},gv=(e,t)=>Math.max(2,Math.min(e,t-1)),_v=B_(),vv=(e,t,n)=>r=>fd(e.get(q_(t,r)),n).hex;function yv(e,t,n,r,i){let a=vv(e,t,i);return bv(n,e.dark).find(e=>!r.includes(a(e)))}function bv(e,t){let n=G_,r=e=>e===`muted`?t?-1:n.length:n.indexOf(e),i=t?1:-1;return G_.map((t,n)=>({rung:t,at:n,distance:Math.min(...e.map(e=>Math.abs(n-r(e))))})).filter(({distance:e})=>e>0).sort((e,t)=>e.distance-t.distance||(t.at-e.at)*i).map(({rung:e})=>e)}const xv=(e,t)=>Math.floor(e*t),Sv=(e,t)=>{let n=t-1;for(let t=e;t<.5&&n>0;t*=2)n--;return n},Cv=e=>{let t=0,n=.5;for(let r=e;r>0;r>>=1,n/=2)t+=n*(r&1);return t},wv=[`van-der-corput`,`golden-angle`,`ends-interleaved`,`monotonic`,`uniform`],Tv=e=>typeof e==`string`&&wv.includes(e),Ev={"van-der-corput":{place:Cv,quantize:Sv},"golden-angle":{place:e=>e*.6180339887498949%1,quantize:xv},"ends-interleaved":{place:(e,t)=>((e%2==0?e/2:t-1-(e-1)/2)+.5)/t,quantize:xv},monotonic:{place:(e,t)=>(e+.5)/t,quantize:xv},uniform:{place:()=>.5,quantize:Sv}},Dv=e=>Ev[e??`van-der-corput`];function Ov(e,t){if(e===void 0)return 0;let{place:n,quantize:r}=e.distribution;return r(n(e.index,e.count),t)}function kv(e,t){let n=e[Ov(t,e.length)];if(n===void 0)throw Error(`vocabularySelect: empty vocabulary`);return n}function Av(e){let t=e=>e.axis===`cell`,n=e.findIndex(t);return{row:(n===-1?e:e.slice(0,n)).at(-1),cell:e.findLast(t)}}const jv=(e,t)=>Ov(t,e.hues.length);function Mv(e,t,n,r){let{row:i,cell:a}=Av(n);return a===void 0?Nv(e,t,i,a,r):Pv(e,t,i,a,r)[a.index-a.lineStart]}function Nv(e,t,n,r,i){let{hues:a,run:o,keystones:s}=t.variation,c=r===void 0?0:Math.floor(r.index/o),l=a[(jv(t.variation,n)+c)%a.length];if(l===void 0)throw Error(`decorEntryFor: empty variation`);let u=s.some(e=>Bv[e](n,r))?rv:l;return{hue:u,shade:kv(mv(e,u,t.shade,i),r)}}function Pv(e,t,n,r,i){let{hues:a,run:o,keystones:s,open:c}=t.variation;return Fv(e,[a.join(`,`),o,s.join(`,`),c.join(`,`),t.shade.tones.join(`,`),t.shade.activated,n===void 0?``:Iv(n),Iv(r,r.lineStart),i].join(`|`),()=>zv(e,t,Array.from({length:r.lineEnd-r.lineStart+1},(a,o)=>Nv(e,t,n,{...r,index:r.lineStart+o},i)),i))}const Fv=B_();function Iv({axis:e,index:t,count:n,distribution:r,lineStart:i,lineEnd:a,...o},s=t){return`${e},${s},${n},${Lv(r)},${i},${a}`}function Lv(e){let t=Rv.get(e);if(t===void 0)throw Error(`decorEntryFor: a cell placed outside DISTRIBUTIONS`);return t}const Rv=new Map(wv.map(e=>[Ev[e],e]));function zv(e,t,n,r){let i=[...n],a=t=>{let n=i[t];return n&&vv(e,n.hue,r)(n.shade)},o=Zv(e,{decor:t,depth:0},r),s=(n,o)=>{let{hue:s}=i[n],c=[a(n-1),a(n+1),...o].filter(e=>e!==void 0),l=mv(e,s,t.shade,r),u=l.find(t=>!c.includes(vv(e,s,r)(t)))??yv(e,s,l,c,r);return u===void 0?void 0:{hue:s,shade:u}},c=e=>[[o],[]].flatMap(t=>[e,e-1].map(e=>({place:e,off:t})));for(let e=1;e<i.length;e++)if(!(i[e-1].hue===i[e].hue||a(e-1)!==a(e)))for(let{place:t,off:n}of c(e)){let e=s(t,n);if(e!==void 0){i[t]=e;break}}return i}const Bv={"bar-start":(e,t)=>(e?.index??0)===0&&(t?.index??0)===0,"line-start":(e,t)=>t===void 0||t.index===t.lineStart,"line-end":(e,t)=>t===void 0||t.index===t.lineEnd},Vv=(e,t)=>e.get(q_(t.hue,t.shade)),Hv=4.5;function Uv(e,t,n){return Wv(e,`${t.hex}|${n}`,()=>{let r=ud(t);return Gv(e,[`background`,`foreground`].map(t=>e.get(t)).reduce((e,t)=>Gl(r,t)<Gl(r,e)?t:e),t,n)})}const Wv=B_();function Gv(e,t,n,r){return Kv(e,`${t.hex}|${n.hex}|${r}`,()=>dd(t,n,Hv,r))}const Kv=B_(),qv=({decor:e,depth:t})=>nv(e.variation.open,t),Jv=(e,t,n)=>mv(e,qv(t),t.decor.shade,n).map(e=>({hue:qv(t),shade:e}));function Yv(e,t,n){let{decor:r,depth:i}=t,{variation:a,shade:o}=r;return Xv(e,[i,a.open.join(`,`),a.hues.join(`,`),a.keystones.length,o.tones.join(`,`),o.activated,n].join(`|`),()=>{let s=qv(t),c=t=>mv(e,t,o,n).map(vv(e,t,n)),l=a.keystones.length>0?[rv]:[],u=i===0?[...a.hues,...l].flatMap(c):(t=>[...c(qv(t)),Zv(e,t,n)])({decor:r,depth:i-1}),d=[...c(s),...u];return d.includes(vv(e,s,n)(o.activated))?yv(e,s,[o.activated],d,n)??o.activated:o.activated})}const Xv=B_(),Zv=(e,t,n)=>vv(e,qv(t),n)(Yv(e,t,n)),Qv=e=>({...e,depth:e.depth+1});function $v(e,t,n){return{state:e.get(q_(qv(t),Yv(e,t,n))),plane:e.get(`surface`),items:Jv(e,t,n).map(t=>Vv(e,t))}}function ey(e,t,n,r){return kv($v(e,t,r).items,n)}function ty(e,t,n,r){let i=ey(e,t,n,r);return{tint:i,text:t.decor.shade.text(e,qv(t),i,r)}}function ny(e,t){switch(e.kind){case`bar`:return t.kind===`bar`&&oy(e,t);case`band`:return t.kind===`band`&&sy(e,t)}}const ry=U_(H_({index:V_,count:V_,distribution:V_,axis:V_,lineStart:V_,lineEnd:V_})),iy=H_({variation:V_,shade:V_}),ay=H_({decor:iy,depth:V_}),oy=H_({kind:V_,decor:iy,address:ry}),sy=H_({kind:V_,band:ay,address:ry}),cy=e=>({kind:`bar`,decor:e,address:[]}),ly=(e,t)=>({...e,address:[...e.address,t]}),uy=e=>({kind:`band`,band:e,address:[]});function dy(e,t,n){switch(t.kind){case`bar`:{let{decor:r,address:i}=t,a=Mv(e,r,i,n),o=Vv(e,a);return{tint:o,text:r.shade.text(e,a.hue,o,n),disclosure:{decor:r,depth:0}}}case`band`:{let{band:r,address:i}=t;return{...ty(e,r,Av(i).cell,n),disclosure:Qv(r)}}}}const fy=new Map([[`dark`,`textual-dark`],[`light`,`textual-light`]]);function py(e){let t=typeof e==`string`?fy.get(e):void 0;return t===void 0?``:` — "${e}" was retired; write "${t}", the same palette`}const my=`textual-dark`;function hy(e,t,n,r,i){let a=t===null?null:i(t);return e??a??n??r}function gy(){return qd()}function _y(){return[`bar`,...gy()]}let vy;function yy(e){return vy??=new Set(_y()),vy.has(e)}function by(e,t,n,r,i){let a=e=>Object.prototype.hasOwnProperty.call(i,e)?e:null;return hy(e===void 0?null:a(e),t,a(n??r),r,a)}const xy=[`style`,`palette`,`effect`];function Sy(e){return e!==void 0&&e.includes(`{{`)}function Cy(e,t,n,r,i){let a=Sy(n)?{kind:`expression`,source:n}:i(n??r.name);return hy(e===void 0?null:i(e),t,a,r,i)}const wy=`none`;function Ty(e,t){let n=t[e];return n===void 0?null:{kind:`decided`,name:e,value:n}}function Ey(e,t){return Ty(e,t)??Ty(`none`,t)??{kind:`decided`,name:`none`,value:Ru}}function Dy(e,t,n,r){return Cy(e,t,n,Ey(wy,r),e=>Ty(e,r))}const Oy=`none`,ky={style:wy,palette:my,effect:Oy};function Ay(e,t,n){return`${e} rendered "${ky[t]}": ${n}`}const jy=Object.freeze([Oy,...Object.keys(o_.loops)]),My=Object.freeze({"1x":1,"5x":5,"10x":10,"20x":20}),Ny=Object.keys(My),Py=Object.freeze([`bar`,...jy]);function Fy(e){let t=jy.find(t=>t===e);return t===void 0?null:{kind:`decided`,name:e,value:t}}function Iy(e){return Fy(e)??{kind:`decided`,name:`none`,value:`none`}}function Ly(e,t,n){return Cy(e,t,n,Iy(Oy),Fy)}const Ry=Object.freeze(Object.keys(wh)),zy=[`powerline`,`capsule`,`plain`];function By(e){return zy.includes(e)}const Vy=[`truecolor`,`256`,`ansi`,`none`];function Hy(e){return Vy.includes(e)}function Uy(e){return iu(e)??H.DEFAULT}const Wy=Object.keys(uv),Gy=Object.keys(tv),Ky=`true`,qy=`false`,Jy=[Ky,qy],Yy={min:0,max:16};function Xy(e){return e===`true`?!0:e===`false`?!1:null}function Zy(e,t){let n=Number(e);return Number.isInteger(n)&&String(n)===e&&n>=t.min&&n<=t.max?n:null}function Qy(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $y(e){return ae(`sha256`).update(JSON.stringify(eb(e))).digest(`hex`)}function eb(e){return Array.isArray(e)?e.map(eb):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,eb(t)])):e}const tb=[`vertical`,`horizontal`],nb={vertical:`row`,horizontal:`cell`};function rb(e){return e.id??e.name}function ib(e){return[...sb(e)].flatMap(e=>e.kind===`segment`?[rb(e)]:[])}function ab(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function ob(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*sb(e){yield e;for(let t of db(e))yield*sb(t)}const cb=(e,t)=>`${e}.children[${t}]`,lb=e=>`${e}.opens.body`;function*ub(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*ub(r,cb(t,n));else e.opens!==void 0&&(yield*ub(e.opens.body,lb(t)))}function db(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}function fb(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const pb=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function mb(e){return e.kind===`file`||e.kind===`shell`}function hb(e,t){let n=e.kind===`template`?{...e,template:t(e.template,`template`)}:e;return mb(n)&&`key`in n.cache?{...n,cache:{...n.cache,key:t(n.cache.key,`cache.key`)}}:n}function gb(e){let t=[];return hb(e,(e,n)=>(t.push([n,e]),e)),t}const _b=[`fail`,`ignore`];function vb(e){return e.missingData??`fail`}function*yb(e){for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&(yield[t,n]);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&(yield[`${t}.${e}`,r])}const bb=`theme`,xb=`effect`,Sb=[bb,xb];function Cb(e){return{...e.settings,[bb]:{label:bb,domain:`theme`,default:e.palette??`bar`},[xb]:{label:xb,domain:Py,default:`bar`}}}function wb(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function Tb(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=wb(r)?.atLeast;if(i===void 0)return[];let a=t[n],o=t[i];return a>=o?[]:[{setting:n,message:`"${n}" (${a}) is below "${i}" (${o}) — ${r.label} must be at least ${e[i].label}`}]})}function Eb(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&yy(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function Db(e){return String(e)}function Ob(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return Zy(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return Eb(e,r)?r:void 0}function Bee(e,t,n,r){let i=e.drafts?.[t];if(i===void 0)return e.settings?.[t]??n.default;let a=r(i),o=Ob(n,a);if(o===void 0)throw Error(`placement setting "${t}": its draft reads ${JSON.stringify(a)}, which its declaration does not admit (${kb(n)})`);return o}function kb(e){let{domain:t}=e;return t===`bool`?`true or false`:t===`theme`?`"bar" (the bar's own theme) or an installed theme name`:`min`in t?`an integer from ${t.min} to ${t.max}`:`one of ${t.map(e=>JSON.stringify(e)).join(`, `)}`}const Vee=[`left`,`center`,`right`],Hee=[`right`,`left`,`middle`];var Ab=class extends Error{file;issues;warnings;constructor(e,t,n=[]){super(Xee(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t,this.warnings=n}},Uee=class extends Ab{prompt;constructor(e,t){super(e,t),this.name=`DroppedFileError`,this.prompt=[`Fix my cc-candybar statusline config. It places segments that do not exist, so those cells are not drawn.`,`Config file to edit: ${e}`,this.message,`For each placement: rename it to a segment the error lists as declared (if it names a plugin file, read that file to confirm), or remove the placement. Edit only the config file; do not change any plugin file.`].join(`
54
+ `?[t+1,0]:[t,n+o],i+=o,{glyph:e,cell:a,width:o}})})}function Ih(e){return e.trim()!==``}function Lh(e){let t=Fh(e.map(({segment:e})=>e));return e.map((e,n)=>({...e,glyphs:t[n]}))}function Rh(e,t){let n,r=()=>{let n=new Map;return e.forEach(({look:e,glyphs:r},i)=>{let a=t[i];if(e===void 0||a===void 0||!(`painted`in a))return;let o=a.painted;r.forEach(({cell:t},r)=>{if(t===void 0)return;let i=n.get(t.row)??[];i.push({col:t.col,anchor:t.anchor,look:e,moved:o[r]}),n.set(t.row,i)})}),n};return(e,t,i)=>{let a=(n??=r()).get(e[0].row)??[],o=e[0].col,s=e[e.length-1].col;if(t===`right`)return a.find(e=>e.col>s&&zf(e.anchor,i));for(let e=a.length-1;e>=0;e--){let t=a[e];if(t.col<o&&zf(t.anchor,i))return t}}}function zh(e){return[e.underline,e.underline2,e.strike,e.overline,e.frame,e.encircle].some(e=>e===!0)}function Bh(e,t,n,r){let i=r.backgroundColor.hex,a,o=()=>t().flatMap(({look:e,glyphs:t})=>{if(e===void 0)return[];let n=e.pair.bg.hex!==i||zh(e.style);return t.flatMap(({glyph:t,cell:r,width:i})=>r===void 0?[]:[{cell:{...r,width:i,pair:e.pair,seam:e.seam},shows:Ih(t)||n}])}),s=()=>a??=o(),c,l,u=e.flatMap(({segment:e,look:t})=>t!==void 0&&Ih(e.text)&&!t.seam?[t.pair]:[]),d=[...new Map(u.map(e=>[`${e.fg.hex}/${e.bg.hex}/${e.terminal.fg}/${e.terminal.bg}/${e.reverse}`,e])).values()],f=e=>d.flatMap(t=>t.terminal[e]?[]:[t[e].hex]);return{all:()=>c??=s().map(({cell:e})=>e),cells:()=>l??=s().flatMap(({cell:e,shows:t})=>t?[e]:[]),pairs:d,colors:new Set([...f(`fg`),...f(`bg`)]),fills:new Set(f(`bg`)),depth:n,theme:r}}function Vh(e,...t){let n=new Set(t),r=e=>{for(let t=e.anchor;t;t=t.inner)if(n.has(t.owner))return!0;return!1},i=e=>({...e,all:()=>e.all().filter(r),cells:()=>e.cells().filter(r)});return t=>K.map(e(i(t)),e=>(t,n)=>r(n)?e(t,n):t)}function Hh(e,t){return t?{fg:e.bg,bg:e.fg}:e}function Uh(e,t,n,r){let i=t.bg.compositeOver(Ul),a=t.fg.compositeOver(i);return{fg:U.matchMove(e.fg,a,n,r,!0),bg:U.matchMove(e.bg,i,n,r,!1)}}function Wh(e,t){return Gh(e.color,t.color,!0)&&Gh(e.bgcolor,t.bgcolor,!1)}function Gh(e,t,n){return e===t||Kh(e,n)===Kh(t,n)}function Kh(e,t){return e?.getAnsiCodes(t).join(`;`)??``}function qh(e){if(e.attributes===void 0)throw TypeError(`an effect frame returns the look it was handed with its changes, { ...look, fg, bg }: this one returned no attributes`);return e}const Jh=Vf.filter(e=>e!==`reverse`);function Yh(e){return Object.fromEntries(Jh.map(t=>[t,e[t]]))}function Xh(e,t){return e===t||Jh.every(n=>e[n]===t[n])}function Zh(e,t){return e===t||e!==void 0&&t!==void 0&&e.type===t.type&&e.name===t.name}function Qh(e,t){return $h(e.fg,t.fg)&&$h(e.bg,t.bg)}function $h(e,t){return e.red===t.red&&e.green===t.green&&e.blue===t.blue&&e.alpha===t.alpha}const eg=(()=>{let e=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];return[...e,...e]})(),tg=e=>e*e*e*(e*(e*6-15)+10),ng=(e,t,n)=>e+n*(t-e);function rg(e,t,n,r){let i=e&15,a=i<8?t:n,o=i<4?n:i===12||i===14?t:r;return(i&1?-a:a)+(i&2?-o:o)}function ig(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=Math.floor(n),o=r&255,s=i&255,c=a&255;e-=r,t-=i,n-=a;let l=tg(e),u=tg(t),d=tg(n),f=eg[o]+s,p=eg[f]+c,m=eg[f+1]+c,h=eg[o+1]+s,g=eg[h]+c,_=eg[h+1]+c;return ng(ng(ng(rg(eg[p],e,t,n),rg(eg[g],e-1,t,n),l),ng(rg(eg[m],e,t-1,n),rg(eg[_],e-1,t-1,n),l),u),ng(ng(rg(eg[p+1],e,t,n-1),rg(eg[g+1],e-1,t,n-1),l),ng(rg(eg[m+1],e,t-1,n-1),rg(eg[_+1],e-1,t-1,n-1),l),u),d)}function ag(e,t,n,r){let i=0,a=1,o=0;for(let s=0;s<r;s++){let r=2**s;i+=a*ig(e*r,t*r,n*r),o+=a,a/=2}return i/o}function og(e,t){let n=Math.sin(e*12.9898+t*78.233)*43758.5453;return n-Math.floor(n)}function sg(e,t,n){let r=Math.min(1,Math.max(0,(n-e)/(t-e)));return r*r*(3-2*r)}const cg=Array.from({length:48},(e,t)=>(t+1)/48);function lg(e,t){return Math.min(Gl(e.fg,e.bg),4.5)-(t===H.TRUECOLOR?.01:0)}const ug=[`fg`,`bg`];function dg({pairs:e,depth:t,theme:n},r,i){let a=(e,t)=>e.terminal[t]?void 0:e[t].hex,o=new Map(e.flatMap(e=>ug.flatMap(t=>{let n=a(e,t);return n===void 0?[]:[[n,e[t]]]}))),s=new Map([...r].filter(e=>!o.has(e)).map(e=>[e,1])),c=e=>Xu.fromRgba(o.get(e)).l;for(let l of[...r].filter(e=>o.has(e)).sort((e,t)=>c(t)-c(e))){let r=e.flatMap(e=>{let t=ug.find(t=>a(e,t)===l);if(t===void 0)return[];let n=a(e,t===`fg`?`bg`:`fg`);return[[e,t,n===void 0?0:s.get(n)??0]]}),o=e=>r.every(([r,a,o])=>{let s=lg(r,t),c=(t,n)=>vg(i,r[t],(t===a?e:o)*n);return cg.every(e=>{let i=jh.shows(r,{fg:c(`fg`,e),bg:c(`bg`,e)},t,n);return Gl(i.fg,i.bg)>=s})}),[c,u]=o(1)?[1,1]:[0,1];for(let e=0;e<20&&u-c>.001;e++){let e=(c+u)/2;[c,u]=o(e)?[e,u]:[c,e]}s.set(l,c)}return s}function fg(e,t){let n=new _l;return gg(hg(e,r=>{let i=t??r.colors,a=[pg(r),`|`,...i].join(` `);return n.get(r.theme,()=>new gl).get(a,()=>dg(r,i,e.touch))}))}function pg({depth:e,pairs:t}){return[e,...t.map(mg)].join(` `)}function mg({fg:e,bg:t,terminal:n,reverse:r}){return`${e.hex}/${t.hex}/${n.fg}/${n.bg}/${r}`}function hg(e,t){return n=>{let r=t(n);return K.continuous(t=>{let i=e.field(t,n);return(t,n)=>{let a=Math.round(Cg(i(n))*48)/48,o=(t,n)=>vg(e.touch,t,(n?0:r.get(t.hex)??0)*a);return{...t,fg:o(t.fg,n.terminal.fg),bg:o(t.bg,n.terminal.bg)}}})}}function gg(e){return t=>_g(t.depth)?K.constant(e=>e):e(t)}function _g(e){switch(e){case H.DEFAULT:case H.STANDARD:case H.WINDOWS:return!0;case H.EIGHT_BIT:case H.TRUECOLOR:return!1}}function vg(e,t,n){return n===0?t:e(t,n)}function yg(e){if(!(Number.isFinite(e.seconds)&&e.seconds>0))throw RangeError(`curve: seconds must be a positive number of seconds, got ${e.seconds}`);if(!(e.swing>=0&&e.swing<=1))throw RangeError(`curve: swing must be in [0, 1], got ${e.swing}`)}function bg(e,t){if(!Number.isFinite(t))throw RangeError(`${e} z must be a finite place in the noise, got ${t}`)}const xg={shimmer:{seconds:109,ease:wf.linear,swing:.9},pulse:{seconds:43,ease:wf.linear,swing:.85},sparkle:{seconds:139,ease:wf.linear,swing:.95},wheel:{seconds:907,ease:wf.linear,swing:1},fade:{seconds:20,ease:wf[`ease-in-out`],swing:1},dissolve:{seconds:30,ease:wf[`ease-in-out`],swing:1}},Sg={sun:new V(255,228,176),firefly:new V(222,245,140)},Cg=e=>Math.min(1,Math.max(0,e));function wg(e,t,n){if(!(n>=0&&n<=1))throw RangeError(`blend: w must be in [0, 1]; got ${n}`);let r=Math.PI/180,i=(1-n)*e.c*Math.cos(e.h*r)+n*t.c*Math.cos(t.h*r),a=(1-n)*e.c*Math.sin(e.h*r)+n*t.c*Math.sin(t.h*r);return new Xu((1-n)*e.l+n*t.l,Math.hypot(i,a),Math.atan2(a,i)/r,e.alpha)}function Tg(e){let t=Xu.fromRgba(e);return(e,n)=>{let r=Xu.fromRgba(e);return wg(r,new Xu(Math.max(r.l,t.l),t.c,t.h,t.alpha),n).toRgba()}}const Eg=(e,t)=>t*e[e.length-1][0];function Dg(e,t,n){let r=t/n,i=e.findIndex(([e])=>r<e);if(!(r>0)||i<0)return 0;let[a,o]=i===0?[0,0]:e[i-1],[s,c]=e[i];return n*(o+(c-o)*(1-Math.cos(Math.PI*(r-a)/(s-a)))/2)}function Og(e,t,n){let r=Eg(e,n),i=t=>{let r=0;for(let i=0;i<24;i++)r+=Dg(e,(i+.5)/24*t,n);return r*t};return i(Math.min(Math.max(t,0),r))/i(r)}const kg=[[.24,1],[.6,0]];function Ag(e,t,n){yg(e),bg(`pulse`,n);let r=.9+.2*og(n,3.1),i=t=>.1*ig(t/(3*e.seconds),.5,.5+n),a=i(0);return{touch:Tg(t),field:t=>{let o=r*t/e.seconds+i(t)-a,s=Math.floor(o),c=.7+.3*sg(-.5,.5,ig(s*.37,2.1,n)),l=.5-.5*Math.cos(2*Math.PI*(o-s)),u=e.swing*e.ease(c*l);return()=>u}}}const jg=e=>Math.abs(e)>=1?0:(1-e*e)**3;function Mg(e,t,n,r){yg(e),bg(`shimmer`,r);let i=e.seconds,a=i/2,o=e=>sg(-.4,.4,ig(e/7,3.3,5.5+r)),s=.7,c=.51,l=.4,u=(e,n,u)=>{let d=o(e),f=(og(e,7.5+r)<.35+.6*d)*(.3+.7*d*(.6+.4*og(e,8.5+r))),p=i*u/80*(c+l*og(e,5.5+r)),m=Cg((n-(e+s*og(e,6.5+r))*a)/p);return{strength:f,centre:m*u-t+.06*u*Math.sin(Math.PI*m)*ig(m,2.7,e+r)}},d=(e,t)=>{let n=s+(c+l)*i*t/80/a,r=Math.floor(e/a),o=[];for(let i=Math.max(0,Math.ceil(r-n));i<=r;i++)o.push(u(i,e,t));return o},f=(e,t,n)=>Math.exp(-((ig(e,t,n)/.8)**2));return{touch:Tg(n),field:(n,i)=>{let[a,o]=zg(i.cells().map(e=>e.col)),s=d(n,o-a+1+2*t);return i=>{let o=0;for(let{strength:e,centre:n}of s)o=Math.max(o,e*jg((i.col-a-n)/t));let c=i.row+r,l=.8*ig(i.col*.05,c*.3+1.3,n*.02),u=(f(i.col*.21+l,c*.9,n*.022)*f(i.col*.33+9.1-l,c*.7,n*.018+4.2))**2;return e.swing*e.ease(o*(.1+.6*u))}}}}function Ng(e,t,n){yg(e),bg(`sparkle`,n);let r=e.seconds,i=22.1,a=3.1,o=(e,t,i,a,o)=>{let s=e*4.9+t*31.7+.3+n,c=e+.5+.7*ig(e*1.7+.2,.3+t*2.9,.5+n),l=i+og(e+t*1013,.7+n)*r,u=Math.floor(l/r),d=og(u,s+1)<.15?0:1,f=.5+.5*og(u,s+2),p=og(u,s+3)*(1-Eg(kg,f)),m=l/r-u-p;return{x:a+c*8+5*(2*og(u,s+4)-1)+5*f*(2*og(u,s+5)-1)*Og(kg,m,f)+1.5*ig(s,.1,i*.035),y:o+t*3+.6*ig(s,2.2,i*.035),glow:d*Dg(kg,m,f)}};return{touch:Tg(t),field:(t,n)=>{let r=n.cells(),[s,c]=zg(r.map(e=>e.col)),[l,u]=zg(r.map(e=>e.row)),d=e=>(e-s)/8-.5,f=e=>(e-l)/3,[p,m]=[Math.ceil(d(s-i)),Math.floor(d(c+i))],[h,g]=[Math.ceil(f(l-a)),Math.floor(f(u+a))],_=Array.from({length:g-h+1},(e,n)=>Array.from({length:m-p+1},(e,r)=>o(p+r,h+n,t,s,l)));return t=>{let n=0,[r,o]=[Math.max(p,Math.ceil(d(t.col-i))),Math.min(m,Math.floor(d(t.col+i)))],[s,c]=[Math.max(h,Math.ceil(f(t.row-a))),Math.min(g,Math.floor(f(t.row+a)))];for(let e=s;e<=c;e++)for(let i=r;i<=o;i++){let r=_[e-h][i-p];n=Math.max(n,r.glow*jg(Math.hypot(t.col-r.x,2*(t.row-r.y))/5))}return e.swing*e.ease(n)}}}}function Pg(e,t){return n=>{let r=Xu.fromRgba(n.theme.backgroundColor);return K.continuous(i=>{let a=e(i,n);return(e,n)=>{let i=t*(1-Cg(a(n)));if(i===0)return e;let o=wg(Xu.fromRgba(e.bg),r,i);return{...e,fg:wg(Xu.fromRgba(e.fg),o,i).toRgba(),bg:o.toRgba()}}})}}function Fg(e){return t=>Cg(.5+1.1*ag(t.col*.09+1.4*ig(t.col*.035,t.row*.2+2.6,e+.5),t.row*.45,e,3))}var Ig=class{effect;schedule;constructor(e,t){this.effect=e,this.schedule=t}done(e){return K.done(this.schedule,e)}};function Lg(e,t){let n=K.of({...K.sequence(K.continuous(()=>void 0),e,K.constant(void 0)),reduced:()=>K.cut(void 0,void 0)}),r=new Ig(i=>{let a=t(i);return K.of({at:e=>a.at(e),nextChange:e=>r.done(e)?1/0:a.nextChange(e),lastChange:e=>r.done(e)?n.lastChange(e):a.lastChange(e),reduced:()=>K.cut(a.at(0),a.at(e))})},n);return r}function Rg(e,t){return(n,r)=>{let[i,a]=zg(r.map(t)),o=(a>i?.55:0)*e.seconds,s=Lf.once(0,e.seconds-o);return e=>{let r=a>i?Cg((t(e)-i)/(a-i)):0;return{along:r,progress:s(n-r*o)}}}}function zg(e){let t=e[0]??0,n=t;for(let r of e)t=Math.min(t,r),n=Math.max(n,r);return[t,n]}function Bg(e,t){yg(e),bg(`fadeIn`,t);let n=Rg(e,Fg(1.7+t));return Lg(e.seconds,Pg((t,r)=>{let i=n(t,r.cells());return t=>e.ease(i(t).progress)},e.swing))}const Vg={depth:.4,from:.5,to:.95,maskFrom:.35,maskTo:.75,late:.6};function Hg(e,t){yg(e),bg(`dissolveOut`,t);let n=Fg(9.3+t),r=Rg(e,Fg(4.2+t)),{depth:i,from:a,to:o,maskFrom:s,maskTo:c,late:l}=Vg;return Lg(e.seconds,Pg((t,u)=>{let d=r(t,u.cells());return t=>{let{along:r,progress:u}=d(t),f=e.ease(u),p=Cg((f-a)/(o-a)),m=i*sg(s,c,n(t))*(1-l+l*r)*Math.sin(Math.PI*p)**2;return 1-f+m}},e.swing))}const Ug=[211,337],Wg=(e,t)=>({row:e.row,centre:e.col+t/2});function Gg(e){let{colors:t}=e,n=(e,t)=>`${e}:${t}`,r=new Map,i=new Set,a=e=>{if(e.seam)return;let n=(e,n)=>!e&&t.has(n)?n:void 0;return n(e.pair.terminal.bg,e.pair.bg.hex)??n(e.pair.terminal.fg,e.pair.fg.hex)},o=[],s=new Map;for(let t of e.all()){r.set(n(t.row,t.col),t);let e=a(t);for(let r=t.col;r<t.col+t.width;r++)t.seam&&i.add(n(t.row,r)),e!==void 0&&(s.set(n(t.row,r),o.length),o.push({row:t.row,col:r,hex:e}))}let c=o.map((e,t)=>t),l=e=>{for(;c[e]!==e;)c[e]=c[c[e]],e=c[e];return e},u=(e,t,r)=>{let i=s.get(n(t,r));i!==void 0&&o[i].hex===o[e].hex&&(c[l(e)]=l(i))};o.forEach(({row:e,col:t},n)=>{u(n,e,t-1),u(n,e-1,t)});let d=new Map;o.forEach(({row:e,col:t,hex:n},r)=>{let i=l(r),a=d.get(i);a===void 0?d.set(i,{hex:n,top:e,bottom:e,left:t,right:t}):[a.top,a.bottom,a.left,a.right]=[Math.min(a.top,e),Math.max(a.bottom,e),Math.min(a.left,t),Math.max(a.right,t)]});let f=(e,t)=>{let r=s.get(n(e,t));return r===void 0?void 0:d.get(l(r))},p=e=>({row:(e.top+e.bottom)/2,centre:(e.left+e.right+1)/2}),m=(e,t,r)=>{let a=t;for(;i.has(n(e,a));)a+=r;return f(e,a)};return(e,t)=>{let i=r.get(n(e.row,e.col)),a=i?.width??1,o=(i?.seam===!0?[m(e.row,e.col-1,-1),m(e.row,e.col+a,1)]:[]).find(e=>e?.hex===t)??f(e.row,e.col);return o===void 0?Wg(e,a):p(o)}}function Kg(e,t){yg(e),bg(`wheel`,t);let n=e.seconds,r=({row:e,centre:n},r)=>ig(r/Ug[0],n/24+5.9,t+e/24+2.3)+.5*ig(r/Ug[1],n/24+97.3,t+e/24+7.1),i=(t,i)=>360*i/n+e.swing*180*((r(t,i)-r(t,0))/1.5),a=new _l;return gg(e=>{let{colors:t,fills:n,depth:r,theme:o}=e,s=(e,n)=>!e&&t.has(n.hex),c=(e,t,r)=>n.has(e.hex)||!r?e.hex:t.hex,l=(e,t)=>`${e.hex} ${t}`,u=a.get(o,()=>new gl).get(pg(e),()=>Qg(e.pairs,r,(e,t)=>{let n=t===`fg`?`bg`:`fg`;return s(e.terminal[t],e[t])?l(e[t],c(e[t],e[n],s(e.terminal[n],e[n]))):void 0})),d=t_(r,o),f=Gg(e);return K.continuous(e=>{let t=new Map,n=(t,n,a)=>{let o=qg(t,i(a,e));return n_(o.looks,t,r===H.TRUECOLOR?o.either.map($g):d,u.get(l(t,n))??Yg)},a=(e,r,i)=>{let a=`${l(e,r)} ${i.row}:${i.centre}`,o=t.get(a)??n(e,r,i);return t.set(a,o),o};return(e,t)=>{let n={fg:s(t.terminal.fg,e.fg),bg:s(t.terminal.bg,e.bg)},r=(e,n,r,i)=>n?a(e,c(e,r,i),f(t,e.hex)):e;return{...e,fg:r(e.fg,n.fg,e.bg,n.bg),bg:r(e.bg,n.bg,e.fg,n.fg)}}})})}function qg(e,t){if(t===0)return{looks:e,either:[e]};let n=Xu.fromRgba(e),r=Wl(e),i=e=>new Xu(e,n.c,n.h+t,n.alpha).toRgba(),[a,o]=[0,1];for(let e=0;e<24;e++){let e=(a+o)/2;[a,o]=Wl(i(e))<r?[e,o]:[a,e]}return{looks:i(o),either:[i(a),i(o)]}}const Jg=e=>Math.log(Gl(e,new V(0,0,0))),Yg={lo:-1/0,hi:1/0},Xg={lo:1/0,hi:-1/0},Zg=Math.log(1.031);function Qg(e,t,n){let r=new Map;for(let i of e.filter(e=>lg(e,t)>1)){let e=(Math.log(Gl(i.fg,i.bg))-Math.log(lg(i,t)))/ug.filter(e=>n(i,e)!==void 0).length;for(let t of ug){let a=n(i,t);if(a===void 0)continue;let[o,s]=[Jg(i[t]),Jg(i[t===`fg`?`bg`:`fg`])],{lo:c,hi:l}=r.get(a)??Yg;r.set(a,o>=s?{lo:Math.max(c,o-e),hi:l}:{lo:c,hi:Math.min(l,o+e)})}}return new Map([...r].map(([e,{lo:t,hi:n}])=>[e,n-t<Zg?Xg:{lo:t,hi:n}]))}const $g=e=>({color:e,looks:Xu.fromRgba(e),stop:Jg(e)}),e_=new _l;function t_(e,t){return e_.get(U.indexed(e,t),e=>e.map(([,e])=>$g(e)))}function n_(e,t,n,{lo:r,hi:i}){return r_(e,[$g(t),...n.filter(({stop:e})=>e>=r&&e<=i)]).color}function r_(e,t){let n=Xu.fromRgba(e),r;for(let e of t){let t=n.deltaE(e.looks);(r===void 0||t<r[1])&&(r=[e,t])}return r?.[0]}function i_({attribute:e,off:t,on:n}){let r=If([t,n]),i=[e=>e,t=>({...t,attributes:{...t.attributes,[e]:!0}})];return()=>K.map(r,e=>i[e])}const a_={blink:{attribute:`conceal`,off:.5,on:.5},boldPulse:{attribute:`bold`,off:.7,on:.3}},o_={loops:{shimmer:(e,t=xg.shimmer)=>fg(Mg(t,24,Sg.sun,e.z)),pulse:(e,t=xg.pulse)=>fg(Ag(t,Sg.sun,e.z)),sparkle:(e,t=xg.sparkle)=>fg(Ng(t,Sg.firefly,e.z)),wheel:(e,t=xg.wheel)=>Kg(t,e.z)},transitions:{fade:(e,t=xg.fade)=>Bg(t,e.z),dissolve:(e,t=xg.dissolve)=>Hg(t,e.z)},attributes:{blink:()=>i_(a_.blink),boldPulse:()=>i_(a_.boldPulse)}};function s_(e,t){let n=0,r=Fh(e).map(e=>e.map(({glyph:e,cell:r})=>({glyph:e,cell:r&&{...r,glyph:e,index:n++,seed:Mh(t,r.row,r.col)}})));return{placed:r,cells:r.flatMap(e=>e.flatMap(({cell:e})=>e===void 0?[]:[e]))}}function c_(e,t){let n=e.map(e=>e.map(({glyph:e,cell:n})=>n===void 0?e:f_(t,n)));return p_(e.flat(),n.flat()),n}function l_(e,t,n){let{placed:r,cells:i}=s_([new G(e.plain)],n.key);return K.map(t({cells:i,asciiOnly:n.asciiOnly}),t=>u_(e,r[0],c_(r,t)[0]))}function u_(e,t,n){if(n.every((e,n)=>e===t[n].glyph))return e;let r=[0],i=[0];t.forEach(({glyph:e},t)=>{r.push(r[t]+e.length),i.push(i[t]+n[t].length)});let a=e=>{let a=0;for(;a+1<r.length&&r[a+1]<=e;)a++;return a===t.length?i[a]:i[a]+Math.min(e-r[a],n[a].length)},o=e.blankCopy(n.join(``));for(let t of e.spans)o.stylize(t.style,a(t.start),a(t.end));return o}const d_=vl(/[\n\t]/);function f_(e,t){let n=e(t);if(n===t.glyph)return n;if(B(n)!==B(t.glyph)||d_.test(n)||im(n)!==n)throw RangeError(`a glyph effect turned ${JSON.stringify(t.glyph)} at row ${t.row}, column ${t.col} into ${JSON.stringify(n)}: it must be ${B(t.glyph)} cell(s) wide, with no line break or control character`);return n}function p_(e,t){let n=n=>e[n]?.cell===void 0?``:t[n];t.forEach((t,r)=>{let{glyph:i,cell:a}=e[r];if(a===void 0||t===i)return;let[o,s]=[n(r-1),n(r+1)];if(Ml(o+t+s).length!==Ml(o).length+Ml(t).length+Ml(s).length)throw RangeError(`a glyph effect turned ${JSON.stringify(i)} at row ${a.row}, column ${a.col} into ${JSON.stringify(t)}, which joins the cell beside it into one character`)})}function m_(e){return` `.repeat(B(e))}function h_(e){let t=new Map;for(let n of e.filter(e=>Ih(e.glyph)))t.set(n.row,{first:t.get(n.row)?.first??n.index,last:n.index});let n=new Map;for(let r of e){let e=t.get(r.row);e!==void 0&&r.index>=e.first&&r.index<=e.last&&B(r.glyph)>0&&n.set(r.index,n.size)}return{length:n.size,place:n}}function g_(e,t){return Math.min(e,Math.max(0,Math.floor(e*t)))}function __(e){let t=If([e]);return(n,r)=>K.of({at:r=>n(Math.round(t.lastChange(r)/e)),nextChange:e=>t.nextChange(e),lastChange:e=>t.lastChange(e),reduced:()=>K.constant(r)})}const v_=e=>e.glyph;function y_(e){let t=Lf.once(0,e.seconds),n=af(e.ease);return Lg(e.seconds,({cells:e})=>{let{length:r,place:i}=h_(e);return K.continuous(e=>{let a=g_(r,n(t(e)));return e=>(i.get(e.index)??-1)<a?e.glyph:m_(e.glyph)})})}const b_=[...`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#$%&*+<=>?@`],x_=1/15;function S_(e,t){bg(`scramble`,t);let n=Lf.once(0,e.seconds),r=af(e.ease),i=__(x_)(e=>e,0);return Lg(e.seconds,({cells:e})=>{let{length:a,place:o}=h_(e);return K.continuous(e=>{let s=g_(a,r(n(e))),c=i.at(e);return e=>!Ih(e.glyph)||(o.get(e.index)??-1)<s?e.glyph:C_(e,t,c)})})}function C_(e,t,n){let r=r=>b_[Math.floor(og(e.seed*7919+r,t+n*.618)*b_.length)];return Array.from({length:B(e.glyph)},(e,t)=>r(t)).join(``)}function w_(e){let t=Lf.once(0,e.seconds),n=af(e.ease);return Lg(e.seconds,({cells:e})=>{let{length:r,place:i}=h_(e);return K.continuous(e=>{let a=r-g_(r,n(t(e)));return e=>(i.get(e.index)??-1)<a?e.glyph:m_(e.glyph)})})}const T_=.3;function E_(e,t){bg(`scrambleOut`,t);let n=Lf.once(0,e.seconds),r=af(e.ease),i=__(x_)(e=>e,0);return Lg(e.seconds,({cells:e})=>{let{length:a,place:o}=h_(e);return K.continuous(e=>{let s=r(n(e)),c=g_(a,s/(1-T_)),l=g_(a,(s-T_)/(1-T_)),u=i.at(e);return e=>{let n=o.get(e.index)??1/0;return n<l?m_(e.glyph):!Ih(e.glyph)||n>=c?e.glyph:C_(e,t,u)}})})}function D_(e){let t=[...e].map(e=>e===e.toUpperCase()?e.toLowerCase():e.toUpperCase()).join(``);return B(t)===B(e)?t:e}function O_({step:e,width:t},n){if(Df(`caseWave step`,e),!(Number.isInteger(t)&&t>0))throw RangeError(`caseWave width must be a positive whole number of columns, got ${t}`);bg(`caseWave`,n);let r=__(e);return({cells:e})=>{let i=e.reduce((e,t)=>Math.max(e,t.col+B(t.glyph)),0)+t,a=Math.floor(og(n,2.3)*i);return r(e=>{let n=((e+a)%i+i)%i;return e=>e.col<n&&e.col+B(e.glyph)>n-t?D_(e.glyph):e.glyph},v_)}}function k_(e,t){let n=e=>{let t=Ml(e);if(t.length===0||t.some(e=>B(e)!==1))throw RangeError(`particles needs one-cell glyphs, got ${JSON.stringify(e)}`);return t},[r,i]=[n(e.glyphs),n(e.ascii)];if(!np(e.ascii))throw RangeError(`particles ascii must be ASCII, got ${JSON.stringify(e.ascii)}`);if(!(e.density>=0&&e.density<=1))throw RangeError(`particles density must be in [0, 1], got ${e.density}`);if(!Number.isInteger(e.drift))throw RangeError(`particles drift must be a whole number of rows, got ${e.drift}`);if(!(e.life>0))throw RangeError(`particles life must be a positive number of steps, got ${e.life}`);Df(`particles step`,e.step),bg(`particles`,t);let a=__(e.step);return({asciiOnly:n})=>{let o=rp({asciiOnly:n},r,i,e=>e.join(``));return a(n=>{let r=Number.isFinite(e.life)?Math.floor(n/e.life):0,i=e.drift*n;return n=>{if(Ih(n.glyph)||B(n.glyph)===0)return n.glyph;let a=n.row-i,s=t+1.37*n.col+.71*r;return og(a,s)<e.density?o[Math.floor(og(a,s+3.1)*o.length)]+m_(n.glyph).slice(1):n.glyph}},v_)}}const A_={typewriter:{seconds:2,ease:wf.linear},scramble:{seconds:2.5,ease:wf[`ease-in`]},backspace:{seconds:1.5,ease:wf.linear},scrambleOut:{seconds:2.5,ease:wf[`ease-out`]},wave:{step:.06,width:3},rain:{glyphs:`│╎`,ascii:`|:`,density:.06,step:.08,drift:1,life:1/0},stars:{glyphs:`·+*`,ascii:`.+*`,density:.04,step:1.5,drift:0,life:1}},j_={loops:{wave:e=>O_(A_.wave,e.z),rain:e=>k_(A_.rain,e.z),stars:e=>k_(A_.stars,e.z)},transitions:{typewriter:(e,t=A_.typewriter)=>y_(t),scramble:(e,t=A_.scramble)=>S_(t,e.z),backspace:(e,t=A_.backspace)=>w_(t),scrambleOut:(e,t=A_.scrambleOut)=>E_(t,e.z)}};var M_=class{beat;width;_shown;constructor(e){this.beat=If(e.map(e=>e.seconds));let t=e.map(e=>Oh(e.text.copy())),n=t.map(e=>e.cellLength);this.width=Math.max(...n),this._shown=t.map((e,t)=>(e.noWrap=!0,e.overflow=`crop`,e.padRight(this.width-n[t])))}at(e){return this._shown[this.beat.at(e)].copy()}nextChange(e){return this.beat.nextChange(e)}lastChange(e){return this.beat.lastChange(e)}reduced(){return K.map(this.beat.reduced(),e=>this._shown[e].copy())}render(e){return Mp(this,e)}measure(){return{minimum:this.width,maximum:this.width}}};function N_(e,t,n){let r=Tp(e,t,n),i=r.value.copy();return i.style=Yf(i.style,Dp(Ep(r,t))),i}function P_(e,t){let n=[...hp(e,t)],r=0;for(let e of n)r+=e.cellLength;return{segments:n,width:r}}const F_={segments:[],width:0},I_={left:()=>0,justify:()=>0,center:e=>Math.floor(e/2),right:e=>e};function L_(e,t){return I_[e](t)}function R_(e,t,n,r){let i=Math.max(0,r-1),a=e===`justify`&&!t&&i>0&&n>0?n:0,o=i>0?Math.floor(a/i):0,s=a-o*i;return Array.from({length:i},(e,t)=>o+ +(t<s))}var z_=class{items;joiner;gap;align;constructor(e,t){this.items=e,this.joiner=t?.joiner,this.gap=t?.gap??0,this.align=t?.align??`left`}*render(e){let t=this.items;if(t.length===0)return;let n=Math.max(1,e.maxWidth),r=this.gap,i=this.joiner,a=t.map(t=>P_(ym(t),e)),o=n=>i?P_(vm(i,null,t[n],{index:n}),e):F_,s=n=>i?P_(vm(i,t[n],null,{index:n+1}),e):F_,c=(n,r)=>i?P_(vm(i,t[n],t[r],{index:r}),e):F_,l=[],u=null,d=r>0?{segments:[new G(` `.repeat(r))],width:r}:F_;for(let e=0;e<t.length;e++){let t=a[e];if(u===null){let n=o(e),r=s(e),i=n.width>0?[n,t]:[t],a=[i.length-1];u={blocks:i,width:n.width+t.width,lastIndex:e,itemBlockIndices:a},u.endCap=r;continue}let i=u.lastIndex,f=c(i,e),p=s(e),m=(r>0?r:0)+f.width+(r>0?r:0)+t.width;if(u.width+m+p.width<=n)r>0&&u.blocks.push(d),f.width>0&&u.blocks.push(f),r>0&&u.blocks.push(d),u.blocks.push(t),u.itemBlockIndices.push(u.blocks.length-1),u.width+=m,u.lastIndex=e,u.endCap=p;else{let n=u.endCap;n.width>0&&u.blocks.push(n),u.width+=n.width,l.push(u);let r=o(e),i=s(e),a=r.width>0?[r,t]:[t],c=[a.length-1];u={blocks:a,width:r.width+t.width,lastIndex:e,itemBlockIndices:c},u.endCap=i}}let f=u;{let e=f.endCap;e.width>0&&f.blocks.push(e),f.width+=e.width,l.push(f)}let p=this.align;for(let e=0;e<l.length;e++){let t=l[e],r=e===l.length-1,i=Math.max(0,n-t.width),a=L_(p,i),o=R_(p,r,i,t.itemBlockIndices.length),s=new Map;t.itemBlockIndices.forEach((e,t)=>s.set(e,t)),a>0&&(yield new G(` `.repeat(a)));for(let e=0;e<t.blocks.length;e++){let n=s.get(e);if(n!==void 0&&n>0){let e=o[n-1];e>0&&(yield new G(` `.repeat(e)))}yield*t.blocks[e].segments}yield G.line()}}measure(e){let t=this.items;if(t.length===0)return{minimum:0,maximum:0};let n=0,r=0;for(let i=0;i<t.length;i++){let a=P_(t[i],e).width,o=this.joiner?P_(vm(this.joiner,null,t[i],{index:i}),e).width:0,s=this.joiner?P_(vm(this.joiner,t[i],null,{index:i+1}),e).width:0;n=Math.max(n,a+o+s),r+=a,i>0&&(r+=this.gap*2,this.joiner&&(r+=P_(vm(this.joiner,t[i-1],t[i],{index:i}),e).width))}return this.joiner&&(r+=P_(vm(this.joiner,null,t[0],{index:0}),e).width,r+=P_(vm(this.joiner,t[t.length-1],null,{index:t.length}),e).width),{minimum:n,maximum:r}}};function B_(){let e=new WeakMap;return(t,n,r)=>{let i=e.get(t);i===void 0&&(i=new Map,e.set(t,i));let a=i.get(n);if(a!==void 0)return a;let o=r();return i.set(n,o),o}}const V_=(e,t)=>e===t;function H_(e){let t=Object.keys(e);return(n,r)=>t.every(t=>e[t](n[t],r[t]))}const U_=e=>(t,n)=>t.length===n.length&&t.every((t,r)=>e(t,n[r])),W_=[`primary`,`secondary`,`accent`],G_=[`darken-3`,`darken-2`,`darken-1`,`base`,`lighten-1`,`lighten-2`,`lighten-3`],K_={"darken-3":`-darken-3`,"darken-2":`-darken-2`,"darken-1":`-darken-1`,base:``,"lighten-1":`-lighten-1`,"lighten-2":`-lighten-2`,"lighten-3":`-lighten-3`,muted:`-muted`},q_=(e,t)=>`${e}${K_[t]}`,J_=(e,t,n,r)=>Uv(e,n,r),Y_=(e,t,n,r)=>Gv(e,e.get(`text-${t}`),n,r),X_=e=>({tones:[G_[e],G_[e+2],G_[e+1]],text:J_,activated:`muted`}),Z_=e=>({tones:[G_[3-e],G_[3+e],G_[3]],text:J_,activated:`muted`}),Q_=e=>({tones:[G_[3-e],G_[3+e]],text:J_,activated:`muted`}),$_={wide:Z_(2),widest:Z_(3),pair:Q_(2),"pair-wide":Q_(3)},ev=Object.keys($_),tv={muted:{tones:[`muted`,`base`],text:Y_,activated:`lighten-2`},deepest:X_(0),deeper:X_(1),middle:X_(2),brighter:X_(3),brightest:X_(4),...$_},nv=(e,t)=>e[t%e.length],rv=`accent`,iv=1/0,av={keystones:[],open:[`accent`,`primary`,`secondary`]},ov={door:[`bar-start`],start:[`line-start`],end:[`line-end`],ends:[`line-start`,`line-end`]},sv={primary:[`primary`],secondary:[`secondary`],alternate:[`primary`,`secondary`]};function cv(){let e=Object.entries(ov).flatMap(([e,t])=>Object.entries(sv).map(([n,r])=>[`${e}-${n}`,{hues:[`secondary`],run:iv,keystones:t,open:r}]));return Object.fromEntries(e)}const lv=cv(),uv={accent:{hues:[`secondary`,`accent`],run:iv,...av},duo:{hues:[`primary`,`secondary`],run:iv,...av},mono:{hues:[`primary`],run:iv,...av},alt:{hues:[`secondary`,`accent`],run:3,...av},...lv},dv=Object.keys(lv),fv={error:[`bright_red`,`red`],warning:[`bright_yellow`,`yellow`],success:[`bright_green`,`green`]},pv=(e,t,n)=>zv(e,t,t.variation.hues.flatMap(r=>{let i=mv(e,r,t.shade,n);return t.shade.tones.map((e,t)=>({hue:r,shade:i[t%i.length]}))}),n);function mv(e,t,n,r){return _v(e,`${t}|${n.tones.join(`,`)}|${r}`,()=>{let i=vv(e,t,r),a=gv(n.tones.length,new Set(G_.map(i)).size),[o,...s]=n.tones,c=[o];for(let e of s)c.length<a&&c.every(t=>i(t)!==i(e))&&c.push(e);return hv(Array.from({length:a-c.length}).reduce(a=>{let o=yv(e,t,n.tones,a.map(i),r);return o===void 0?a:[...a,o]},c))})}const hv=e=>{if(e.length<3)return e;let t=G_,[n,...r]=[...e].sort((e,n)=>t.indexOf(e)-t.indexOf(n));return[n,r.at(-1),...r.slice(0,-1)]},gv=(e,t)=>Math.max(2,Math.min(e,t-1)),_v=B_(),vv=(e,t,n)=>r=>fd(e.get(q_(t,r)),n).hex;function yv(e,t,n,r,i){let a=vv(e,t,i);return bv(n,e.dark).find(e=>!r.includes(a(e)))}function bv(e,t){let n=G_,r=e=>e===`muted`?t?-1:n.length:n.indexOf(e),i=t?1:-1;return G_.map((t,n)=>({rung:t,at:n,distance:Math.min(...e.map(e=>Math.abs(n-r(e))))})).filter(({distance:e})=>e>0).sort((e,t)=>e.distance-t.distance||(t.at-e.at)*i).map(({rung:e})=>e)}const xv=(e,t)=>Math.floor(e*t),Sv=(e,t)=>{let n=t-1;for(let t=e;t<.5&&n>0;t*=2)n--;return n},Cv=e=>{let t=0,n=.5;for(let r=e;r>0;r>>=1,n/=2)t+=n*(r&1);return t},wv=[`van-der-corput`,`golden-angle`,`ends-interleaved`,`monotonic`,`uniform`],Tv=e=>typeof e==`string`&&wv.includes(e),Ev={"van-der-corput":{place:Cv,quantize:Sv},"golden-angle":{place:e=>e*.6180339887498949%1,quantize:xv},"ends-interleaved":{place:(e,t)=>((e%2==0?e/2:t-1-(e-1)/2)+.5)/t,quantize:xv},monotonic:{place:(e,t)=>(e+.5)/t,quantize:xv},uniform:{place:()=>.5,quantize:Sv}},Dv=e=>Ev[e??`van-der-corput`];function Ov(e,t){if(e===void 0)return 0;let{place:n,quantize:r}=e.distribution;return r(n(e.index,e.count),t)}function kv(e,t){let n=e[Ov(t,e.length)];if(n===void 0)throw Error(`vocabularySelect: empty vocabulary`);return n}function Av(e){let t=e=>e.axis===`cell`,n=e.findIndex(t);return{row:(n===-1?e:e.slice(0,n)).at(-1),cell:e.findLast(t)}}const jv=(e,t)=>Ov(t,e.hues.length);function Mv(e,t,n,r){let{row:i,cell:a}=Av(n);return a===void 0?Nv(e,t,i,a,r):Pv(e,t,i,a,r)[a.index-a.lineStart]}function Nv(e,t,n,r,i){let{hues:a,run:o,keystones:s}=t.variation,c=r===void 0?0:Math.floor(r.index/o),l=a[(jv(t.variation,n)+c)%a.length];if(l===void 0)throw Error(`decorEntryFor: empty variation`);let u=s.some(e=>Bv[e](n,r))?rv:l;return{hue:u,shade:kv(mv(e,u,t.shade,i),r)}}function Pv(e,t,n,r,i){let{hues:a,run:o,keystones:s,open:c}=t.variation;return Fv(e,[a.join(`,`),o,s.join(`,`),c.join(`,`),t.shade.tones.join(`,`),t.shade.activated,n===void 0?``:Iv(n),Iv(r,r.lineStart),i].join(`|`),()=>zv(e,t,Array.from({length:r.lineEnd-r.lineStart+1},(a,o)=>Nv(e,t,n,{...r,index:r.lineStart+o},i)),i))}const Fv=B_();function Iv({axis:e,index:t,count:n,distribution:r,lineStart:i,lineEnd:a,...o},s=t){return`${e},${s},${n},${Lv(r)},${i},${a}`}function Lv(e){let t=Rv.get(e);if(t===void 0)throw Error(`decorEntryFor: a cell placed outside DISTRIBUTIONS`);return t}const Rv=new Map(wv.map(e=>[Ev[e],e]));function zv(e,t,n,r){let i=[...n],a=t=>{let n=i[t];return n&&vv(e,n.hue,r)(n.shade)},o=Zv(e,{decor:t,depth:0},r),s=(n,o)=>{let{hue:s}=i[n],c=[a(n-1),a(n+1),...o].filter(e=>e!==void 0),l=mv(e,s,t.shade,r),u=l.find(t=>!c.includes(vv(e,s,r)(t)))??yv(e,s,l,c,r);return u===void 0?void 0:{hue:s,shade:u}},c=e=>[[o],[]].flatMap(t=>[e,e-1].map(e=>({place:e,off:t})));for(let e=1;e<i.length;e++)if(!(i[e-1].hue===i[e].hue||a(e-1)!==a(e)))for(let{place:t,off:n}of c(e)){let e=s(t,n);if(e!==void 0){i[t]=e;break}}return i}const Bv={"bar-start":(e,t)=>(e?.index??0)===0&&(t?.index??0)===0,"line-start":(e,t)=>t===void 0||t.index===t.lineStart,"line-end":(e,t)=>t===void 0||t.index===t.lineEnd},Vv=(e,t)=>e.get(q_(t.hue,t.shade)),Hv=4.5;function Uv(e,t,n){return Wv(e,`${t.hex}|${n}`,()=>{let r=ud(t);return Gv(e,[`background`,`foreground`].map(t=>e.get(t)).reduce((e,t)=>Gl(r,t)<Gl(r,e)?t:e),t,n)})}const Wv=B_();function Gv(e,t,n,r){return Kv(e,`${t.hex}|${n.hex}|${r}`,()=>dd(t,n,Hv,r))}const Kv=B_(),qv=({decor:e,depth:t})=>nv(e.variation.open,t),Jv=(e,t,n)=>mv(e,qv(t),t.decor.shade,n).map(e=>({hue:qv(t),shade:e}));function Yv(e,t,n){let{decor:r,depth:i}=t,{variation:a,shade:o}=r;return Xv(e,[i,a.open.join(`,`),a.hues.join(`,`),a.keystones.length,o.tones.join(`,`),o.activated,n].join(`|`),()=>{let s=qv(t),c=t=>mv(e,t,o,n).map(vv(e,t,n)),l=a.keystones.length>0?[rv]:[],u=i===0?[...a.hues,...l].flatMap(c):(t=>[...c(qv(t)),Zv(e,t,n)])({decor:r,depth:i-1}),d=[...c(s),...u];return d.includes(vv(e,s,n)(o.activated))?yv(e,s,[o.activated],d,n)??o.activated:o.activated})}const Xv=B_(),Zv=(e,t,n)=>vv(e,qv(t),n)(Yv(e,t,n)),Qv=e=>({...e,depth:e.depth+1});function $v(e,t,n){return{state:e.get(q_(qv(t),Yv(e,t,n))),plane:e.get(`surface`),items:Jv(e,t,n).map(t=>Vv(e,t))}}function ey(e,t,n,r){return kv($v(e,t,r).items,n)}function ty(e,t,n,r){let i=ey(e,t,n,r);return{tint:i,text:t.decor.shade.text(e,qv(t),i,r)}}function ny(e,t){switch(e.kind){case`bar`:return t.kind===`bar`&&oy(e,t);case`band`:return t.kind===`band`&&sy(e,t)}}const ry=U_(H_({index:V_,count:V_,distribution:V_,axis:V_,lineStart:V_,lineEnd:V_})),iy=H_({variation:V_,shade:V_}),ay=H_({decor:iy,depth:V_}),oy=H_({kind:V_,decor:iy,address:ry}),sy=H_({kind:V_,band:ay,address:ry}),cy=e=>({kind:`bar`,decor:e,address:[]}),ly=(e,t)=>({...e,address:[...e.address,t]}),uy=e=>({kind:`band`,band:e,address:[]});function dy(e,t,n){switch(t.kind){case`bar`:{let{decor:r,address:i}=t,a=Mv(e,r,i,n),o=Vv(e,a);return{tint:o,text:r.shade.text(e,a.hue,o,n),disclosure:{decor:r,depth:0}}}case`band`:{let{band:r,address:i}=t;return{...ty(e,r,Av(i).cell,n),disclosure:Qv(r)}}}}const fy=new Map([[`dark`,`textual-dark`],[`light`,`textual-light`]]);function py(e){let t=typeof e==`string`?fy.get(e):void 0;return t===void 0?``:` — "${e}" was retired; write "${t}", the same palette`}const my=`textual-dark`;function hy(e,t,n,r,i){let a=t===null?null:i(t);return e??a??n??r}function gy(){return qd()}function _y(){return[`bar`,...gy()]}let vy;function yy(e){return vy??=new Set(_y()),vy.has(e)}function by(e,t,n,r,i){let a=e=>Object.prototype.hasOwnProperty.call(i,e)?e:null;return hy(e===void 0?null:a(e),t,a(n??r),r,a)}const xy=[`style`,`palette`,`effect`];function Sy(e){return e!==void 0&&e.includes(`{{`)}function Cy(e,t,n,r,i){let a=Sy(n)?{kind:`expression`,source:n}:i(n??r.name);return hy(e===void 0?null:i(e),t,a,r,i)}const wy=`none`;function Ty(e,t){let n=t[e];return n===void 0?null:{kind:`decided`,name:e,value:n}}function Ey(e,t){return Ty(e,t)??Ty(`none`,t)??{kind:`decided`,name:`none`,value:Ru}}function Dy(e,t,n,r){return Cy(e,t,n,Ey(wy,r),e=>Ty(e,r))}const Oy=`none`,ky={style:wy,palette:my,effect:Oy};function Ay(e,t,n){return`${e} rendered "${ky[t]}": ${n}`}const jy=Object.freeze([Oy,...Object.keys(o_.loops)]),My=Object.freeze({"1x":1,"5x":5,"10x":10,"20x":20}),Ny=Object.keys(My),Py=Object.freeze([`bar`,...jy]);function Fy(e){let t=jy.find(t=>t===e);return t===void 0?null:{kind:`decided`,name:e,value:t}}function Iy(e){return Fy(e)??{kind:`decided`,name:`none`,value:`none`}}function Ly(e,t,n){return Cy(e,t,n,Iy(Oy),Fy)}const Ry=Object.freeze(Object.keys(wh)),Bee=[`powerline`,`capsule`,`plain`];function zy(e){return Bee.includes(e)}const By=[`truecolor`,`256`,`ansi`,`none`];function Vy(e){return By.includes(e)}function Hy(e){return iu(e)??H.DEFAULT}const Uy=Object.keys(uv),Wy=Object.keys(tv),Gy=`true`,Ky=`false`,qy=[Gy,Ky],Jy={min:0,max:16};function Yy(e){return e===`true`?!0:e===`false`?!1:null}function Xy(e,t){let n=Number(e);return Number.isInteger(n)&&String(n)===e&&n>=t.min&&n<=t.max?n:null}function Zy(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qy(e){return ae(`sha256`).update(JSON.stringify($y(e))).digest(`hex`)}function $y(e){return Array.isArray(e)?e.map($y):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,$y(t)])):e}const eb=[`vertical`,`horizontal`],tb={vertical:`row`,horizontal:`cell`};function nb(e){return e.id??e.name}function rb(e){return[...ob(e)].flatMap(e=>e.kind===`segment`?[nb(e)]:[])}function ib(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function ab(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*ob(e){yield e;for(let t of ub(e))yield*ob(t)}const sb=(e,t)=>`${e}.children[${t}]`,cb=e=>`${e}.opens.body`;function*lb(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*lb(r,sb(t,n));else e.opens!==void 0&&(yield*lb(e.opens.body,cb(t)))}function ub(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}function db(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const fb=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function pb(e){return e.kind===`file`||e.kind===`shell`}function mb(e,t){let n=e.kind===`template`?{...e,template:t(e.template,`template`)}:e;return pb(n)&&`key`in n.cache?{...n,cache:{...n.cache,key:t(n.cache.key,`cache.key`)}}:n}function hb(e){let t=[];return mb(e,(e,n)=>(t.push([n,e]),e)),t}const gb=[`fail`,`ignore`];function _b(e){return e.missingData??`fail`}function*vb(e){for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&(yield[t,n]);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&(yield[`${t}.${e}`,r])}const yb=`theme`,bb=`effect`,xb=[yb,bb];function Sb(e){return{...e.settings,[yb]:{label:yb,domain:`theme`,default:e.palette??`bar`},[bb]:{label:bb,domain:Py,default:`bar`}}}function Cb(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function wb(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=Cb(r)?.atLeast;if(i===void 0)return[];let a=t[n],o=t[i];return a>=o?[]:[{setting:n,message:`"${n}" (${a}) is below "${i}" (${o}) — ${r.label} must be at least ${e[i].label}`}]})}function Tb(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&yy(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function Eb(e){return String(e)}function Db(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return Xy(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return Tb(e,r)?r:void 0}function Vee(e,t,n,r){let i=e.drafts?.[t];if(i===void 0)return e.settings?.[t]??n.default;let a=r(i),o=Db(n,a);if(o===void 0)throw Error(`placement setting "${t}": its draft reads ${JSON.stringify(a)}, which its declaration does not admit (${Ob(n)})`);return o}function Ob(e){let{domain:t}=e;return t===`bool`?`true or false`:t===`theme`?`"bar" (the bar's own theme) or an installed theme name`:`min`in t?`an integer from ${t.min} to ${t.max}`:`one of ${t.map(e=>JSON.stringify(e)).join(`, `)}`}const Hee=[`left`,`center`,`right`],Uee=[`right`,`left`,`middle`];var kb=class extends Error{file;issues;warnings;constructor(e,t,n=[]){super(Zee(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t,this.warnings=n}},Wee=class extends kb{prompt;constructor(e,t){super(e,t),this.name=`DroppedFileError`,this.prompt=[`Fix my cc-candybar statusline config. It places segments that do not exist, so those cells are not drawn.`,`Config file to edit: ${e}`,this.message,`For each placement: rename it to a segment the error lists as declared (if it names a plugin file, read that file to confirm), or remove the placement. Edit only the config file; do not change any plugin file.`].join(`
55
55
 
56
- `)}},Wee=class extends Error{constructor(e){super(e.map(e=>e.message).join(`
57
- `)),this.errors=e,this.name=`DroppedPlacements`}};function J(e,t){return jb(e)(t)}function jb(e){let t,n=()=>(t??={node:Gee(e)},t.node);return t=>Kee(e,n,t)}function Gee(e){try{return Fa(e)}catch(e){if(e instanceof Pa)return;throw e}}function Kee(e,t,n){let r=n.some(e=>/^\d+$/.test(e))?qee(e,t(),n):void 0;if(r!==void 0)return r;let i=0,a;for(let t of n){if(t===``||/^\d+$/.test(t))continue;let n=Jee(e,i,t);if(n===-1)return a===void 0?void 0:Mb(e,a);i=n,a=n}return a===void 0?void 0:Mb(e,a)}function qee(e,t,n){if(t===void 0)return;let r=t,i,a=!1;for(let e of n){let t=r.kind===`array`&&/^\d+$/.test(e),n=r.kind===`array`?t?r.elements[Number(e)]:void 0:Ia(r,e)?.value;if(n===void 0)break;a||=t,r=n,i=n}return i===void 0||!a?void 0:Mb(e,i.span.start)}function Jee(e,t,n){let r=n.replace(/[\\^$.*+?()[\]{}|]/g,`\\$&`),i=RegExp(`(?:["']${r}["']|\\b${r}\\b)\\s*:`,`g`);i.lastIndex=t;let a=i.exec(e);return a?a.index:-1}function Mb(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Yee(e,t){try{return Fa(t),null}catch(n){if(!(n instanceof Pa))throw n;return`${e}:${Mb(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function Xee(e,t){if(t.length===0)return`${e}: invalid config (no details)`;let n=[`Invalid config in ${e} (${t.length} issue${t.length===1?``:`s`}):`];for(let e of t){let t=[];e.line!==void 0&&t.push(`line ${e.line}${e.col===void 0?``:`:${e.col}`}`),e.path&&t.push(e.path);let r=t.length>0?`[${t.join(` • `)}] `:``;n.push(` ${r}${e.message}`)}return n.join(`
58
- `)}function Nb(e,t,n,r){let i=n[r];return typeof i==`string`?i:(e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${Lb(i)}`,line:J(e.source,[...t.split(`.`),r])}),null)}function Zee(e,t,n,r){let i=n.default;if(i!==void 0){if(!(r===`string`&&typeof i==`string`||r===`number`&&typeof i==`number`||r===`boolean`&&typeof i==`boolean`)){e.issues.push({path:`${t}.default`,message:`default must be a ${r}, got ${Lb(i)}`,line:J(e.source,[...t.split(`.`),`default`])});return}return i}}function Pb(e,t,n,r){let i=n[r];if(i!==void 0){if(typeof i!=`string`){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${Lb(i)}`,line:J(e.source,[...t.split(`.`),r])});return}return i}}function Fb(e,t,n){let r=Pb(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${py(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[...t.split(`.`),`palette`])});return}return r}}function Ib(e,t,n,r,i){let a=n[r];if(a!==void 0){if(typeof a!=`string`||!i.includes(a)){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be one of: ${i.join(`, `)}; got ${Y(a)}`,line:J(e.source,[...t.split(`.`),r])});return}return a}}function Lb(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Y(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function Rb(e,t,n,r){return Qy(r)?(Vb(e,n,r,t.noun,new Set(Object.keys(t.fields)),zb(e,t.removed??{},n,r)),Bb(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${Lb(r)}`,line:J(e.source,n.split(`.`))}),null)}function zb(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)Hb(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function Bb(e,t,n,r){let i=t,a={},o=!0;for(let[t,s]of Object.entries(i)){let i=s.parse(e,n,t,r);i===void 0?s.required&&(o=!1):a[t]=i}return o?a:null}const Qee=new Set;function Vb(e,t,n,r,i,a=Qee){for(let o of Object.keys(n))!i.has(o)&&!a.has(`${t}.${o}`)&&e.issues.push({path:`${t}.${o}`,message:`Unknown ${r} "${o}". Expected one of: ${[...i].join(`, `)}`,line:J(e.source,[...t.split(`.`),o])})}function Hb(e,t,n){return e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))}),null}function Ub(e,t,n,r){if(!Qy(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${Lb(r)}`,line:J(e.source,n.split(`.`))}),null;let i=t.arms,a=Object.keys(i),o=Object.keys(r).filter(e=>e in i),s=Object.keys(r).filter(e=>!(e in i));for(let r of s)e.issues.push({path:`${n}.${r}`,message:`Unknown ${t.noun} key "${r}". Expected exactly one of: ${a.join(`, `)}`,line:J(e.source,[...n.split(`.`),r])});if(o.length===0)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)}`,line:J(e.source,n.split(`.`))}),null;if(o.length>1)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)} (found: ${o.join(`, `)})`,line:J(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function $ee(e,t,n,r){if(!Qy(r))return e.issues.push({path:n,message:`${n} must be an object, got ${Lb(r)}`,line:J(e.source,n.split(`.`))}),null;let i=r[t.tag];if(typeof i!=`string`)return e.issues.push({path:`${n}.${t.tag}`,message:`${n}.${t.tag} must be a string, got ${Lb(i)}`,line:J(e.source,n.split(`.`))}),null;let a=t.arms;if(!Object.hasOwn(a,i)){let o=Object.hasOwn(t.retired,i)?t.retired[i](r):`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`;return e.issues.push({path:`${n}.${t.tag}`,message:o,line:J(e.source,[...n.split(`.`),t.tag])}),null}let o=a[i],s=e.issues.length,c=o.parse(e,n,r),l=new Set(e.issues.slice(s).map(e=>e.path));return Vb(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function ete(e,t,n){return{json:ote(Zb(n),e,t),keys:new Set([e,...Object.keys(n)])}}function Wb(e){return(...t)=>e()(...t)}function tte(e,...t){return(n,r,i)=>{let a=e(n,r,i);if(a===null)return null;for(let e of t){if(e.ok(a))continue;let{field:t,message:i}=e.issue(a),o=t===``?r:`${r}.${t}`;return n.issues.push({path:o,message:i,line:J(n.source,o.split(`.`))}),null}return a}}function Gb(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Pb(e,t,r,n)}}function Kb(){return{required:!1,json:{type:`boolean`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`boolean`){e.issues.push({path:`${t}.${n}`,message:`${n} must be a boolean, got ${Lb(i)}`,line:J(e.source,[n])});return}return i}}}}function nte(e){let{min:t,max:n}=e;return{required:!1,json:{type:`integer`,minimum:t,maximum:n},parse:(e,r,i,a)=>{let o=a[i];if(o!==void 0){if(typeof o!=`number`||!Number.isInteger(o)||o<t||o>n){e.issues.push({path:`${r}.${i}`,message:`${i} must be an integer between ${t} and ${n}, got ${Y(o)}`,line:J(e.source,[i])});return}return o}}}}function qb(e={}){let{min:t}=e;return{required:!1,json:{type:`number`,...t!==void 0&&{minimum:t}},parse:(e,n,r,i)=>{let a=i[r];if(a!==void 0){if(typeof a!=`number`||!Number.isFinite(a)||t!==void 0&&a<t){let i=t===void 0?`a finite number`:`a finite number >= ${t}`;e.issues.push({path:`${n}.${r}`,message:`${r} must be ${i}, got ${Y(a)}`,line:J(e.source,[r])});return}return a}}}}function rte(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Fb(e,t,r)}}function Jb(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Nb(e,t,r,n)??void 0}}function Yb(e,t){return u(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function ite(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=Nb(e,t,r,n);if(i===null)return;let a=Yb(`${t}.${n}`,i);return a===null?i:Hb(e,`${t}.${n}`,a)??void 0}}}function Xb(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>Ib(t,n,i,r,e)}}function Zb(e,t={closed:!0}){let n=e,r={},i=[];for(let[e,t]of Object.entries(n))r[e]=t.json,t.required&&i.push(e);return{type:`object`,properties:r,...i.length>0&&{required:i},...t.closed&&{additionalProperties:!1}}}function ate(e){return Zb(e.fields)}function ote(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function ste(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function Qb(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const $b=(e,t)=>Array.from({length:e*2},(e,n)=>({lit:n%2==0,seconds:t})),ex=[...$b(3,1),...$b(3,.25)],cte=ex.reduce((e,{seconds:t})=>e+t,0),lte={min:15,max:600,step:15},ute=(e,t)=>e+t,dte=e=>e-cte,tx=(e,t,{previews:n=[],shown:r=`true`}={})=>({label:e,place:t,previews:n,shown:r}),nx=(e,t,n={})=>({spec:Xb(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e,...n}}}),rx=e=>t=>e.includes(t)?`🧪 ${t}`:t,fte={spec:Kb(),domain:`bool`,parse:Xy},pte=e=>({spec:nte(e),domain:e,parse:t=>Zy(t,e)});function ix(e,t,n,r={}){return{kind:`session`,...nx(e,r.optionDomain,{library:r.library,labelOf:r.labelOf}),floor:t,control:n,themeDefault:r.themeDefault??!1}}function ax(e,t){return{kind:`session`,...fte,floor:e,control:t,themeDefault:!1}}function ox(e,t,n){return{kind:`session`,...pte(e),floor:t,control:n,themeDefault:!1}}function sx(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const cx=e=>({kind:`text`,spec:e}),mte={required:!1,json:{enum:[...Vy]},parse:(e,t,n,r)=>{if(r[n]===`auto`){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: "auto" is not supported — the render daemon runs detached, so terminal detection would read the daemon's environment, not your terminal's. Pick an explicit depth: ${Vy.join(`, `)}`,line:J(e.source,[...t.split(`.`),n])});return}return Ib(e,t,r,n,Vy)}},hte={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=Pb(e,t,r,n);return Sy(i)?i:Fb(e,t,r)}},gte={required:!1,json:{anyOf:[{enum:[...jy]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Sy(i)?i:Ib(e,t,r,n,jy)}},lx=/^[^\r\n]*\S[^\r\n]*$/u,ux=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),_te={required:!1,json:{type:`string`,pattern:lx.source,not:{pattern:ux.source}},parse:(e,t,n,r)=>{let i=Pb(e,t,r,n);if(i===void 0||lx.test(i)&&!ux.test(i))return i;e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: must be one line of visible text other than a close glyph ("✖", "✕") — the settings menu needs a glyph to click`,line:J(e.source,[...t.split(`.`),n])})}},vte=Object.fromEntries($c.map(e=>[Zc[e].switch.setting,ax(!1,tx(Zc[e].label,`toggles`))])),yte={claude:`Claude Code's status line`,tmux:`the tmux status line, while this pane is shown`},bte={groups:[{id:`renderer`,label:`draw the bar in`}],entry:e=>({group:`renderer`,description:yte[e]})},dx={palette:sx(`theme`,hte,{themes:`themes`},tx(`🎨 theme`,`door`)),preset:sx(`preset`,Gb(),{from:`presets`},tx(`▦ preset`,`door`,{previews:[`layout`,`presetDelete`]})),style:sx(`style`,Gb(),{from:`styles`},tx(`◐ style`,`gear`,{previews:[`palette`]}),{themeDefault:!0}),effect:sx(`effect`,gte,{from:jy},tx(`✨ effect`,`look`)),endcaps:ix(Ry,`powerline`,tx(`✦ endcaps`,`look`),{optionDomain:`endcaps`}),variation:ix(Wy,`accent`,tx(`🎼 variation`,`gear`,{previews:[`layout`]}),{optionDomain:`variations`,labelOf:rx(dv),themeDefault:!0}),shade:ix(Gy,`middle`,tx(`🔆 shade`,`gear`,{previews:[`layout`]}),{optionDomain:`shades`,labelOf:rx(ev),themeDefault:!0}),transitions:ax(!1,tx(`fade in/out`,`look`)),animationSpeed:ix(Ny,`1x`,tx(`speed`,`look`)),autoWrap:ax(!0,tx(`wrap`,`config`)),padding:ox({...Yy,step:1},1,tx(`padding`,`config`)),updateNotice:ax(!0,tx(`update notice`,`config`)),menuTimeout:ox(lte,120,tx(`menu timeout`,`config`)),renderer:ix(Yc,`claude`,tx(`renderer`,`config`,{shown:Xc}),{optionDomain:`renderers`,library:bte}),...vte,colorCompatibility:{kind:`config`,...nx(Vy,`colorCompatibilities`),spec:mte,floor:`truecolor`},default_empty_value:cx(Gb()),default_separator:cx(Gb()),menuGlyph:cx(_te)},fx=Object.entries(dx),px=fx.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),xte=fx.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),mx=fx.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),hx=fx.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function gx(e){return dx[e]}const _x=e=>gx(e).floor;function vx(e){let t=dx[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const yx=e=>`${e}.effective`,bx=e=>{let t=dx[e];return t.kind===`selection`?t.sessionKey:e},xx=Object.fromEntries(xte.map(e=>{let t=bx(e);return[t,{configKey:e,sessionKey:t,effectiveVar:yx(t),...dx[e].control}]})),Sx=Object.keys(xx),Cx=Object.values(xx),wx=px.filter(e=>dx[e].kind===`config`).map(e=>({configKey:e,effectiveVar:yx(e)})),Tx=new Set(wx.map(e=>e.configKey)),Ex=new Map([...Cx,...wx].map(e=>[e.configKey,e.effectiveVar])),Dx=new Map(Cx.map(e=>[e.sessionKey,e.effectiveVar]));function Ox(e){return Object.fromEntries(Sx.map(t=>[t,e(t)]))}const kx=new Map(Sx.map(e=>[xx[e].sessionKey,e])),Ax=new Map;function jx(e){let t=Nx(e);if(t===null)throw Error(`Palette "${e}" did not resolve in the theme registry — allowed names and the registry are inconsistent`);return t}function Mx(e,t){return e===`bar`?t:jx(e)}function Nx(e){let t=Ax.get(e);if(t!==void 0)return t;let n=Jd(e);return n===null?null:(Ax.set(e,n),n)}function Px(e,t){return Fx(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>tf(e,t))}const Fx=B_();function Ix(e){let t=Nx(e);return t===null?null:{kind:`decided`,name:e,value:t}}function Lx(e,t,n){let r=Ix(e);return r===null?(n(Ay(t,`palette`,`"${e}" names no installed theme${py(e)}`)),zx()):r}function Rx(e,t,n){return Cy(e,t,n,zx(),Ix)}function zx(){return{kind:`decided`,name:my,value:jx(my)}}const Bx=/^[A-Za-z_][A-Za-z0-9_]*$/;function Vx(e){return`#${e+1}`}const Hx={rows:{}};function Ux(e){return`rows`in e}function Wx(e){return Object.fromEntries(e.map((e,t)=>[Vx(t),e]))}function Ste(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:Wx(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:Wx([n])}}function Gx(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function Kx(e){return Ux(e)?Gx(e):e}function*qx(e,t){if(!Ux(e)){yield*ub(e,t);return}yield[Gx(e),t];for(let[n,r]of Object.entries(e.rows))yield*ub(r,`${t}.rows.${n}`)}function Jx(e,t){return Ux(e)?{...t,...e,rows:{...t.rows,...e.rows}}:Ste(e)}function Yx(e,t){return t.reduce((e,t)=>{let n=t.id??t.seg,r=[...sb(Gx(e.root))].flatMap(e=>e.kind===`segment`?[e]:[]);if(r.some(e=>e.name===t.seg&&(t.id===void 0||rb(e)===t.id)))return e;let i=r.find(e=>rb(e)===n);if(i!==void 0)return Xx(e,t,`as "${n}", but placement "${n}" is already segment "${i.name}" — give the cell its own id`);let a={kind:`segment`,name:t.seg,...t.id!==void 0&&{id:t.id},insertedBy:t.by},o=Object.entries(e.root.rows).map(([e,n])=>[e,n,Zx(n,t.anchor,a,t.relation)]);return o.some(([,,e])=>e!==null)?{...e,root:{...e.root,rows:Object.fromEntries(o.map(([e,t,n])=>[e,n??t]))}}:Xx(e,t,`${t.relation} "${t.anchor}", but there is no placement "${t.anchor}"`)},{root:e,unplaced:[]})}function Xx(e,t,n){return{...e,unplaced:[...e.unplaced,{cell:t,reason:n}]}}function Zx(e,t,n,r){if(e.kind===`segment`&&rb(e)===t){let{when:t,...i}=e;return{kind:`container`,direction:`horizontal`,children:r===`before`?[n,i]:[i,n],...t!==void 0&&{when:t}}}return e.kind===`container`?Qx(e,t,n,r):$x(e,t,n,r)}function Qx(e,t,n,r){let i=e.children.findIndex(e=>e.kind===`segment`&&rb(e)===t);if(i>=0){let t=r===`before`?i:i+1,{when:a}=e.children[i];return{...e,children:[...e.children.slice(0,t),{...n,...a!==void 0&&{when:a}},...e.children.slice(t)]}}for(let[i,a]of e.children.entries()){let o=a.kind===`container`?Qx(a,t,n,r):$x(a,t,n,r);if(o!==null)return{...e,children:e.children.map((e,t)=>t===i?o:e)}}return null}function $x(e,t,n,r){let i=!1,a=ob(e,e=>{let a=Qx(e,t,n,r);return i=a!==null,a??e});return i?a:null}function eS(e){if(!Ux(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const tS=`default`,nS={};function rS(e){return[...new Set([tS,...Object.keys(e)])]}function iS(e,t,n){return by(void 0,e,t,tS,n)}function aS(e,t){let n={[tS]:nS,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${tS}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function oS(e,t){let n=aS(e.presets,t).root??Hx;return{node:Gx(Jx(n,e.root)),path:eS(n)?`presets.${t}.root`:`root`}}function sS(e,t,n){if(t.length===0)return{config:e,notices:[]};let r=Yx(e.root,t),i=Object.entries(e.presets).filter(([,e])=>eS(e.root??Hx)).map(([n,r])=>({name:n,preset:r,...Yx(Jx(r.root??Hx,e.root),t)})),a=new Map,o=e=>({cell:t,reason:n})=>{let r=a.get(t)??new Map;r.set(n,[...r.get(n)??[],e]),a.set(t,r)};(n.root?r.unplaced:[]).forEach(o(`the root`));for(let{name:e,unplaced:t}of i.filter(({name:e})=>n.presets.has(e)))t.forEach(o(`preset "${e}"`));return{config:{...e,root:r.root,presets:{...e.presets,...Object.fromEntries(i.map(({name:e,preset:t,root:n})=>[e,{...t,root:Gx(n)}]))}},notices:[...a].flatMap(([e,t])=>[...t].map(([t,n])=>cS(e,`${t} (in ${n.join(`, `)})`)))}}function cS(e,t){return`${e.by.file}: ${e.by.entry} places "${e.seg}" ${t}`}function lS(e,t){return{...e.globals,...aS(e.presets,t).globals}}const uS=new Map;function dS(e,t,n={}){uS.set(e,{permanent:!0,resolve:t,...n})}dS(`themes`,()=>gy(),{paletteOf:e=>jx(e)});const fS=`placementThemes`;dS(fS,_y,{paletteOf:(e,t)=>Mx(e,t.palette)});for(let{name:e,members:t,library:n,labelOf:r}of hx)dS(e,()=>t,{library:n,labelOf:r});function Cte(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>Px(n.basePalette,e.styles[t])}],[`presets`,{members:rS(e.presets)}]])}function pS(e){return[...new Set([...uS.keys(),...e.keys()])]}function mS(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=uS.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf,library:r.library,labelOf:r.labelOf};throw Error(gS(e,t))}const hS=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function gS(e,t){let n=hS.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${pS(t).join(`, `)})`}const _S=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`slash`,`run`,`do`];function vS(e){return JSON.stringify([e.run,Object.entries(e.env),e.cwd,e.refreshes])}function*yS(e){let t=[];bS(e,(e,n)=>(t.push([n,e]),e)),yield*t}function bS(e,t){if(`copy`in e)return{...e,copy:t(e.copy,`copy`)};if(`open`in e)return{...e,open:t(e.open,`open`)};if(`preset`in e&&e.preset===`delete`)return{...e,name:t(e.name,`name`)};if(`run`in e){let n=e.run.map((e,n)=>t(e,`run.${n}`));return{...e,run:n,env:Object.fromEntries(Object.entries(e.env).map(([e,n])=>[e,t(n,`env.${e}`)]))}}return e}function xS(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}const SS=`groups.`,CS=`menus.`,wS=`menupages.`,TS=`edit.`,ES=`candybar.`,DS=[SS,CS,wS,TS,ES];function OS(e){return DS.some(t=>e.startsWith(t))}const kS=`${ES}menu`,AS=ha,jS={variable:kS,key:kS,member:AS},MS=`${ES}diagnostics`,NS=`${da}://`,PS=`dispatch`,FS=`set-state`,IS=`step-state`,LS=`copy-text`,RS=`open-in-vscode`,zS=`toolbar-toggle`,BS=`set-config`,VS=`step-config`,HS=`save`,US=`save-preset`,WS=`save-theme-default`,GS=`delete-preset`,KS=`reset-config`,qS=`apply-layout-op`,JS=`undo`,YS=`redo`,XS=`back`,ZS=`rewind`,QS=`apply-update`,$S=`doctor-run`,eC=`doctor-fix`,tC=`doctor-mark`,nC=`probe`,rC=[PS,nC];function wte(e){return rC.includes(e)}const iC=`slash`,aC=`repo-config`,oC=`copy-diagnostic`,sC=`range`,cC=[...rC,sC],lC=(e,t)=>`step ${e} ${t.startsWith(`-`)?`down`:`up`} by ${t.replace(`-`,``)}`,uC=(e,t)=>e.startsWith(t)?e.slice(t.length):e;function Tte(e,t){if(e===MS)return`${t===`0`?`close`:`open`} diagnostics`;let n=`set ${e} to ${t}`;if(!OS(e))return n;let r=uC(uC(e,wS),CS);return e.startsWith(`menupages.`)?`turn ${r} to page ${Number(t)+1}`:t===`closed`?`close ${r}`:t===`open`?`open ${r}`:e.startsWith(`menus.`)?`open ${t}`:n}function Ete(e){let t=[...e];return t.length<=60?e:`${t.slice(0,28).join(``)}...${t.slice(-28).join(``)}`}const Dte={[FS]:([,...e])=>e.flatMap((t,n)=>n%2==0?[Tte(t,e[n+1])]:[]),[IS]:([,e,t])=>[lC(e,t)],[LS]:([,e])=>[`copy ${Ete(e)}`],[RS]:([,e])=>[`open ${e} in vs code`],[zS]:()=>[`toggle the toolbar`],[BS]:([,e,t])=>[`save ${e} as ${t}`],[VS]:([,e,t])=>[`save ${lC(e,t)}`],[HS]:()=>[`save settings`],[US]:()=>[`save as a new preset`],[WS]:()=>[`save this look for the theme`],[GS]:([,e])=>[`delete preset ${e}`],[KS]:([,...e])=>e.map(e=>`reset ${e}`),[qS]:([,e,t])=>[`edit ${t} in ${e}`],[JS]:()=>[`undo`],[YS]:()=>[`redo`],[XS]:()=>[`go back`],[ZS]:()=>[`cancel edits`],[QS]:()=>[`update cc-candybar`],[$S]:()=>[`run doctor`],[eC]:([,e])=>[`fix ${e}`],[tC]:([,e,t])=>[`mark ${e} ${t}`],[iC]:([,e])=>[`type ${e}`],run:([,e])=>[`run ${e}`],[aC]:([,e,t])=>[`mark config in ${e} ${t}`],[oC]:()=>[`copy diagnostic`]},Ote=e=>encodeURIComponent(e).replaceAll(`%20`,`+`).replaceAll(`%2F`,`/`).replaceAll(`%3A`,`:`);function kte(e){let t=e=>e.verb===`set-state`||e.verb===`step-state`,[n=`nothing`,...r]=[...e.filter(e=>!t(e)),...e.filter(t)].flatMap(e=>Dte[e.verb](e.args));return r.length>0?`${n} and ${r.length} more`:n}function dC(e){return e.map(encodeURIComponent).join(`/`)}function Ate(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function fC(e,t,n=kte(t)){let r=t.map(e=>`e=${encodeURIComponent(`${e.verb}/${dC(e.args)}`)}`);return pC(e,PS,[`does=${Ote(n)}`,...r].join(`&`))}function jte(e,t){return pC(e,nC,encodeURIComponent(t))}function pC(e,t,n){return`${NS}to/${e}/${t}/${n}`}function mC(e){return new r(e).getAll(`e`).map(vC)}const hC=new Set([FS,KS]);function gC(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&_C(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function _C(e,t){if(e.verb!==t.verb||!hC.has(e.verb))return;let[n,r]=[vC(e.value),vC(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function vC(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}function yC(e){if(!e.startsWith(NS))return{ok:!1,problem:`expected a ${NS} link, got: ${e}`};let t=e.slice(NS.length);if(!t.startsWith(`to/`))return{ok:!1,problem:`the link is in ${t.includes(`/`)?`the direct verb form ${NS}<verb>/…`:`the bare copy form ${NS}<value>`}, which names no renderer: ${e}`};let n=t.slice(3),r=n.indexOf(`/`);if(r===-1)return{ok:!1,problem:`the link names a renderer and no click: ${e}`};try{return xC(n.slice(r+1),We(n.slice(0,r)))}catch(e){return{ok:!1,problem:e.message}}}function bC(e){if(!pa(e))return null;let t=e.slice(NS.length).split(`%`)[0];if(!t.startsWith(`to/`))return`to/`.startsWith(t)?null:`in a grammar older than names, which names no renderer`;let[,,n,...r]=t.split(`/`);return n===void 0||r.length===0||cC.includes(n)?null:`naming the verb "${n}", which a link never names: a link names ${cC.join(`, `)}`}function xC(e,t){let n=e.indexOf(`/`);if(n===-1)return{ok:!1,problem:`the link carries no verb: ${e}`};let r=e.slice(0,n);try{return{ok:!0,to:t,verb:decodeURIComponent(r),value:e.slice(n+1)}}catch{return{ok:!1,problem:`the link's verb is malformed: ${r}`}}}const SC=[`plugins`,`repo`];function CC({scope:e,name:t}){return`${e}.${t}`}function wC(e){return t=>t===e||t.startsWith(`${e}.`)}const TC=`self`;function EC(e){return SC.find(t=>e===t||e.startsWith(`${t}.`))}function DC(e,t){let n=EC(e);if(n===void 0||n===e)return``;let r=SC.filter(e=>e!==n).map(t=>`${t}${e.slice(n.length)}`).find(t);return r===void 0?``:` ("${r}" is declared: a repository's own plugins are named under repo., installed ones under plugins., and a name in one is never looked up in the other)`}const OC=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*kC(e){let t=e.indexOf(`{{`);for(;t!==-1;){let n=``,r=t+2,i=[[0,r]];for(;r<e.length&&!e.startsWith(`}}`,r);){if(e.startsWith(`/*`,r)){let t=e.indexOf(`*/`,r+2);r=t===-1?e.length:t+2,i.push([n.length,r]);continue}let t=r,a=e[r];if(r+=1,a===`"`||a===`'`||a==="`"){for(;r<e.length&&e[r]!==a;)r+=e[r]===`\\`&&a!=="`"?2:1;r+=1}n+=e.slice(t,r)}if(r>=e.length)return;yield{text:n,at:e=>{let[t,n]=i[0];for(let[r,a]of i)r<=e&&([t,n]=[r,a]);return n+e-t}},t=e.indexOf(`{{`,r+2)}}const AC=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,jC=RegExp(`^(?:(\\$)(?:\\.(${AC}))?|\\.(${AC})?)(?=[\\s)]|$)`);function MC(e,t,n){let r=jC.exec(e.trimStart());if(r===null)return null;let[i,a]=r[1]===void 0?[t,r[3]]:[n,r[2]];return i===null?null:a===void 0?i:`${i}${a}.`}const NC=/^(\w+)\b\s*([\s\S]*)$/;function*PC(e,t){let n=[t];for(let r of kC(e)){let e=r.text.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=NC.exec(e)??[],o=n[n.length-1],s=n.length>1?n[n.length-2]:o;if(i===`end`){n.length>1&&n.pop();continue}if(i===`else`){yield{code:e,dot:s,block:r};let i=/^with\b([\s\S]*)$/.exec(a);n[n.length-1]=i===null?s:MC(i[1],s,t);continue}yield{code:e,dot:o,block:r},i===`if`&&n.push(o),i===`with`&&n.push(MC(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const FC=/(?<![.$])\btemplate\s+$/;function*IC(e,t,n){let r=0;for(let i of[...e.matchAll(OC)]){let a=i.index+i[0].length;FC.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:MC(e.slice(a),t,n),index:i.index}),r=a}}function*LC(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...PC(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...IC(s,c,i)]){let i=Object.hasOwn(t,e.name)?t[e.name]:void 0,a=`${e.name}\0${e.at??`\0`}`;i===void 0||o.has(e.name)||n.has(a)||(n.add(a),yield*r(i,e.at,e.name,new Set([...o,e.name])))}}}yield*r(e,``,null,new Set)}function RC(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const zC=new WeakMap;function BC(e,t){let n=zC.get(t);return n===void 0&&(n=RC(e=>[...LC(e,t)]),zC.set(t,n)),n(e)}const VC=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${AC})`,`g`);function*HC({code:e,dot:t,root:n}){let r=e.replace(OC,``);for(let e of[...r.matchAll(VC)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function UC(e,t){let n=new Map;for(let r of BC(e,t))for(let e of HC(r))n.has(e)||n.set(e,r.via);return n}const WC=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,GC={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*KC(e){let t=0,n=0,r=`action`;for(let i of[...e.matchAll(OC)]){let a=e.slice(t,i.index),o=WC.exec(a);o===null?a.trim()!==``&&(n=0):(n=GC[o[1]],r=o[1]===`action`?`action`:`options`),n>0&&(yield{name:i[0].slice(1,-1),site:r,index:i.index},n--),t=i.index+i[0].length}}function qC(e,t){let n=new Map;for(let{code:r,via:i}of BC(e,t))for(let{name:e,site:t}of KC(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}function JC(e,t){let n=new Map;for(let{code:r,via:i}of BC(e,t))for(let e of r.matchAll(OC)){let t=e[0].slice(1,-1),r=bC(t);if(r===null)continue;let a=`${t}\0${i??`\0`}`;n.has(a)||n.set(a,{literal:t,problem:r,via:i})}return[...n.values()]}const YC=e=>Object.keys(GC).filter(t=>GC[t]>=e).join(`|`),XC=RegExp(`(?<![\\w.$])(?:(?:${YC(1)})\\s+|(?:${YC(2)})\\s+""\\s+)(?=[^\\s"\`)|}])`);function ZC(e,t){for(let{code:n}of BC(e,t))if(XC.test(n.replace(OC,`""`)))return!0;return!1}const QC=/(?<![\w.$])[A-Za-z_]\w*/g;function $C(e,t){let n=new Set;for(let{code:r}of BC(e,t))for(let[e]of r.replace(OC,``).matchAll(QC))n.add(e);return n}function ew(e,t){return new Set([...tw(e,t)].filter(e=>Object.hasOwn(t,e)))}function tw(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of BC(e,t))for(let{name:e}of IC(r,i,a))n.add(e);return n}const nw=e=>RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.${e}(?![A-Za-z0-9_])`,`g`);function rw(e,t,n){let r=nw(t),i=wC(t),a=[];for(let{dot:t,block:n}of PC(e,``)){let e=n.text.replace(OC,e=>` `.repeat(e.length));for(let i of e.matchAll(r))(i[1]===`$`?``:t)===``&&a.push(n.at(i.index+i[1].length+1));for(let{name:e,index:r}of[...IC(n.text,t,``),...KC(n.text)])i(e)&&a.push(n.at(r+1))}return[...new Set(a)].sort((e,t)=>t-e).reduce((e,r)=>e.slice(0,r)+n+e.slice(r+t.length),e)}function*iw(e){for(let[t,n]of Object.entries(e.variables))yield[t,n,[`variables`,t]];for(let[t,n]of Object.entries(e.segments))for(let[e,r]of Object.entries(n.vars??{}))yield[`${t}.${e}`,r,[`segments`,t,`vars`,e]]}function*aw(e){for(let[t,n]of iw(e))yield[t,n]}function ow(e,t){let n=e.split(`.`);for(let e=n.length;e>0;e--){let r=n.slice(0,e).join(`.`);if(t.has(r))return[r]}let r=`${e}.`;return[...t].filter(e=>e.startsWith(r))}function sw(e,t){return ow(e,t.names).some(n=>!e.startsWith(`${n}.`)||t.documents.has(n))}function cw(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),lw(r)&&n.add(e)};for(let[t,n]of aw(e))r(t,n);return{names:t,documents:n,helpers:e.helpers}}function lw(e){return e.kind===`dropped`||e.kind===`source`||(e.kind===`shell`||e.kind===`file`)&&fb(e.parse)===`json`}var uw=De((e=>{function t(e,...t){throw Error(`[MobX] minified error nr: ${e}${t.length?` `+t.map(String).join(`,`):``}. See mobx.js.org/errors`)}function n(e){let t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function r(e){return typeof e==`function`}function i(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function a(e){return typeof e==`object`&&!!e}function o(e){if(!a(e))return!1;let t=Object.getPrototypeOf(e);if(t==null)return!0;let n=p(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===Bt}function s(e){let t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function c(e,t,n){It(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function l(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return a(e)&&!0===e[n]}}function u(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function d(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function f(e){return e===null?null:typeof e==`object`?``+e:e}function p(e,t){return Lt.hasOwnProperty.call(e,t)}function m(e,t){return!!(e&t)}function h(e,t,n){return n?e|=t:e&=~t,e}function g(e,t=Vt,n=Vt){let r=new Wt(e);return t!==Vt&&(r.onBOL=new Set([t])),n!==Vt&&(r.onBUOL=new Set([n])),r}function _(e,t){return kt(e,t)}function v(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||Qe(e)?e:Array.isArray(e)?sn.array(e,{name:n}):o(e)?sn.object(e,void 0,{name:n}):u(e)?sn.map(e,{name:n}):d(e)?sn.set(e,{name:n}):typeof e!=`function`||Ve(e)||Ye(e)?e:s(e)?Gn(e):Ln(n,e)}function y(e){return e}function b(e,t){return{t:e,i:t,o:x,u:S}}function x(e,t,n,r){var i;return(i=this.i)!=null&&i.bound?this.u(e,t,n,!1)===null?0:1:r===e.h?this.u(e,t,n,!1)===null?0:2:Ve(n.value)?1:(It(r,t,w(e,this,t,n,!1)),2)}function S(e,t,n,r){let i=w(e,this,t,n);return e.l(t,i,r)}function C(e,n,r){let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>{var t;return he(s.i?.name??a.toString(),e,(t=s.i?.autoAction)!=null&&t)};return i==`field`?function(e){var t;let n=e;return Ve(n)||(n=c(n)),(t=s.i)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n}:i==`method`?(Ve(n)||(n=c(n)),(l=s.i)!=null&&l.bound&&o(function(){let e=this,t=e[a].bind(e);t.isMobxAction=!0,e[a]=t}),n):void t(43,s.t,String(a),i);var l}function w(e,t,n,r,i=N.safeDescriptors){var a,o,s;let{value:c}=r;return(a=t.i)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:he(t.i?.name??n.toString(),c,(o=t.i?.autoAction)!=null&&o,(s=t.i)!=null&&s.bound?e.v??e.h:void 0),configurable:!i||e.p,enumerable:!1,writable:!i}}function T(e,t){return{t:e,i:t,o:E,u:ee}}function E(e,t,n,r){var i;return r===e.h?this.u(e,t,n,!1)===null?0:2:(i=this.i)!=null&&i.bound&&(!p(e.h,t)||!Ye(e.h[t]))&&this.u(e,t,n,!1)===null?0:Ye(n.value)?1:(It(r,t,te(e,0,0,n,!1,!1)),2)}function ee(e,t,n,r){let i=te(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function D(e,t,n){var r;let{name:i,addInitializer:a}=n;return Ye(t)||(t=Gn(t)),(r=e.i)!=null&&r.bound&&a(function(){let e=this,t=e[i].bind(e);t.isMobXFlow=!0,e[i]=t}),t}function te(e,t,n,r,i,a=N.safeDescriptors){let{value:o}=r;return Ye(o)||(o=Gn(o)),i&&(o=o.bind(e.v??e.h),o.isMobXFlow=!0),{value:o,configurable:!a||e.p,enumerable:!1,writable:!a}}function O(e,t){return{t:e,i:t,o:k,u:ne}}function k(e,t,n){return this.u(e,t,n,!1)===null?0:1}function ne(e,t,n,r){return e.m(t,Pt({},this.i,{get:n.get,set:n.set}),r)}function A(e,t,n){function r(e){let n=Pt({},i.i,{get:t,context:e});return n.name||=`ObservableObject.${a.toString()}`,new yn(n)}let i=e,{name:a,addInitializer:o}=n,s;return o(function(){let e=St(this)[j],n=this,i=e.j.get(a);i instanceof yn&&i.derivation!==t&&e.j.delete(a),(e.O??=new Map).set(a,()=>r(n))}),function(){let e=this[j],n=e.j.get(a);if(n instanceof yn&&n.derivation!==t){let e=s?.get(this);return e||(e=r(this),(s??=new WeakMap).set(this,e)),e.get()}return e._(a)}}function re(e,t){return{t:e,i:t,o:ie,u:ae}}function ie(e,t,n){return this.u(e,t,n,!1)===null?0:1}function ae(e,t,n,r){return e.S(t,n.value,this.i?.A??v,r)}function oe(e,t,n){function r(e,t){let n=St(e)[j];return(n.V??=new Map).set(o,()=>new _n(t,i.i?.A??v,`ObservableObject.${o.toString()}`,!1)),n}let i=e,{kind:a,name:o}=n;if(a===`accessor`)return{get(){return(this[j]??r(this,t.get.call(this)))._(o)},set(e){return(this[j]??r(this,e)).M(o,e)},init(e){return r(this,e),e}}}function se(e){return{t:Jt,i:e,o:ce,u:le}}function ce(e,t,n,r){var i,a,o;if(n.get)return dn.o(e,t,n,r);if(n.set){let i=Ve(n.set)?n.set:he(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!N.safeDescriptors||e.p,set:i})===null?0:2:(It(r,t,{configurable:!0,set:i}),2)}if(r!==e.h&&typeof n.value==`function`)return s(n.value)?((o=this.i)!=null&&o.autoBind?Kn:Gn).o(e,t,n,r):((a=this.i)!=null&&a.autoBind?zn:Ln).o(e,t,n,r);let c=!1===this.i?.deep?nn:sn;return typeof n.value==`function`&&(i=this.i)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),c.o(e,t,n,r)}function le(e,t,n,r){var i;return n.get?dn.u(e,t,n,r):n.set?e.l(t,{configurable:!N.safeDescriptors||e.p,set:he(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.i)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),(!1===this.i?.deep?nn:sn).u(e,t,n,r))}function ue(e,t){return Pt(function(n,r){if(r&&typeof r.kind==`string`)return t(e,n,r)},e)}function de(e){return e||Xt}function fe(e){return ue(e,oe)}function pe(e){return!0===e.deep?v:!1===e.deep?y:(t=e.defaultDecorator)&&(n=(r=t.i)?.A)!=null?n:v;var t,n,r}function me(e){return ue(e,A)}function he(e,t,n=!1,r){function i(){return ge(0,n,t,r||this,arguments)}return i.isMobxAction=!0,i.toString=()=>t.toString(),hn&&(gn.value=e,It(i,`name`,gn)),i}function ge(e,t,n,r,i){let a=_e(0,t);try{return n.apply(r,i)}catch(e){throw a.N=e,e}finally{ve(a)}}function _e(e,t){let n=N.trackingDerivation,r=!t||!n;je();let i=N.allowStateChanges;r&&Te();let a={R:r,k:n,C:i,I:N.allowStateReads,P:!1,T:0,B:mn++,D:pn};return pn=a.B,a}function ve(e){pn!==e.B&&t(30),pn=e.D,e.N!==void 0&&(N.suppressReactionErrors=!0),Me(),e.R&&Ee(e.k),N.suppressReactionErrors=!1}function ye(e,t){let n=function(e){let t=N.allowStateChanges;return N.allowStateChanges=e,t}(e);try{return t()}finally{(function(e){N.allowStateChanges=e})(n)}}function be(e){return e instanceof xn}function xe(e){switch(e.K){case 0:return!1;case-1:case 2:return!0;case 1:{let t=Te(),n=e.L,r=n.length;for(let i=0;i<r;i++){let r=n[i];if(bn(r)){if(N.disableErrorBoundaries)r.get();else try{r.get()}catch{return Ee(t),!0}if(e.K===2)return Ee(t),!0}}return De(e),Ee(t),!1}}}function Se(e,t,n){De(e),e.$=Array(e.U===0?100:e.L.length),e.W=0,e.U=++N.runId;let r=N.trackingDerivation,i;if(N.trackingDerivation=e,N.inBatch++,!0===N.disableErrorBoundaries)i=t.call(n);else try{i=t.call(n)}catch(e){i=new xn(e)}return N.inBatch--,N.trackingDerivation=r,function(e){let t=e.L,n=e.L=e.$,r=0,i=0,a=e.W;for(let e=0;e<a;e++){let t=n[e];t.diffValue===0&&(t.diffValue=1,i!==e&&(n[i]=t),i++),t.K>r&&(r=t.K)}for(n.length=i,e.$=null,a=t.length;a--;){let n=t[a];n.diffValue===0&&ke(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,Oe(t,e))}r!==0&&(e.K=r,e.q())}(e),i}function Ce(e){let t=e.L;e.L=[];let n=t.length;for(;n--;)ke(t[n],e);e.K=-1}function we(e){let t=Te();try{return e()}finally{Ee(t)}}function Te(){let e=N.trackingDerivation;return N.trackingDerivation=null,e}function Ee(e){N.trackingDerivation=e}function De(e){if(e.K===0)return;e.K=0;let t=e.L,n=t.length;for(;n--;)t[n].F=0}function Oe(e,t){(e.H??=new Set).add(t),e.F>t.K&&(e.F=t.K)}function ke(e,t){let n=e.H;n&&(n.delete(t),n.size===0&&Ae(e))}function Ae(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,N.pendingUnobservations.push(e))}function je(){N.inBatch++}function Me(){--N.inBatch===0&&(Ie(),!N.isRunningUnobservations&&N.pendingUnobservations.length>0&&function(){N.isRunningUnobservations=!0;try{let e=N.pendingUnobservations;for(let t=0;t<e.length;t++){let n=e[t];n.isPendingUnobservation=!1,n.H&&n.H.size!==0||(n.H=null,n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof yn&&n.G())}N.pendingUnobservations=[]}finally{N.isRunningUnobservations=!1}}())}function Ne(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.L)==null||t.forEach(Ne))}function Pe(e){let t=N.trackingDerivation;return t===null?((!e.H||e.H.size===0)&&N.inBatch>0&&Ae(e),!1):(t.U!==e.J&&(e.J=t.U,t.$[t.W++]=e,!e.isBeingObserved&&N.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function Fe(e){var t;e.F!==2&&(e.F=2,(t=e.H)==null||t.forEach(e=>{e.K===0&&e.q(),e.K=2}))}function Ie(){N.inBatch>0||N.isRunningReactions||On(Le)}function Le(){N.isRunningReactions=!0;let e=N.pendingReactions,t=0;for(;e.length>0;){++t===Dn&&(console.error(`[mobx] cycle in reaction: ${e[0]}`),e.splice(0));let n=e.splice(0);for(let e=0,t=n.length;e<t;e++)n[e].X()}N.isRunningReactions=!1}function Re(e){return ue(e,C)}function ze(e){return function(t,n){return n&&typeof n.kind==`string`?C(e?Pn:Mn,t,n):r(t)?he(t.name||`<unnamed action>`,t,e):r(n)?he(t,n,e):i(t)?Re(b(e?jn:An,{name:t,autoAction:e})):void 0}}function Be(e){return ge(0,!1,e,this,void 0)}function Ve(e){return r(e)&&!0===e.isMobxAction}function He(e,t=zt){function n(){e(a)}var r;let i=t?.name??`Autorun`,a;if(t.scheduler||t.delay){let e=Ue(t),r=!1;a=new En(i,()=>{r||(r=!0,e(()=>{r=!1,a.isDisposed||a.track(n)}))},t.onError,t.requiresObservable)}else a=new En(i,function(){this.track(n)},t.onError,t.requiresObservable);return t!=null&&(r=t.signal)!=null&&r.aborted||a.Y(),a.Z(t?.signal)}function Ue(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Bn}function We(e,t,n,i){let a=typeof i==`function`?Tt(t,n):Tt(t),o=r(i)?i:n,s=`${e}L`;return a[s]?a[s].add(o):a[s]=new Set([o]),function(){let e=a[s];e&&(e.delete(o),e.size===0&&delete a[s])}}function Ge(e,t,n,r){let i=Ut(t);return Ot(()=>{let t=St(e,r)[j];Ht(i).forEach(e=>{t.u(e,i[e],!n||!(e in n)||n[e])})}),e}function Ke(e){let t={name:e.tt};var n;return e.L&&e.L.length>0&&(t.dependencies=(n=e.L,Array.from(new Set(n))).map(Ke)),t}function qe(e){let t={name:e.tt};return function(e){return!!e.H&&e.H.size>0}(e)&&(t.observers=Array.from(function(e){return e.H??new Set}(e),qe)),t}function Je(e){r(e.cancel)&&e.cancel()}function Ye(e){return!0===e?.isMobXFlow}function Xe(e,t){var n;if(t===void 0)return bn(e);if(!1===wt(e))return!1;let r=e[j];return(n=r.O)!=null&&n.has(t)?!0:r.j.has(t)?bn(Tt(e,t)):!1}function Ze(e,t){if(!e)return!1;if(t!==void 0){if(wt(e)){var n,r;let i=e[j];return i.j.has(t)||!((n=i.O)==null||!n.has(t))||!((r=i.V)==null||!r.has(t))}return!1}return wt(e)||!!e[j]||Gt(e)||kn(e)||bn(e)}function Qe(e){return Ze(e)}function $e(e){return wt(e)?e[j].nt():ir(e)||sr(e)?Array.from(e.keys()):yt(e)?e.map((e,t)=>t):void t(5)}function et(e,n){return wt(e)?e[j].et(n):ir(e)||sr(e)?e.has(n):yt(e)?n>=0&&n<e.length:void t(10)}function tt(e){if(wt(e))return e[j].it();t(38)}function nt(e,t,n){if(bn(e)){let r,i=!0;return He(()=>{let a=e.get();if(!i||n){let n=Te();t({observableKind:`computed`,debugObjectName:e.tt,type:Xn,object:e,newValue:a,oldValue:r}),Ee(n)}i=!1,r=a})}return n&&t({observableKind:`value`,debugObjectName:e.tt,object:e,type:Xn,newValue:e.rt,oldValue:void 0}),ft(e,t)}function rt(e,t,n){return e.set(t,n),n}function it(e,t){if(typeof e!=`object`||!e||e instanceof Date||!Qe(e))return e;if(vn(e)||bn(e))return it(e.get(),t);if(t.has(e))return t.get(e);if(yt(e)){let n=rt(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=it(e,t)}),n}if(sr(e)){let n=rt(t,e,new Set);return e.forEach(e=>{n.add(it(e,t))}),n}if(ir(e)){let n=rt(t,e,new Map);return e.forEach((e,r)=>{n.set(r,it(e,t))}),n}{let n=rt(t,e,{});return tt(e).forEach(r=>{Lt.propertyIsEnumerable.call(e,r)&&(n[r]=it(e[r],t))}),n}}function at(e,t){je();try{return e.apply(t)}finally{Me()}}function ot(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[j].isDisposed){if(a(),!n.onError)throw e;n.onError(e)}},n.timeout)}n.name=`When`;let i=he(`When-effect`,t);var a=He(t=>{ye(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function st(e){return e[j]}function ct(e){return e.st!==void 0&&e.st.length>0}function lt(e,t){let r=e.st;return r?r.push(t):r=e.st=[t],n(()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)})}function ut(e,n){let r=Te();try{let r=[...e.st||[]];for(let e=0,i=r.length;e<i&&((n=r[e](n))&&!n.type&&t(14),n);e++);return n}finally{Ee(r)}}function dt(e){return e.ot!==void 0&&e.ot.length>0}function ft(e,t){let r=e.ot;return r?r.push(t):r=e.ot=[t],n(()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)})}function pt(e,t){let n=Te(),r=e.ot;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Ee(n)}}function mt(e,n,r){if(!0===r&&(r=e.ut),!1===r)return;n in e.h||t(1,r.t,`${e.tt}.${n.toString()}`);let i=e.h;for(;i&&i!==Lt;){let t=Ft(i,n);if(t){let a=r.o(e,n,t,i);if(a===0)return;if(a===1)break}i=Object.getPrototypeOf(i)}}function ht(e,t){typeof Array.prototype[e]==`function`&&($n[e]=t(e))}function gt(e){return function(){let t=this[j];t.ct.reportObserved();let n=t.ht(t.j);return n[e].apply(n,arguments)}}function _t(e){return function(t,n){let r=this[j];return r.ct.reportObserved(),r.ht(r.j)[e]((e,r)=>t.call(n,e,r,this))}}function vt(e){return function(){let t=this[j];t.ct.reportObserved();let n=t.ht(t.j),r=arguments[0];return arguments[0]=(e,t,n)=>r(e,t,n,this),n[e].apply(n,arguments)}}function yt(e){return a(e)&&er(e[j])}function bt(e){return e[Symbol.toStringTag]=`MapIterator`,Mt(e)}function xt(e){return e[Symbol.toStringTag]=`SetIterator`,Mt(e)}function St(e,t){if(p(e,j))return e;let n=t?.name??`ObservableObject`;return c(e,j,new ur(e,new Map,String(n),function(e){return e?e.defaultDecorator??function(e){let t=!1!==e.deep,n=!!e.autoBind,r=!t|(n?2:0);return M[r]??(M[r]=se({deep:t,autoBind:n}))}(e):void 0}(t))),e}function Ct(e){return cr[e]||(cr[e]={get(){return this[j]._(e)},set(t){return this[j].M(e,t)}})}function wt(e){return!!a(e)&&dr(e[j])}function Tt(e,n){if(typeof e==`object`&&e){if(yt(e))return n!==void 0&&t(23),e[j].ct;if(sr(e))return e.ct;if(ir(e)){if(n===void 0)return e.lt;let r=e.ft.get(n)||e.dt.get(n);return r||t(25,n,Dt(e)),r}if(wt(e)){if(!n)return t(26);let r=e[j],i=r.j.get(n)??r.vt(n)??r.bt(n);return i||t(27,n,Dt(e)),i}if(Gt(e)||bn(e)||kn(e))return e}else if(r(e)&&kn(e[j]))return e[j];t(28)}function Et(e,n){return e||t(29),n===void 0?Gt(e)||bn(e)||kn(e)||ir(e)||sr(e)?e:e[j]?e[j]:void t(24,e):Et(Tt(e,n))}function Dt(e,t){let n;if(t!==void 0)n=Tt(e,t);else{if(Ve(e))return e.name;n=wt(e)||ir(e)||sr(e)?Et(e):Tt(e)}return n.tt}function Ot(e){let t=Te();je();try{return e()}finally{Me(),Ee(t)}}function kt(e,t,n=-1){return At(e,t,n)}function At(e,t,n,i,a){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!=e)return t!=t;let o=typeof e;if(o!==`function`&&o!==`object`&&typeof t!=`object`)return!1;let s=fr.call(e);if(s!==fr.call(t))return!1;switch(s){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++}e=jt(e),t=jt(t);let c=s===`[object Array]`;if(!c){if(typeof e!=`object`||typeof t!=`object`)return!1;let n=e.constructor,i=t.constructor;if(n!==i&&!(r(n)&&n instanceof n&&r(i)&&i instanceof i)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),a||=[];let l=(i||=[]).length;for(;l--;)if(i[l]===e)return a[l]===t;if(i.push(e),a.push(t),c){if(l=e.length,l!==t.length)return!1;for(;l--;)if(!At(e[l],t[l],n-1,i,a))return!1}else{let r=Object.keys(e),o=r.length;if(Object.keys(t).length!==o)return!1;for(let s=0;s<o;s++){let o=r[s];if(!p(t,o)||!At(e[o],t[o],n-1,i,a))return!1}}return i.pop(),a.pop(),!0}function jt(e){return yt(e)?e.slice():u(e)||ir(e)||d(e)||sr(e)?Array.from(e.entries()):e}function Mt(e){return e[Symbol.iterator]=Nt,Pt(Object.create(pr),e)}function Nt(){return this}Object.defineProperty(e,`__esModule`,{value:!0});let Pt=Object.assign,Ft=Object.getOwnPropertyDescriptor,It=Object.defineProperty,Lt=Object.prototype,Rt=[];Object.freeze(Rt);let zt={};Object.freeze(zt);let Bt=Object.toString(),Vt=()=>{},Ht=Reflect.ownKeys,Ut=Object.getOwnPropertyDescriptors,j=Symbol(`mobx administration`);var Wt=class{constructor(e=`Atom`){this.tt=void 0,this.yt=0,this.H=null,this.J=0,this.F=-1,this.onBOL=void 0,this.onBUOL=void 0,this.tt=e}get isBeingObserved(){return m(this.yt,1)}set isBeingObserved(e){this.yt=h(this.yt,1,e)}get isPendingUnobservation(){return m(this.yt,2)}set isPendingUnobservation(e){this.yt=h(this.yt,2,e)}get diffValue(){return+!!m(this.yt,4)}set diffValue(e){this.yt=h(this.yt,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return Pe(this)}reportChanged(){je(),Fe(this),Me()}toString(){return this.tt}};let Gt=l(`Atom`,Wt),Kt=Object.is,qt={t:`override`,o:function(){return 0},u:function(){t(44,this.t)}},Jt=`true`,Yt=se(),M=[Yt],Xt={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Xt);let Zt=re(`observable`),Qt=re(`observable.ref`,{A:y}),$t=re(`observable.shallow`,{A:function(e,t,n){return e==null||wt(e)||yt(e)||ir(e)||sr(e)?e:Array.isArray(e)?sn.array(e,{name:n,deep:!1}):o(e)?sn.object(e,void 0,{name:n,deep:!1}):u(e)?sn.map(e,{name:n,deep:!1}):d(e)?sn.set(e,{name:n,deep:!1}):void 0}}),en=re(`observable.struct`,{A:function(e,t){return kt(e,t)?t:e}}),tn={box(e,t){let n=de(t);return new _n(e,pe(n),n.name,!0,n.equals)},array(e,t){let n=de(t);return function(e,t,n=`ObservableArray`,r=!1){return Ot(()=>{let i=new Qn(n,t,r);It(i.j,j,{enumerable:!1,writable:!1,configurable:!0,value:i});let a=new Proxy(i.j,Zn);return i.v=a,e&&e.length&&i.wt(0,0,e),a})}(e,pe(n),n.name)},map(e,t){let n=de(t);return new rr(e,pe(n),n.name)},set(e,t){let n=de(t);return new or(e,pe(n),n.name)},object:(e,t,n)=>Ot(()=>Ge(function(e,t){var n;return(n=(e=St(e,t))[j]).v??(n.v=new Proxy(e,qn))}({},n),e,t))},nn=fe(Qt),rn=fe($t),an=fe(Zt),on=fe(en);var sn=Pt(function(e,t,n){return t&&typeof t.kind==`string`?oe(Zt,e,t):Qe(e)?e:o(e)?sn.object(e,t,n):Array.isArray(e)?sn.array(e,t):u(e)?sn.map(e,t):d(e)?sn.set(e,t):typeof e==`object`&&e?e:sn.box(e,t)},Zt,tn);let cn=`computed`,ln=O(cn),un=me(O(`computed.struct`,{equals:_})),dn=function(e,t){if(t&&typeof t.kind==`string`)return A(ln,e,t);if(o(e))return me(O(cn,e));let n=o(t)?t:{};return n.get=e,n.name||=e.name||``,new yn(n)};var fn;Pt(dn,ln);let pn=0,mn=1,hn=(fn=Ft(()=>{},`name`)?.configurable)!=null&&fn,gn={value:`action`,configurable:!0,writable:!1,enumerable:!1};var _n=class extends Wt{constructor(e,t,n=`ObservableValue`,r=!0,i=Kt){super(n),this.A=void 0,this.tt=void 0,this.xt=void 0,this.gt=!1,this.st=void 0,this.ot=void 0,this.rt=void 0,this.dehancer=void 0,this.A=t,this.tt=n,this.xt=i,this.rt=t(e,void 0,n)}dehanceValue(e){return this.dehancer===void 0?e:this.dehancer(e)}set(e){(e=this.jt(e))!==N.UNCHANGED&&this.Ot(e)}jt(e){if(ct(this)){let t=ut(this,{object:this,type:Xn,newValue:e});if(!t)return N.UNCHANGED;e=t.newValue}return e=this.A(e,this.rt,this.tt),this.xt(this.rt,e)?N.UNCHANGED:e}Ot(e){let t=this.rt;this.rt=e,this.reportChanged(),dt(this)&&pt(this,{type:Xn,object:this,newValue:e,oldValue:t})}get(){return this.reportObserved(),this.dehanceValue(this.rt)}raw(){return this.rt}toJSON(){return this.get()}toString(){return`${this.tt}[${this.rt}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let vn=l(`ObservableValue`,_n);var yn=class{constructor(e){this.K=-1,this.L=[],this.$=null,this.H=null,this.U=0,this.J=0,this.F=0,this.W=0,this.rt=new xn(null),this.tt=void 0,this._t=void 0,this.yt=0,this.derivation=void 0,this.St=void 0,this.At=void 0,this.xt=void 0,this.Vt=void 0,this.Mt=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||t(31),this.derivation=e.get,this.tt=e.name||`ComputedValue`,e.set&&(this.St=he(`ComputedValue-setter`,e.set)),this.xt=e.equals||Kt,this.At=e.context,this.Vt=e.requiresReaction,this.Mt=!!e.keepAlive}q(){(function(e){var t;e.F===0&&(e.F=1,(t=e.H)==null||t.forEach(e=>{e.K===0&&(e.K=1,e.q())}))})(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return m(this.yt,1)}set isComputing(e){this.yt=h(this.yt,1,e)}get isRunningSetter(){return m(this.yt,2)}set isRunningSetter(e){this.yt=h(this.yt,2,e)}get isBeingObserved(){return m(this.yt,4)}set isBeingObserved(e){this.yt=h(this.yt,4,e)}get isPendingUnobservation(){return m(this.yt,8)}set isPendingUnobservation(e){this.yt=h(this.yt,8,e)}get diffValue(){return+!!m(this.yt,16)}set diffValue(e){this.yt=h(this.yt,16,e===1)}get(){if(this.isComputing&&t(32,this.tt,this.derivation),N.inBatch!==0||this.H&&this.H.size!==0||this.Mt){let e=this.isBeingObserved;if(Pe(this),xe(this)){let e=N.trackingContext;e||!this.Mt&&!this.isBeingObserved||(N.trackingContext=this),this.trackAndCompute()&&function(e){var t;e.F!==2&&(e.F=2,(t=e.H)==null||t.forEach(t=>{t.K===1?t.K=2:t.K===0&&(e.F=0)}))}(this),N.trackingContext=e}else !e&&this.isBeingObserved&&this.L.forEach(Ne)}else xe(this)&&(this.Nt(),je(),this.rt=this.Rt(!1),Me());let e=this.rt;if(be(e))throw e.cause;return e}set(e){if(this.St){this.isRunningSetter&&t(33,this.tt),this.isRunningSetter=!0;try{this.St.call(this.At,e)}finally{this.isRunningSetter=!1}}else t(34,this.tt)}trackAndCompute(){let e=this.rt,t=this.K===-1,n=this.Rt(!0),r=t||be(e)||be(n)||!this.xt(e,n);return r&&(this.rt=n),r}Rt(e){let t;if(this.isComputing=!0,e)t=Se(this,this.derivation,this.At);else if(!0===N.disableErrorBoundaries)t=this.derivation.call(this.At);else try{t=this.derivation.call(this.At)}catch(e){t=new xn(e)}return this.isComputing=!1,t}G(){this.Mt||(Ce(this),this.rt=void 0)}Nt(){}toString(){return`${this.tt}[${this.derivation.toString()}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let bn=l(`ComputedValue`,yn);var xn=class{constructor(e){this.cause=void 0,this.cause=e}};let Sn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Cn=class{constructor(){this.version=7,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.isRunningUnobservations=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.safeDescriptors=!0}};let wn=!0,Tn=!1,N=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(wn=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(wn=!1),wn?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Cn):(setTimeout(()=>{Tn||t(35)},1),new Cn)}();var En=class{constructor(e=`Reaction`,t,n,r){this.tt=void 0,this.Et=void 0,this.kt=void 0,this.Ct=void 0,this.L=[],this.$=[],this.K=-1,this.U=0,this.W=0,this.yt=0,this.It=void 0,this.tt=e,this.Et=t,this.kt=n,this.Ct=r}get isDisposed(){return m(this.yt,1)}set isDisposed(e){this.yt=h(this.yt,1,e)}get isScheduled(){return m(this.yt,2)}set isScheduled(e){this.yt=h(this.yt,2,e)}get isTrackPending(){return m(this.yt,4)}set isTrackPending(e){this.yt=h(this.yt,4,e)}get isRunning(){return m(this.yt,8)}set isRunning(e){this.yt=h(this.yt,8,e)}get diffValue(){return+!!m(this.yt,16)}set diffValue(e){this.yt=h(this.yt,16,e===1)}q(){this.Y()}Y(){this.isScheduled||(this.isScheduled=!0,N.pendingReactions.push(this),Ie())}X(){if(!this.isDisposed){je(),this.isScheduled=!1;let e=N.trackingContext;if(N.trackingContext=this,xe(this)){this.isTrackPending=!0;try{this.Et()}catch(e){this.Pt(e)}}N.trackingContext=e,Me()}}track(e){if(this.isDisposed)return;je(),this.isRunning=!0;let t=N.trackingContext;N.trackingContext=this;let n=Se(this,e,void 0);N.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Ce(this),be(n)&&this.Pt(n.cause),Me()}Pt(e){if(this.kt)this.kt(e,this);else{if(N.disableErrorBoundaries)throw e;N.suppressReactionErrors||console.error(`[mobx] uncaught error in '${this}'`,e),N.globalReactionErrorHandlers.forEach(t=>t(e,this))}}dispose(){var e;this.isDisposed||(this.isDisposed=!0,(e=this.It)==null||e.call(this),this.isRunning||(je(),Ce(this),Me()))}Z(e){let t=()=>this.dispose();return e!=null&&e.addEventListener&&!this.isDisposed&&(e.addEventListener(`abort`,t),this.It=()=>e.removeEventListener==null?void 0:e.removeEventListener(`abort`,t)),t[j]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.tt}]`}};let Dn=100,On=e=>e(),kn=l(`Reaction`,En),An=`action`,jn=`autoAction`,Mn=b(An),Nn=b(`action.bound`,{bound:!0}),Pn=b(jn,{autoAction:!0}),Fn=b(`autoAction.bound`,{autoAction:!0,bound:!0}),In=ze(!1);Pt(In,Mn);let Ln=ze(!0);Pt(Ln,Pn);let Rn=Re(Nn),zn=Re(Fn),Bn=e=>e(),Vn=`always`;var Hn=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};let Un=T(`flow`),Wn=T(`flow.bound`,{bound:!0}),Gn=Pt(function(e,t){if(t&&typeof t.kind==`string`)return D(Un,e,t);let n=e,i=n.name||`flow`,a=function(){let e=arguments,t=In(i,n).apply(this,e),a,o,s=new Promise(function(e,n){function s(e){let r;o=void 0;try{r=In(i,t.next).call(t,e)}catch(e){return n(e)}l(r)}function c(e){let r;o=void 0;try{r=In(i,t.throw).call(t,e)}catch(e){return n(e)}l(r)}function l(t){if(!r(t?.then))return t.done?e(t.value):(o=Promise.resolve(t.value),o.then(s,c));t.then(l,n)}a=n,s(void 0)});return s.cancel=In(i,function(){try{o&&Je(o);let e=t.return(void 0),n=Promise.resolve(e.value);n.then(Vt,Vt),Je(n),a(new Hn)}catch(e){a(e)}}),s};return a.isMobXFlow=!0,a},Un),Kn=ue(Wn,D),qn={has:(e,t)=>st(e).et(t),get:(e,t)=>st(e).Tt(t),set(e,t,n){var r;return!!i(t)&&((r=st(e).Bt(t,n,!0))==null||r)},deleteProperty(e,t){var n;return!!i(t)&&((n=st(e).Dt(t,!0))==null||n)},defineProperty(e,t,n){var r;return(r=st(e).l(t,n))==null||r},ownKeys:e=>st(e).it(),preventExtensions(e){t(13)}},Jn=Symbol(`mobx-keys`),Yn=`splice`,Xn=`update`,Zn={get(e,t){let n=e[j];return t===j?n:t===`length`?n.Kt():typeof t!=`string`||isNaN(t)?p($n,t)?$n[t]:e[t]:n.Tt(parseInt(t))},set(e,t,n){let r=e[j];return t===`length`?r.Lt(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.Bt(parseInt(t),n),!0},preventExtensions(){t(15)}};var Qn=class{constructor(e=`ObservableArray`,t,n){this.$t=void 0,this.ct=void 0,this.j=[],this.st=void 0,this.ot=void 0,this.A=void 0,this.dehancer=void 0,this.v=void 0,this.Ut=0,this.$t=n,this.ct=new Wt(e),this.A=(e,n)=>t(e,n,`ObservableArray[..]`)}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}ht(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e}Kt(){return this.ct.reportObserved(),this.j.length}Lt(e){(!Number.isInteger(e)||e<0)&&t(40,e);let n=this.j.length;if(e!==n)if(e>n){let t=Array.from({length:e-n});this.wt(n,0,t)}else this.wt(e,n-e)}zt(e,n){e!==this.Ut&&t(16),this.Ut+=n}wt(e,t,n){let r=this.j.length;if(e===void 0?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=arguments.length===1?r-e:t==null?0:Math.max(0,Math.min(t,r-e)),n===void 0&&(n=Rt),ct(this)){let r=ut(this,{object:this.v,type:Yn,index:e,removedCount:t,added:n});if(!r)return Rt;t=r.removedCount,n=r.added}n=n.length===0?n:n.map(e=>this.A(e,void 0));let i=this.qt(e,t,n);return t===0&&n.length===0||this.Ft(e,n,i),this.ht(i)}qt(e,t,n){if(n.length<1e4)return this.j.splice(e,t,...n);{let r=this.j.slice(e,e+t),i=this.j.slice(e+t);this.j.length+=n.length-t;for(let t=0;t<n.length;t++)this.j[e+t]=n[t];for(let t=0;t<i.length;t++)this.j[e+n.length+t]=i[t];return r}}Ht(e,t,n){let r=dt(this),i=r?{observableKind:`array`,object:this.v,type:Xn,debugObjectName:this.ct.tt,index:e,newValue:t,oldValue:n}:null;this.ct.reportChanged(),r&&pt(this,i)}Ft(e,t,n){let r=dt(this),i=r?{observableKind:`array`,object:this.v,debugObjectName:this.ct.tt,type:Yn,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;this.ct.reportChanged(),r&&pt(this,i)}Tt(e){return this.ct.reportObserved(),this.Wt(this.j[e])}Bt(e,t){let n=this.j;if(e<n.length){let r=n[e];if(ct(this)){let n=ut(this,{type:Xn,object:this.v,index:e,newValue:t});if(!n)return;t=n.newValue}(t=this.A(t,r))!==r&&(n[e]=t,this.Ht(e,t,r))}else{let r=Array.from({length:e+1-n.length});r[r.length-1]=t,this.wt(n.length,0,r)}}},$n={clear(){return this.splice(0)},replace(e){let t=this[j];return t.wt(0,t.j.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[j];switch(arguments.length){case 0:return[];case 1:return r.wt(e);case 2:return r.wt(e,t)}return r.wt(e,t,n)},spliceWithArray(e,t,n){return this[j].wt(e,t,n)},push(...e){let t=this[j];return t.wt(t.j.length,0,e),t.j.length},pop(){return this.splice(Math.max(this[j].j.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[j];return t.wt(0,0,e),t.j.length},reverse(){return N.trackingDerivation&&t(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){N.trackingDerivation&&t(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[j],n=t.ht(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};ht(`at`,gt),ht(`concat`,gt),ht(`flat`,gt),ht(`includes`,gt),ht(`indexOf`,gt),ht(`join`,gt),ht(`lastIndexOf`,gt),ht(`slice`,gt),ht(`toString`,gt),ht(`toLocaleString`,gt),ht(`toSorted`,gt),ht(`toSpliced`,gt),ht(`with`,gt),ht(`every`,_t),ht(`filter`,_t),ht(`find`,_t),ht(`findIndex`,_t),ht(`findLast`,_t),ht(`findLastIndex`,_t),ht(`flatMap`,_t),ht(`forEach`,_t),ht(`map`,_t),ht(`some`,_t),ht(`toReversed`,_t),ht(`reduce`,vt),ht(`reduceRight`,vt);let er=l(`ObservableArrayAdministration`,Qn),tr={},nr=`delete`;var rr=class{constructor(e,t=v,n=`ObservableMap`){this.A=void 0,this.tt=void 0,this[j]=tr,this.ft=void 0,this.dt=void 0,this.lt=void 0,this.st=void 0,this.ot=void 0,this.dehancer=void 0,this.A=t,this.tt=n,Ot(()=>{this.lt=g(`ObservableMap.keys()`),this.ft=new Map,this.dt=new Map,e&&this.merge(e)})}et(e){return this.ft.has(e)}has(e){if(!N.trackingDerivation)return this.et(e);let t=this.dt.get(e);if(!t){let n=t=new _n(this.et(e),y,`ObservableMap.key?`,!1);this.dt.set(e,n),n.onBUOL=new Set([()=>this.dt.delete(e)])}return t.get()}set(e,t){let n=this.et(e);if(ct(this)){let r=ut(this,{type:n?Xn:`add`,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.Gt(e,t):this.Jt(e,t),this}delete(e){if(ct(this)&&!ut(this,{type:nr,object:this,name:e}))return!1;if(this.et(e)){let t=dt(this),n=t?{observableKind:`map`,debugObjectName:this.tt,type:nr,object:this,oldValue:this.ft.get(e).rt,name:e}:null;return at(()=>{var t;this.lt.reportChanged(),(t=this.dt.get(e))==null||t.Ot(!1),this.ft.get(e).Ot(void 0),this.ft.delete(e)}),t&&pt(this,n),!0}return!1}Gt(e,t){let n=this.ft.get(e);if((t=n.jt(t))!==N.UNCHANGED){let r=dt(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:Xn,object:this,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&pt(this,i)}}Jt(e,t){at(()=>{var n;let r=new _n(t,this.A,`ObservableMap.key`,!1);this.ft.set(e,r),t=r.rt,(n=this.dt.get(e))==null||n.Ot(!0),this.lt.reportChanged()});let n=dt(this);n&&pt(this,n?{observableKind:`map`,debugObjectName:this.tt,type:`add`,object:this,name:e,newValue:t}:null)}get(e){return this.has(e)?this.Wt(this.ft.get(e).get()):this.Wt(void 0)}getOrInsert(e,t){return this.has(e)||this.set(e,t),this.get(e)}getOrInsertComputed(e,t){return this.has(e)||this.set(e,t(e)),this.get(e)}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}keys(){return this.lt.reportObserved(),this.ft.keys()}values(){let e=this,t=this.keys();return bt({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:e.get(r)}}})}entries(){let e=this,t=this.keys();return bt({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:[r,e.get(r)]}}})}[Symbol.iterator](){return this.entries()}forEach(e,t){for(let[n,r]of this)e.call(t,r,n,this)}merge(e){return ir(e)&&(e=new Map(e)),at(()=>{o(e)?function(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>Lt.propertyIsEnumerable.call(e,t))]:t}(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):u(e)?(function(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}(e)||t(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&t(20,e)}),this}clear(){at(()=>{we(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return at(()=>{let n=function(e){if(u(e)||ir(e))return e;if(Array.isArray(e))return new Map(e);if(o(e)){let t=new Map;for(let n in e)t.set(n,e[n]);return t}return t(21,e)}(e),r=new Map,i=!1;for(let e of this.ft.keys())if(!n.has(e))if(this.delete(e))i=!0;else{let t=this.ft.get(e);r.set(e,t)}for(let[e,t]of n.entries()){let n=this.ft.has(e);if(this.set(e,t),this.ft.has(e)){let t=this.ft.get(e);r.set(e,t),n||(i=!0)}}if(!i)if(this.ft.size!==r.size)this.lt.reportChanged();else{let e=this.ft.keys(),t=r.keys(),n=e.next(),i=t.next();for(;!n.done;){if(n.value!==i.value){this.lt.reportChanged();break}n=e.next(),i=t.next()}}this.ft=r}),this}get size(){return this.lt.reportObserved(),this.ft.size}toString(){return`[object ObservableMap]`}toJSON(){return Array.from(this)}get[Symbol.toStringTag](){return`Map`}},ir=l(`ObservableMap`,rr);let ar={};var or=class{constructor(e,t=v,n=`ObservableSet`){this.tt=void 0,this[j]=ar,this.ft=new Set,this.ct=void 0,this.ot=void 0,this.st=void 0,this.dehancer=void 0,this.A=void 0,this.tt=n,this.A=(e,r)=>t(e,r,n),Ot(()=>{this.ct=g(this.tt),e&&this.replace(e)})}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){at(()=>{we(()=>{for(let e of this.ft.values())this.delete(e)})})}forEach(e,t){for(let n of this)e.call(t,n,n,this)}get size(){return this.ct.reportObserved(),this.ft.size}add(e){if(ct(this)){let t=ut(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){at(()=>{e=this.A(e,void 0),this.ft.add(e),this.ct.reportChanged()});let t=dt(this);t&&pt(this,t?{observableKind:`set`,debugObjectName:this.tt,type:`add`,object:this,newValue:e}:null)}return this}delete(e){if(ct(this)&&!ut(this,{type:nr,object:this,oldValue:e}))return!1;if(this.has(e)){let t=dt(this),n=t?{observableKind:`set`,debugObjectName:this.tt,type:nr,object:this,oldValue:e}:null;return at(()=>{this.ct.reportChanged(),this.ft.delete(e)}),t&&pt(this,n),!0}return!1}has(e){return this.ct.reportObserved(),this.ft.has(this.Wt(e))}entries(){let e=this.values();return xt({next(){let{value:t,done:n}=e.next();return n?{value:void 0,done:n}:{value:[t,t],done:n}}})}keys(){return this.values()}values(){this.ct.reportObserved();let e=this,t=this.ft.values();return xt({next(){let{value:n,done:r}=t.next();return r?{value:void 0,done:r}:{value:e.Wt(n),done:r}}})}intersection(e){return new Set(this).intersection(e)}union(e){return new Set(this).union(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}replace(e){return sr(e)&&(e=new Set(e)),Array.isArray(e)||d(e)?at(()=>{let t=d(e)?e:new Set(e);if(t.size!==0)if(this.ft.size!==0){for(let e of this.ft.values())t.has(this.Wt(e))||this.delete(e);t.forEach(e=>this.add(e))}else t.forEach(e=>this.add(e));else this.clear()}):e!=null&&t(41,e),this}toJSON(){return Array.from(this)}toString(){return`[object ObservableSet]`}[Symbol.iterator](){return this.values()}get[Symbol.toStringTag](){return`Set`}},sr=l(`ObservableSet`,or);let cr=Object.create(null),lr=`remove`;var ur=class{constructor(e,t=new Map,n,r=Yt){this.h=void 0,this.j=void 0,this.tt=void 0,this.ut=void 0,this.lt=void 0,this.ot=void 0,this.st=void 0,this.v=void 0,this.p=void 0,this.Xt=void 0,this.Qt=void 0,this.O=void 0,this.V=void 0,this.h=e,this.j=t,this.tt=n,this.ut=r,this.lt=new Wt(`ObservableObject.keys`),this.p=o(this.h)}_(e){return(this.j.get(e)??this.vt(e)??this.bt(e)).get()}vt(e){let t=this.O?.get(e);if(!t)return;this.O.delete(e),this.O.size===0&&(this.O=void 0);let n=t();return this.j.set(e,n),n}bt(e){let t=this.V?.get(e);if(!t)return;this.V.delete(e),this.V.size===0&&(this.V=void 0);let n=t();return this.j.set(e,n),n}M(e,t){let n=this.j.get(e)??this.vt(e)??this.bt(e);if(n instanceof yn)return n.set(t),!0;if(ct(this)){let n=ut(this,{type:Xn,object:this.v||this.h,name:e,newValue:t});if(!n)return null;t=n.newValue}if((t=n.jt(t))!==N.UNCHANGED){let r=dt(this),i=r?{type:Xn,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&pt(this,i)}return!0}Tt(e){return N.trackingDerivation&&!p(this.h,e)&&this.et(e),this.h[e]}Bt(e,t,n=!1){return p(this.h,e)?this.j.has(e)?this.M(e,t):n?Reflect.set(this.h,e,t):(this.h[e]=t,!0):this.u(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.ut,n)}et(e){if(!N.trackingDerivation)return e in this.h;this.Qt||=new Map;let t=this.Qt.get(e);return t||(t=new _n(e in this.h,y,`ObservableObject.key?`,!1),this.Qt.set(e,t)),t.get()}u(e,t,n,r=!1){return!0===n&&(n=this.ut),!1===n?this.l(e,t,r):n.u(this,e,t,r)}l(e,t,n=!1){try{je();let r=this.Dt(e);if(!r)return r;if(ct(this)){let n=ut(this,{object:this.v||this.h,name:e,type:`add`,newValue:t.value});if(!n)return null;let{newValue:r}=n;t.value!==r&&(t=Pt({},t,{value:r}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else It(this.h,e,t);this.Yt(e,t.value)}finally{Me()}return!0}S(e,t,n,r=!1){try{je();let i=this.Dt(e);if(!i)return i;if(ct(this)){let n=ut(this,{object:this.v||this.h,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let a=Ct(e),o={configurable:!N.safeDescriptors||this.p,enumerable:!0,get:a.get,set:a.set};if(r){if(!Reflect.defineProperty(this.h,e,o))return!1}else It(this.h,e,o);let s=new _n(t,n,`ObservableObject.key`,!1);this.j.set(e,s),this.Yt(e,s.rt)}finally{Me()}return!0}m(e,t,n=!1){try{je();let r=this.Dt(e);if(!r)return r;if(ct(this)&&!ut(this,{object:this.v||this.h,name:e,type:`add`,newValue:void 0}))return null;t.name||=`ObservableObject.key`,t.context=this.v||this.h;let i=Ct(e),a={configurable:!N.safeDescriptors||this.p,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.h,e,a))return!1}else It(this.h,e,a);this.j.set(e,new yn(t)),this.Yt(e,void 0)}finally{Me()}return!0}Dt(e,t=!1){if(!p(this.h,e))return!0;if(ct(this)&&!ut(this,{object:this.v||this.h,name:e,type:lr}))return null;try{var n;je();let r=dt(this),i=this.j.get(e),a;if(i||!r||(a=Ft(this.h,e)?.value),t){if(!Reflect.deleteProperty(this.h,e))return!1}else delete this.h[e];i&&(this.j.delete(e),i instanceof _n&&(a=i.rt),Fe(i)),this.lt.reportChanged(),(n=this.Qt)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&pt(this,{type:lr,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{Me()}return!0}Yt(e,t){var n;let r=dt(this);r&&r&&pt(this,r?{type:`add`,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,name:e,newValue:t}:null),(n=this.Qt)==null||(n=n.get(e))==null||n.set(!0),this.lt.reportChanged()}it(){return this.lt.reportObserved(),Ht(this.h)}nt(){return this.lt.reportObserved(),Object.keys(this.h)}};let dr=l(`ObservableObjectAdministration`,ur),fr=Lt.toString,pr=globalThis.Iterator?.prototype||{};e.$mobx=j,e.FlowCancellationError=Hn,e.ObservableMap=rr,e.ObservableSet=or,e.Reaction=En,e._allowStateChanges=ye,e._allowStateChangesInsideComputed=Be,e._allowStateReadsEnd=function(e){N.allowStateReads=e},e._allowStateReadsStart=function(e){let t=N.allowStateReads;return N.allowStateReads=e,t},e._autoAction=Ln,e._autoActionBound=zn,e._endAction=ve,e._getAdministration=Et,e._getGlobalState=function(){return N},e._interceptReads=function(e,t,n){let r;return ir(e)||yt(e)||vn(e)?r=Et(e):wt(e)&&(r=Et(e,t)),r.dehancer=typeof t==`function`?t:n,()=>{r.dehancer=void 0}},e._isComputingDerivation=function(){return N.trackingDerivation!==null},e._resetGlobalState=function(){let e=new Cn;for(let t in e)Sn.indexOf(t)===-1&&(N[t]=e[t]);N.allowStateChanges=!N.enforceActions},e._startAction=_e,e.action=In,e.actionBound=Rn,e.autorun=He,e.compareDefault=Kt,e.compareIdentity=function(e,t){return e===t},e.compareShallow=function(e,t){return kt(e,t,1)},e.compareStructural=_,e.computed=dn,e.computedStruct=un,e.configure=function(e){!0===e.isolateGlobalState&&function(){if((N.pendingReactions.length||N.inBatch||N.isRunningReactions)&&t(36),Tn=!0,wn){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),N=new Cn}}();let{enforceActions:n}=e;if(n!==void 0){let e=n===Vn?Vn:n===`observed`;N.enforceActions=e,N.allowStateChanges=!0!==e&&e!==Vn}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(N[t]=!!e[t])}),N.allowStateReads=!N.observableRequiresReaction,e.reactionScheduler&&function(e){let t=On;On=n=>e(()=>t(n))}(e.reactionScheduler)},e.createAtom=g,e.defineProperty=function(e,n,r){if(wt(e))return e[j].l(n,r);t(39)},e.entries=function(e){return wt(e)?$e(e).map(t=>[t,e[t]]):ir(e)?$e(e).map(t=>[t,e.get(t)]):sr(e)?Array.from(e.entries()):yt(e)?e.map((e,t)=>[t,e]):void t(7)},e.extendObservable=Ge,e.flow=Gn,e.flowBound=Kn,e.flowResult=function(e){return e},e.get=function(e,n){if(et(e,n))return wt(e)?e[j].Tt(n):ir(e)?e.get(n):yt(e)?e[n]:void t(11)},e.getAtom=Tt,e.getDebugName=Dt,e.getDependencyTree=function(e,t){return Ke(Tt(e,t))},e.getObserverTree=function(e,t){return qe(Tt(e,t))},e.has=et,e.intercept=function(e,t,n){return r(n)?function(e,t,n){return lt(Et(e,t),n)}(e,t,n):function(e,t){return lt(Et(e),t)}(e,t)},e.isAction=Ve,e.isBoxedObservable=vn,e.isComputed=function(e){return Xe(e)},e.isComputedProp=function(e,t){return Xe(e,t)},e.isFlow=Ye,e.isFlowCancellationError=function(e){return e instanceof Hn},e.isObservable=Qe,e.isObservableArray=yt,e.isObservableMap=ir,e.isObservableObject=wt,e.isObservableProp=function(e,t){return Ze(e,t)},e.isObservableSet=sr,e.keys=$e,e.makeAutoObservable=function(e,t,n){return o(e)?Ge(e,e,t,n):(Ot(()=>{let r=St(e,n)[j];if(!e[Jn]){let t=Object.getPrototypeOf(e),n=new Set([...Ht(e),...Ht(t)]);n.delete(`constructor`),n.delete(j),c(t,Jn,n)}e[Jn].forEach(e=>mt(r,e,!t||!(e in t)||t[e]))}),e)},e.makeObservable=function(e,t,n){return Ot(()=>{let r=St(e,n)[j];Ht(t).forEach(e=>mt(r,e,t[e]))}),e},e.observable=sn,e.observableDeep=an,e.observableRef=nn,e.observableShallow=rn,e.observableStruct=on,e.observe=function(e,t,n,i){return r(n)?function(e,t,n,r){return nt(Et(e,t),n,r)}(e,t,n,i):function(e,t,n){let r=Et(e);if(yt(e))n&&t({observableKind:`array`,object:r.v,debugObjectName:r.ct.tt,type:`splice`,index:0,added:r.j.slice(),addedCount:r.j.length,removed:[],removedCount:0});else if(!ir(e)&&!sr(e)&&!wt(e))return nt(r,t,n);return ft(r,t)}(e,t,n)},e.onBecomeObserved=function(e,t,n){return We(`onBO`,e,t,n)},e.onBecomeUnobserved=function(e,t,n){return We(`onBUO`,e,t,n)},e.onReactionError=function(e){return N.globalReactionErrorHandlers.push(e),()=>{let t=N.globalReactionErrorHandlers.indexOf(e);t>=0&&N.globalReactionErrorHandlers.splice(t,1)}},e.override=qt,e.ownKeys=tt,e.reaction=function(e,t,n=zt){function r(){if(p=!1,h.isDisposed)return;let t=!1,r=d;h.track(()=>{let n=ye(!1,()=>e(h));t=f||!m(d,n),d=n}),(f&&n.fireImmediately||!f&&t)&&o(d,r,h),f=!1}var i;let a=n.name??`Reaction`,o=In(a,n.onError?(s=n.onError,c=t,function(){try{return c.apply(this,arguments)}catch(e){s.call(this,e)}}):t);var s,c;let l=!n.scheduler&&!n.delay,u=Ue(n),d,f=!0,p=!1,m=n.equals||Kt,h=new En(a,()=>{f||l?r():p||(p=!0,u(r))},n.onError,n.requiresObservable);return n!=null&&(i=n.signal)!=null&&i.aborted||h.Y(),h.Z(n?.signal)},e.remove=function(e,n){wt(e)?e[j].Dt(n):ir(e)||sr(e)?e.delete(n):yt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=Be,e.set=function e(n,r,i){if(arguments.length===2&&!sr(n)){je();let t=r;try{for(let r in t)e(n,r,t[r])}finally{Me()}return}wt(n)?n[j].Bt(r,i):ir(n)?n.set(r,i):sr(n)?n.add(r):yt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(42,r),je(),r>=n.length&&(n.length=r+1),n[r]=i,Me()):t(8)},e.spy=function(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}},e.toJS=function(e){return it(e,new Map)},e.transaction=at,e.untracked=we,e.values=function(e){return wt(e)?$e(e).map(t=>e[t]):ir(e)?$e(e).map(t=>e.get(t)):sr(e)?Array.from(e.values()):yt(e)?e.slice():void t(6)},e.when=function(e,t,n){return arguments.length===1||t&&typeof t==`object`?function(e,t){var n;if(t!=null&&(n=t.signal)!=null&&n.aborted)return Pt(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let r,i,a=new Promise((n,a)=>{var o;let s=ot(e,n,Pt({},t,{onError:a}));r=()=>{s(),a(Error(`WHEN_CANCELLED`))},i=()=>{s(),a(Error(`WHEN_ABORTED`))},t==null||(o=t.signal)==null||o.addEventListener==null||o.addEventListener(`abort`,i)}).finally(()=>{var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,i)});return a.cancel=r,a}(e,t):ot(e,t,n||{})}})),dw=De((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t={0:`Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'`,1(e,t){return`Cannot apply '${e}' to '${t.toString()}': Field not found.`},5:`'keys()' can only be used on observable objects, arrays, sets and maps`,6:`'values()' can only be used on observable objects, arrays, sets and maps`,7:`'entries()' can only be used on observable objects, arrays and maps`,8:`'set()' can only be used on observable objects, arrays and maps`,9:`'remove()' can only be used on observable objects, arrays and maps`,10:`'has()' can only be used on observable objects, arrays and maps`,11:`'get()' can only be used on observable objects, arrays and maps`,12:`Invalid annotation`,13:`Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,14:`Intercept handlers should return nothing or a change object`,15:`Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,16:`Modification exception: the internal structure of an observable array was changed.`,19(e){return`Cannot initialize from classes that inherit from Map: `+e.constructor.name},20(e){return`Cannot initialize map from `+e},21(e){return`Cannot convert to map from '${e}'`},23:`It is not possible to get index atoms from arrays`,24(e){return`Cannot obtain administration from `+e},25(e,t){return`the entry '${e}' does not exist in the observable map '${t}'`},26:`please specify a property`,27(e,t){return`no observable property '${e.toString()}' found on the observable object '${t}'`},28(e){return`Cannot obtain atom from `+e},29:`Expecting some object`,30:`invalid action stack. did you forget to finish an action?`,31:`missing option for computed: get`,32(e,t){return`Cycle detected in computation ${e}: ${t}`},33(e){return`The setter of computed value '${e}' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?`},34(e){return`[ComputedValue '${e}'] It is not possible to assign a new value to a computed value.`},35:"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`",36:`isolateGlobalState should be called before MobX is running any reactions`,37(e){return`[mobx] \`observableArray.${e}()\` mutates the array in-place, which is not allowed inside a derivation. Use \`array.slice().${e}()\` instead`},38:`'ownKeys()' can only be used on observable objects`,39:`'defineProperty()' can only be used on observable objects`,40(e){return`Out of range: `+e},41(e){return`Cannot initialize set from `+e},42(e){return`Invalid index: '${e}'`},43(e,t,n){return`Cannot apply '${e}' to '${t}' (kind: ${n}):\n'${e}' can only be used on properties with a function value.`},44(e){return`'${e}' can only be used with 'makeObservable'`}};function n(e,...n){{let r=typeof e==`string`?e:t[e];throw typeof r==`function`&&(r=r.apply(null,n)),Error(`[MobX] ${r}`)}}let r=Object.assign,i=Object.getOwnPropertyDescriptor,a=Object.defineProperty,o=Object.prototype,s=[];Object.freeze(s);let c={};Object.freeze(c);let l=Object.toString();function u(){return++M.mobxGuid}function d(e){let t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}let f=()=>{};function p(e){return typeof e==`function`}function m(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function h(e){return typeof e==`object`&&!!e}function g(e){if(!h(e))return!1;let t=Object.getPrototypeOf(e);if(t==null)return!0;let n=D(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===l}function _(e){let t=e?.constructor;return t?t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`:!1}function v(e,t,n){a(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function y(e,t,n){a(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function b(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return h(e)&&e[n]===!0}}function x(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function S(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function C(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function w(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let T=Reflect.ownKeys;function E(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function ee(e){return e===null?null:typeof e==`object`?``+e:e}function D(e,t){return o.hasOwnProperty.call(e,t)}let te=Object.getOwnPropertyDescriptors;function O(e,t){return!!(e&t)}function k(e,t,n){return n?e|=t:e&=~t,e}function ne(e,t){t.includes(e.kind)||n(`The decorator applied to '${String(e.name)}' cannot be used on a ${e.kind} element`)}let A=Symbol(`mobx administration`);var re=class{constructor(e=`Atom@`+u()){this.name_=void 0,this.flags_=0,this.observers_=null,this.lastAccessedBy_=0,this.lowestObserverState_=-1,this.onBOL=void 0,this.onBUOL=void 0,this.name_=e}get isBeingObserved(){return O(this.flags_,1)}set isBeingObserved(e){this.flags_=k(this.flags_,1,e)}get isPendingUnobservation(){return O(this.flags_,2)}set isPendingUnobservation(e){this.flags_=k(this.flags_,2,e)}get diffValue(){return+!!O(this.flags_,4)}set diffValue(e){this.flags_=k(this.flags_,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return ln(this)}reportChanged(){an(),un(this),on()}toString(){return this.name_}};let ie=b(`Atom`,re);function ae(e,t=f,n=f){let r=new re(e);return t!==f&&(r.onBOL=new Set([t])),n!==f&&(r.onBUOL=new Set([n])),r}function oe(e,t){return e===t}function se(e,t){return Li(e,t)}function ce(e,t){return Li(e,t,1)}let le=Object.is;function ue(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||xr(e)?e:Array.isArray(e)?ut.array(e,{name:n}):g(e)?ut.object(e,void 0,{name:n}):x(e)?ut.map(e,{name:n}):C(e)?ut.set(e,{name:n}):typeof e==`function`&&!zn(e)&&!fr(e)?_(e)?cr(e):Fn(n,e):e}function de(e,t,r){if(e==null||Ai(e)||pi(e)||_i(e)||Si(e))return e;if(Array.isArray(e))return ut.array(e,{name:r,deep:!1});if(g(e))return ut.object(e,void 0,{name:r,deep:!1});if(x(e))return ut.map(e,{name:r,deep:!1});if(C(e))return ut.set(e,{name:r,deep:!1});n(`The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets`)}function fe(e){return e}function pe(e,t){return xr(e)&&n(`observable.struct should not be used with observable values`),Li(e,t)?t:e}let me=`override`,he={annotationType_:me,make_:_e,extend_:ve};function ge(e){return e.annotationType_===me}function _e(e,t){return e.isPlainObject_&&n(`Cannot apply '${this.annotationType_}' to '${e.name_}.${t.toString()}':\n'${this.annotationType_}' cannot be used on plain objects.`),D(e.appliedAnnotations_,t)||n(`'${e.name_}.${t.toString()}' is annotated with '${this.annotationType_}', but no such annotated member was found on prototype.`),0}function ve(e,t,r,i){n(44,this.annotationType_)}function ye(e,t){return{annotationType_:e,options_:t,make_:be,extend_:xe}}function be(e,t,n,r){var i;return(i=this.options_)!=null&&i.bound?this.extend_(e,t,n,!1)===null?0:1:r===e.target_?this.extend_(e,t,n,!1)===null?0:2:zn(n.value)?1:(a(r,t,we(e,this,t,n,!1)),2)}function xe(e,t,n,r){let i=we(e,this,t,n);return e.defineProperty_(t,i,r)}function Se(e,t,r){ne(r,[`method`,`field`]);let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>bt(s.options_?.name??a.toString(),e,s.options_?.autoAction??!1);if(i==`field`)return function(e){var t;let n=e;return zn(n)||(n=c(n)),(t=s.options_)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n};if(i==`method`){var l;return zn(t)||(t=c(t)),(l=s.options_)!=null&&l.bound&&o(function(){let e=this,t=e[a].bind(e);t.isMobxAction=!0,e[a]=t}),t}n(43,s.annotationType_,String(a),i)}function Ce(e,{annotationType_:t},r,{value:i}){p(i)||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on properties with a function value.`)}function we(e,t,n,r,i=M.safeDescriptors){var a,o;Ce(e,t,n,r);let{value:s}=r;return(a=t.options_)!=null&&a.bound&&(s=s.bind(e.proxy_??e.target_)),{value:bt(t.options_?.name??n.toString(),s,t.options_?.autoAction??!1,(o=t.options_)!=null&&o.bound?e.proxy_??e.target_:void 0),configurable:i?e.isPlainObject_:!0,enumerable:!1,writable:!i}}function Te(e,t){return{annotationType_:e,options_:t,make_:Ee,extend_:De}}function Ee(e,t,n,r){var i;return r===e.target_?this.extend_(e,t,n,!1)===null?0:2:(i=this.options_)!=null&&i.bound&&(!D(e.target_,t)||!fr(e.target_[t]))&&this.extend_(e,t,n,!1)===null?0:fr(n.value)?1:(a(r,t,Ae(e,this,t,n,!1,!1)),2)}function De(e,t,n,r){let i=Ae(e,this,t,n,this.options_?.bound);return e.defineProperty_(t,i,r)}function Oe(e,t,n){var r;ne(n,[`method`]);let{name:i,addInitializer:a}=n;return fr(t)||(t=cr(t)),(r=e.options_)!=null&&r.bound&&a(function(){let e=this,t=e[i].bind(e);t.isMobXFlow=!0,e[i]=t}),t}function ke(e,{annotationType_:t},r,{value:i}){p(i)||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on properties with a generator function value.`)}function Ae(e,t,n,r,i,a=M.safeDescriptors){ke(e,t,n,r);let{value:o}=r;return fr(o)||(o=cr(o)),i&&(o=o.bind(e.proxy_??e.target_),o.isMobXFlow=!0),{value:o,configurable:a?e.isPlainObject_:!0,enumerable:!1,writable:!a}}function je(e,t){return{annotationType_:e,options_:t,make_:Me,extend_:Ne}}function Me(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Ne(e,t,n,i){return Fe(e,this,t,n),e.defineComputedProperty_(t,r({},this.options_,{get:n.get,set:n.set}),i)}function Pe(e,t,n){ne(n,[`getter`]);let i=e,{name:a,addInitializer:o}=n,s;function c(e,n){let o=r({},i.options_,{get:t,context:e});return o.name||=`${n.name_}.${a.toString()}`,new kt(o)}return o(function(){let e=Di(this)[A],n=this,r=e.values_.get(a);r instanceof kt&&r.derivation!==t&&e.values_.delete(a),(e.lazyComputedKeys_??=new Map).set(a,()=>c(n,e))}),function(){let e=this[A],n=e.values_.get(a);if(n instanceof kt&&n.derivation!==t){let t=s?.get(this);return t||(t=c(this,e),(s??=new WeakMap).set(this,t)),t.get()}return e.getObservablePropValue_(a)}}function Fe(e,{annotationType_:t},r,{get:i}){i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on getter(+setter) properties.`)}function Ie(e,t){return{annotationType_:e,options_:t,make_:Le,extend_:Re}}function Le(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Re(e,t,n,r){return Be(e,this,t,n),e.defineObservableProperty_(t,n.value,this.options_?.enhancer_??ue,r)}function ze(e,t,r){if(r.kind===`field`)throw n(`Please use \`@observable accessor ${String(r.name)}\` instead of \`@observable ${String(r.name)}\``);ne(r,[`accessor`]);let i=e,{kind:a,name:o}=r;if(a!==`accessor`)return;function s(e,t){let n=Di(e)[A];return(n.lazyObservableKeys_??=new Map).set(o,()=>new Dt(t,i.options_?.enhancer_??ue,`${n.name_}.${o.toString()}`,!1)),n}return{get(){return(this[A]??s(this,t.get.call(this))).getObservablePropValue_(o)},set(e){return(this[A]??s(this,e)).setObservablePropValue_(o,e)},init(e){return s(this,e),e}}}function Be(e,{annotationType_:t},r,i){`value`in i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' cannot be used on getter/setter properties`)}let Ve=He();function He(e){return{annotationType_:`true`,options_:e,make_:Ge,extend_:Ke}}let Ue=[Ve];function We(e){let t=e.deep!==!1,n=!!e.autoBind,r=!t|(n?2:0);return Ue[r]??(Ue[r]=He({deep:t,autoBind:n}))}function Ge(e,t,n,r){var i;if(n.get)return ht.make_(e,t,n,r);if(n.set){let i=zn(n.set)?n.set:bt(t.toString(),n.set);return r===e.target_?e.defineProperty_(t,{configurable:M.safeDescriptors?e.isPlainObject_:!0,set:i})===null?0:2:(a(r,t,{configurable:!0,set:i}),2)}if(r!==e.target_&&typeof n.value==`function`){var o;if(_(n.value)){var s;return((s=this.options_)!=null&&s.autoBind?lr:cr).make_(e,t,n,r)}return((o=this.options_)!=null&&o.autoBind?Ln:Fn).make_(e,t,n,r)}let c=this.options_?.deep===!1?ot:ut;return typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),c.make_(e,t,n,r)}function Ke(e,t,n,r){var i;return n.get?ht.extend_(e,t,n,r):n.set?e.defineProperty_(t,{configurable:M.safeDescriptors?e.isPlainObject_:!0,set:bt(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),(this.options_?.deep===!1?ot:ut).extend_(e,t,n,r))}function qe(e,t){return r(function(r,i){if(i&&typeof i.kind==`string`)return t(e,r,i);n(`Invalid arguments for \`${e.annotationType_}\``)},e)}let Je={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Je);function Ye(e){return e||Je}let Xe=Ie(`observable`),Ze=Ie(`observable.ref`,{enhancer_:fe}),Qe=Ie(`observable.shallow`,{enhancer_:de}),$e=Ie(`observable.struct`,{enhancer_:pe});function et(e){return qe(e,ze)}function tt(e){return e.deep===!0?ue:e.deep===!1?fe:rt(e.defaultDecorator)}function nt(e){return e?e.defaultDecorator??We(e):void 0}function rt(e){return e?e.options_?.enhancer_??ue:ue}function it(e,t,n){return t&&typeof t.kind==`string`?ze(Xe,e,t):xr(e)?e:g(e)?ut.object(e,t,n):Array.isArray(e)?ut.array(e,t):x(e)?ut.map(e,t):C(e)?ut.set(e,t):typeof e==`object`&&e?e:ut.box(e,t)}let at={box(e,t){let n=Ye(t);return new Dt(e,tt(n),n.name,!0,n.equals)},array(e,t){let n=Ye(t);return oi(e,tt(n),n.name)},map(e,t){let n=Ye(t);return new gi(e,tt(n),n.name)},set(e,t){let n=Ye(t);return new xi(e,tt(n),n.name)},object(e,t,n){return Fi(()=>Xn(Gr({},n),e,t))}},ot=et(Ze),st=et(Qe),ct=et(Xe),lt=et($e);var ut=r(it,Xe,at);let dt=`computed`;function ft(e){return qe(e,Pe)}let pt=je(dt),mt=ft(je(`computed.struct`,{equals:se})),ht=function(e,t){if(t&&typeof t.kind==`string`)return Pe(pt,e,t);if(g(e))return ft(je(dt,e));p(e)||n("First argument to `computed` should be an expression."),p(t)&&n("A setter as second argument is no longer supported, use `{ set: fn }` option instead");let r=g(t)?t:{};return r.get=e,r.name||=e.name||``,new kt(r)};r(ht,pt);let gt=0,_t=1,vt=i(()=>{},`name`)?.configurable??!1,yt={value:`action`,configurable:!0,writable:!1,enumerable:!1};function bt(e,t,r=!1,i){p(t)||n("`action` can only be invoked on functions"),(typeof e!=`string`||!e)&&n(`actions should have valid names, got: '${e}'`);function o(){return xt(e,r,t,i||this,arguments)}return o.isMobxAction=!0,o.toString=()=>t.toString(),vt&&(yt.value=e,a(o,`name`,yt)),o}function xt(e,t,n,r,i){let a=St(e,t,r,i);try{return n.apply(r,i)}catch(e){throw a.error_=e,e}finally{Ct(a)}}function St(e,t,n,r){let i=bn()&&!!e,a=0;i&&(a=Date.now(),Sn({type:N,name:e,object:n,arguments:r?Array.from(r):s}));let o=M.trackingDerivation,c=!t||!o;an();let l=M.allowStateChanges;c&&(Ht(),l=Tt(!0));let u=M.allowStateReads;j(!0);let d={runAsAction_:c,prevDerivation_:o,prevAllowStateChanges_:l,prevAllowStateReads_:u,notifySpy_:i,startTime_:a,actionId_:_t++,parentActionId_:gt};return gt=d.actionId_,d}function Ct(e){gt!==e.actionId_&&n(30),gt=e.parentActionId_,e.error_!==void 0&&(M.suppressReactionErrors=!0),Et(e.prevAllowStateChanges_),Wt(e.prevAllowStateReads_),on(),e.runAsAction_&&Ut(e.prevDerivation_),e.notifySpy_&&wn({time:Date.now()-e.startTime_}),M.suppressReactionErrors=!1}function wt(e,t){let n=Tt(e);try{return t()}finally{Et(n)}}function Tt(e){let t=M.allowStateChanges;return M.allowStateChanges=e,t}function Et(e){M.allowStateChanges=e}var Dt=class extends re{constructor(e,t,n=`ObservableValue@`+u(),r=!0,i=le){super(n),this.enhancer_=void 0,this.name_=void 0,this.equals_=void 0,this.hasUnreportedChange_=!1,this.interceptors_=void 0,this.changeListeners_=void 0,this.value_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,this.equals_=i,this.value_=t(e,void 0,n),r&&bn()&&xn({type:`create`,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:this.value_})}dehanceValue(e){return this.dehancer===void 0?e:this.dehancer(e)}set(e){let t=this.value_;if(e=this.prepareNewValue_(e),e!==M.UNCHANGED){let n=bn();n&&Sn({type:ri,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:e,oldValue:t}),this.setNewValue_(e),n&&wn()}}prepareNewValue_(e){if(Ft(this),Kr(this)){let t=Jr(this,{object:this,type:ri,newValue:e});if(!t)return M.UNCHANGED;e=t.newValue}return e=this.enhancer_(e,this.value_,this.name_),this.equals_(this.value_,e)?M.UNCHANGED:e}setNewValue_(e){let t=this.value_;this.value_=e,this.reportChanged(),Yr(this)&&Zr(this,{type:ri,object:this,newValue:e,oldValue:t})}get(){return this.reportObserved(),this.dehanceValue(this.value_)}raw(){return this.value_}toJSON(){return this.get()}toString(){return`${this.name_}[${this.value_}]`}valueOf(){return ee(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let Ot=b(`ObservableValue`,Dt);var kt=class{constructor(e){this.dependenciesState_=-1,this.observing_=[],this.newObserving_=null,this.observers_=null,this.runId_=0,this.lastAccessedBy_=0,this.lowestObserverState_=0,this.unboundDepsCount_=0,this.value_=new jt(null),this.name_=void 0,this.triggeredBy_=void 0,this.flags_=0,this.derivation=void 0,this.setter_=void 0,this.scope_=void 0,this.equals_=void 0,this.requiresReaction_=void 0,this.keepAlive_=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||n(31),this.derivation=e.get,this.name_=e.name||`ComputedValue@`+u(),e.set&&(this.setter_=bt(this.name_+`-setter`,e.set)),this.equals_=e.equals||le,this.scope_=e.context,this.requiresReaction_=e.requiresReaction,this.keepAlive_=!!e.keepAlive}onBecomeStale_(){fn(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return O(this.flags_,1)}set isComputing(e){this.flags_=k(this.flags_,1,e)}get isRunningSetter(){return O(this.flags_,2)}set isRunningSetter(e){this.flags_=k(this.flags_,2,e)}get isBeingObserved(){return O(this.flags_,4)}set isBeingObserved(e){this.flags_=k(this.flags_,4,e)}get isPendingUnobservation(){return O(this.flags_,8)}set isPendingUnobservation(e){this.flags_=k(this.flags_,8,e)}get diffValue(){return+!!O(this.flags_,16)}set diffValue(e){this.flags_=k(this.flags_,16,e===1)}get(){if(this.isComputing&&n(32,this.name_,this.derivation),M.inBatch===0&&(!this.observers_||this.observers_.size===0)&&!this.keepAlive_)Nt(this)&&(this.warnAboutUntrackedRead_(),an(),this.value_=this.computeValue_(!1),on());else{let e=this.isBeingObserved;if(ln(this),Nt(this)){let e=M.trackingContext;!e&&(this.keepAlive_||this.isBeingObserved)&&(M.trackingContext=this),this.trackAndCompute()&&dn(this),M.trackingContext=e}else !e&&this.isBeingObserved&&this.observing_.forEach(cn)}let e=this.value_;if(Mt(e))throw e.cause;return e}set(e){if(this.setter_){this.isRunningSetter&&n(33,this.name_),this.isRunningSetter=!0;try{this.setter_.call(this.scope_,e)}finally{this.isRunningSetter=!1}}else n(34,this.name_)}trackAndCompute(){let e=this.value_,t=this.dependenciesState_===-1,n=this.computeValue_(!0),r=t||Mt(e)||Mt(n)||!this.equals_(e,n);return r&&(this.value_=n,bn()&&xn({observableKind:`computed`,debugObjectName:this.name_,object:this.scope_,type:`update`,oldValue:e,newValue:n})),r}computeValue_(e){this.isComputing=!0;let t=Tt(!1),n;if(e)n=Lt(this,this.derivation,this.scope_);else if(M.disableErrorBoundaries===!0)n=this.derivation.call(this.scope_);else try{n=this.derivation.call(this.scope_)}catch(e){n=new jt(e)}return Et(t),this.isComputing=!1,n}suspend_(){this.keepAlive_||(Bt(this),this.value_=void 0)}warnAboutUntrackedRead_(){(typeof this.requiresReaction_==`boolean`?this.requiresReaction_:M.computedRequiresReaction)&&console.warn(`[mobx] Computed value '${this.name_}' is being read outside a reactive context. Doing a full recompute.`)}toString(){return`${this.name_}[${this.derivation.toString()}]`}valueOf(){return ee(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let At=b(`ComputedValue`,kt);var jt=class{constructor(e){this.cause=void 0,this.cause=e}};function Mt(e){return e instanceof jt}function Nt(e){switch(e.dependenciesState_){case 0:return!1;case-1:case 2:return!0;case 1:{let t=j(!0),n=Ht(),r=e.observing_,i=r.length;for(let a=0;a<i;a++){let i=r[a];if(At(i)){if(M.disableErrorBoundaries)i.get();else try{i.get()}catch{return Ut(n),Wt(t),!0}if(e.dependenciesState_===2)return Ut(n),Wt(t),!0}}return Gt(e),Ut(n),Wt(t),!1}}}function Pt(){return M.trackingDerivation!==null}function Ft(e){let t=!!e.observers_&&e.observers_.size>0;!M.allowStateChanges&&(t||M.enforceActions===`always`)&&console.warn(`[MobX] `+(M.enforceActions?`Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: `:`Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: `)+e.name_)}function It(e){!M.allowStateReads&&M.observableRequiresReaction&&console.warn(`[mobx] Observable '${e.name_}' being read outside a reactive context.`)}function Lt(e,t,n){let r=j(!0);Gt(e),e.newObserving_=Array(e.runId_===0?100:e.observing_.length),e.unboundDepsCount_=0,e.runId_=++M.runId;let i=M.trackingDerivation;M.trackingDerivation=e,M.inBatch++;let a;if(M.disableErrorBoundaries===!0)a=t.call(n);else try{a=t.call(n)}catch(e){a=new jt(e)}return M.inBatch--,M.trackingDerivation=i,zt(e),Rt(e),Wt(r),a}function Rt(e){e.observing_.length===0&&(typeof e.requiresObservable_==`boolean`?e.requiresObservable_:M.reactionRequiresObservable)&&console.warn(`[mobx] Derivation '${e.name_}' is created/updated without reading any observable value.`)}function zt(e){let t=e.observing_,n=e.observing_=e.newObserving_,r=0,i=0,a=e.unboundDepsCount_;for(let e=0;e<a;e++){let t=n[e];t.diffValue===0&&(t.diffValue=1,i!==e&&(n[i]=t),i++),t.dependenciesState_>r&&(r=t.dependenciesState_)}for(n.length=i,e.newObserving_=null,a=t.length;a--;){let n=t[a];n.diffValue===0&&nn(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,tn(t,e))}r!==0&&(e.dependenciesState_=r,e.onBecomeStale_())}function Bt(e){let t=e.observing_;e.observing_=[];let n=t.length;for(;n--;)nn(t[n],e);e.dependenciesState_=-1}function Vt(e){let t=Ht();try{return e()}finally{Ut(t)}}function Ht(){let e=M.trackingDerivation;return M.trackingDerivation=null,e}function Ut(e){M.trackingDerivation=e}function j(e){let t=M.allowStateReads;return M.allowStateReads=e,t}function Wt(e){M.allowStateReads=e}function Gt(e){if(e.dependenciesState_===0)return;e.dependenciesState_=0;let t=e.observing_,n=t.length;for(;n--;)t[n].lowestObserverState_=0}let Kt=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var qt=class{constructor(){this.version=7,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.isRunningUnobservations=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.safeDescriptors=!0}};let Jt=!0,Yt=!1,M=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Jt=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(Jt=!1),Jt?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new qt):(setTimeout(()=>{Yt||n(35)},1),new qt)}();function Xt(){if((M.pendingReactions.length||M.inBatch||M.isRunningReactions)&&n(36),Yt=!0,Jt){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),M=new qt}}function Zt(){return M}function Qt(){let e=new qt;for(let t in e)Kt.indexOf(t)===-1&&(M[t]=e[t]);M.allowStateChanges=!M.enforceActions}function $t(e){return!!e.observers_&&e.observers_.size>0}function en(e){return e.observers_??new Set}function tn(e,t){(e.observers_??=new Set).add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function nn(e,t){let n=e.observers_;n&&(n.delete(t),n.size===0&&rn(e))}function rn(e){e.isPendingUnobservation===!1&&(e.isPendingUnobservation=!0,M.pendingUnobservations.push(e))}function an(){M.inBatch++}function on(){--M.inBatch===0&&(gn(),!M.isRunningUnobservations&&M.pendingUnobservations.length>0&&sn())}function sn(){M.isRunningUnobservations=!0;try{let e=M.pendingUnobservations;for(let t=0;t<e.length;t++){let n=e[t];n.isPendingUnobservation=!1,(!n.observers_||n.observers_.size===0)&&(n.observers_=null,n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof kt&&n.suspend_())}M.pendingUnobservations=[]}finally{M.isRunningUnobservations=!1}}function cn(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.observing_)==null||t.forEach(cn))}function ln(e){It(e);let t=M.trackingDerivation;return t===null?((!e.observers_||e.observers_.size===0)&&M.inBatch>0&&rn(e),!1):(t.runId_!==e.lastAccessedBy_&&(e.lastAccessedBy_=t.runId_,t.newObserving_[t.unboundDepsCount_++]=e,!e.isBeingObserved&&M.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function un(e){var t;e.lowestObserverState_!==2&&(e.lowestObserverState_=2,(t=e.observers_)==null||t.forEach(e=>{e.dependenciesState_===0&&e.onBecomeStale_(),e.dependenciesState_=2}))}function dn(e){var t;e.lowestObserverState_!==2&&(e.lowestObserverState_=2,(t=e.observers_)==null||t.forEach(t=>{t.dependenciesState_===1?t.dependenciesState_=2:t.dependenciesState_===0&&(e.lowestObserverState_=0)}))}function fn(e){var t;e.lowestObserverState_===0&&(e.lowestObserverState_=1,(t=e.observers_)==null||t.forEach(e=>{e.dependenciesState_===0&&(e.dependenciesState_=1,e.onBecomeStale_())}))}var pn=class{constructor(e=`Reaction@`+u(),t,n,r){this.name_=void 0,this.onInvalidate_=void 0,this.errorHandler_=void 0,this.requiresObservable_=void 0,this.observing_=[],this.newObserving_=[],this.dependenciesState_=-1,this.runId_=0,this.unboundDepsCount_=0,this.flags_=0,this.removeAbortListener_=void 0,this.name_=e,this.onInvalidate_=t,this.errorHandler_=n,this.requiresObservable_=r}get isDisposed(){return O(this.flags_,1)}set isDisposed(e){this.flags_=k(this.flags_,1,e)}get isScheduled(){return O(this.flags_,2)}set isScheduled(e){this.flags_=k(this.flags_,2,e)}get isTrackPending(){return O(this.flags_,4)}set isTrackPending(e){this.flags_=k(this.flags_,4,e)}get isRunning(){return O(this.flags_,8)}set isRunning(e){this.flags_=k(this.flags_,8,e)}get diffValue(){return+!!O(this.flags_,16)}set diffValue(e){this.flags_=k(this.flags_,16,e===1)}onBecomeStale_(){this.schedule_()}schedule_(){this.isScheduled||(this.isScheduled=!0,M.pendingReactions.push(this),gn())}runReaction_(){if(!this.isDisposed){an(),this.isScheduled=!1;let e=M.trackingContext;if(M.trackingContext=this,Nt(this)){this.isTrackPending=!0;try{this.onInvalidate_(),this.isTrackPending&&bn()&&xn({name:this.name_,type:`scheduled-reaction`})}catch(e){this.reportExceptionInDerivation_(e)}}M.trackingContext=e,on()}}track(e){if(this.isDisposed)return;an();let t=bn(),n;t&&(n=Date.now(),Sn({name:this.name_,type:`reaction`})),this.isRunning=!0;let r=M.trackingContext;M.trackingContext=this;let i=Lt(this,e,void 0);M.trackingContext=r,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Bt(this),Mt(i)&&this.reportExceptionInDerivation_(i.cause),t&&wn({time:Date.now()-n}),on()}reportExceptionInDerivation_(e){if(this.errorHandler_){this.errorHandler_(e,this);return}if(M.disableErrorBoundaries)throw e;let t=`[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '${this}'`;M.suppressReactionErrors?console.warn(`[mobx] (error in reaction '${this.name_}' suppressed, fix error of causing action below)`):console.error(t,e),bn()&&xn({type:`error`,name:this.name_,message:t,error:``+e}),M.globalReactionErrorHandlers.forEach(t=>t(e,this))}dispose(){if(!this.isDisposed){var e;this.isDisposed=!0,(e=this.removeAbortListener_)==null||e.call(this),this.isRunning||(an(),Bt(this),on())}}getDisposer_(e){let t=()=>this.dispose();return e!=null&&e.addEventListener&&!this.isDisposed&&(e.addEventListener(`abort`,t),this.removeAbortListener_=()=>e.removeEventListener==null?void 0:e.removeEventListener(`abort`,t)),t[A]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.name_}]`}};function mn(e){return M.globalReactionErrorHandlers.push(e),()=>{let t=M.globalReactionErrorHandlers.indexOf(e);t>=0&&M.globalReactionErrorHandlers.splice(t,1)}}let hn=e=>e();function gn(){M.inBatch>0||M.isRunningReactions||hn(_n)}function _n(){M.isRunningReactions=!0;let e=M.pendingReactions,t=0;for(;e.length>0;){++t===100&&(console.error(`Reaction doesn't converge to a stable state after 100 iterations. Probably there is a cycle in the reactive function: ${e[0]}`),e.splice(0));let n=e.splice(0);for(let e=0,t=n.length;e<t;e++)n[e].runReaction_()}M.isRunningReactions=!1}let vn=b(`Reaction`,pn);function yn(e){let t=hn;hn=n=>e(()=>t(n))}function bn(){return!!M.spyListeners.length}function xn(e){if(!M.spyListeners.length)return;let t=M.spyListeners;for(let n=0,r=t.length;n<r;n++)t[n](e)}function Sn(e){xn(r({},e,{spyReportStart:!0}))}let Cn={type:`report-end`,spyReportEnd:!0};function wn(e){xn(e?r({},e,{type:`report-end`,spyReportEnd:!0}):Cn)}function Tn(e){return M.spyListeners.push(e),d(()=>{M.spyListeners=M.spyListeners.filter(t=>t!==e)})}let N=`action`,En=`autoAction`,Dn=`<unnamed action>`,On=ye(N),kn=ye(`action.bound`,{bound:!0}),An=ye(En,{autoAction:!0}),jn=ye(`autoAction.bound`,{autoAction:!0,bound:!0});function Mn(e){return qe(e,Se)}function Nn(e){return function(t,r){if(r&&typeof r.kind==`string`)return Se(e?An:On,t,r);if(p(t))return bt(t.name||Dn,t,e);if(p(r))return bt(t,r,e);if(m(t))return Mn(ye(e?En:N,{name:t,autoAction:e}));n("Invalid arguments for `action`")}}let Pn=Nn(!1);r(Pn,On);let Fn=Nn(!0);r(Fn,An);let In=Mn(kn),Ln=Mn(jn);function Rn(e){return xt(e.name||Dn,!1,e,this,void 0)}function zn(e){return p(e)&&e.isMobxAction===!0}function Bn(e,t=c){var r;p(e)||n(`Autorun expects a function as first argument`),zn(e)&&n(`Autorun does not accept actions since actions are untrackable`);let i=t?.name??(e.name||`Autorun@`+u()),a=!t.scheduler&&!t.delay,o;if(a)o=new pn(i,function(){this.track(s)},t.onError,t.requiresObservable);else{let e=Hn(t),n=!1;o=new pn(i,()=>{n||(n=!0,e(()=>{n=!1,o.isDisposed||o.track(s)}))},t.onError,t.requiresObservable)}function s(){e(o)}return t!=null&&(r=t.signal)!=null&&r.aborted||o.schedule_(),o.getDisposer_(t?.signal)}let Vn=e=>e();function Hn(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Vn}function Un(e,t,r=c){var i;(!p(e)||!p(t))&&n(`First and second argument to reaction should be functions`),g(r)||n(`Third argument of reactions should be an object`);let a=r.name??`Reaction@`+u(),o=Pn(a,r.onError?Wn(r.onError,t):t),s=!r.scheduler&&!r.delay,l=Hn(r),d=!0,f=!1,m,h=r.equals||le,_=new pn(a,()=>{d||s?v():f||(f=!0,l(v))},r.onError,r.requiresObservable);function v(){if(f=!1,_.isDisposed)return;let t=!1,n=m;_.track(()=>{let n=wt(!1,()=>e(_));t=d||!h(m,n),m=n}),(d&&r.fireImmediately||!d&&t)&&o(m,n,_),d=!1}return r!=null&&(i=r.signal)!=null&&i.aborted||_.schedule_(),_.getDisposer_(r?.signal)}function Wn(e,t){return function(){try{return t.apply(this,arguments)}catch(t){e.call(this,t)}}}function Gn(e,t,n){return qn(`onBO`,e,t,n)}function Kn(e,t,n){return qn(`onBUO`,e,t,n)}function qn(e,t,n,r){let i=typeof r==`function`?P(t,n):P(t),a=p(r)?r:n,o=`${e}L`;return i[o]?i[o].add(a):i[o]=new Set([a]),function(){let e=i[o];e&&(e.delete(a),e.size===0&&delete i[o])}}let Jn=`always`;function Yn(e){e.isolateGlobalState===!0&&Xt();let{enforceActions:t}=e;if(t!==void 0){let e=t===Jn?Jn:t===`observed`;M.enforceActions=e,M.allowStateChanges=!(e===!0||e===Jn)}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(M[t]=!!e[t])}),M.allowStateReads=!M.observableRequiresReaction,M.disableErrorBoundaries===!0&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),e.reactionScheduler&&yn(e.reactionScheduler)}function Xn(e,t,r,i){arguments.length>4&&n(`'extendObservable' expected 2-4 arguments`),typeof e!=`object`&&n(`'extendObservable' expects an object as first argument`),_i(e)&&n(`'extendObservable' should not be used on maps, use map.merge instead`),g(t)||n(`'extendObservable' only accepts plain objects as second argument`),(xr(t)||xr(r))&&n(`Extending an object with another observable (object) is not supported`);let a=te(t);return Fi(()=>{let t=Di(e,i)[A];T(a).forEach(e=>{t.extend_(e,a[e],r&&e in r?r[e]:!0)})}),e}function Zn(e,t){return Qn(P(e,t))}function Qn(e){let t={name:e.name_};return e.observing_&&e.observing_.length>0&&(t.dependencies=tr(e.observing_).map(Qn)),t}function $n(e,t){return er(P(e,t))}function er(e){let t={name:e.name_};return $t(e)&&(t.observers=Array.from(en(e),er)),t}function tr(e){return Array.from(new Set(e))}let nr=0;var rr=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};function ir(e){return e instanceof rr}function ar(e){return qe(e,Oe)}let or=Te(`flow`),sr=Te(`flow.bound`,{bound:!0}),cr=r(function(e,t){if(t&&typeof t.kind==`string`)return Oe(or,e,t);arguments.length!==1&&n(`Flow expects single argument with generator function`);let r=e,i=r.name||`<unnamed flow>`,a=function(){let e=this,t=arguments,n=++nr,a=Pn(`${i} - runid: ${n} - init`,r).apply(e,t),o,s,c=new Promise(function(e,t){let r=0;o=t;function c(e){s=void 0;let o;try{o=Pn(`${i} - runid: ${n} - yield ${r++}`,a.next).call(a,e)}catch(e){return t(e)}u(o)}function l(e){s=void 0;let o;try{o=Pn(`${i} - runid: ${n} - yield ${r++}`,a.throw).call(a,e)}catch(e){return t(e)}u(o)}function u(n){if(p(n?.then)){n.then(u,t);return}return n.done?e(n.value):(s=Promise.resolve(n.value),s.then(c,l))}c(void 0)});return c.cancel=Pn(`${i} - runid: ${n} - cancel`,function(){try{s&&ur(s);let e=a.return(void 0),t=Promise.resolve(e.value);t.then(f,f),ur(t),o(new rr)}catch(e){o(e)}}),c};return a.isMobXFlow=!0,a},or),lr=ar(sr);function ur(e){p(e.cancel)&&e.cancel()}function dr(e){return e}function fr(e){return e?.isMobXFlow===!0}function pr(e,t,r){let i;if(_i(e)||pi(e)||Ot(e))i=Ni(e);else if(Ai(e)){if(!m(t))return n(`InterceptReads can only be used with a specific property, not with an object in general`);i=Ni(e,t)}else return n(`Expected observable map, object or array as first array`);return i.dehancer===void 0?(i.dehancer=typeof t==`function`?t:r,()=>{i.dehancer=void 0}):n(`An intercept reader was already established`)}function mr(e,t,n){return p(n)?gr(e,t,n):hr(e,t)}function hr(e,t){return qr(Ni(e),t)}function gr(e,t,n){return qr(Ni(e,t),n)}function _r(e,t){var n;if(t===void 0)return At(e);if(Ai(e)===!1)return!1;let r=e[A];return(n=r.lazyComputedKeys_)!=null&&n.has(t)?!0:r.values_.has(t)?At(P(e,t)):!1}function vr(e){return arguments.length>1?n(`isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property`):_r(e)}function yr(e,t){return m(t)?_r(e,t):n(`isComputed expected a property name as second argument`)}function br(e,t){if(!e)return!1;if(t!==void 0){if(_i(e)||pi(e))return n(`isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.`);if(Ai(e)){var r,i;let n=e[A];return n.values_.has(t)||!!((r=n.lazyComputedKeys_)!=null&&r.has(t))||!!((i=n.lazyObservableKeys_)!=null&&i.has(t))}return!1}return Ai(e)||!!e[A]||ie(e)||vn(e)||At(e)}function xr(e){return arguments.length!==1&&n(`isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property`),br(e)}function Sr(e,t){return m(t)?br(e,t):n(`expected a property name as second argument`)}function Cr(e){if(Ai(e))return e[A].keys_();if(_i(e)||Si(e))return Array.from(e.keys());if(pi(e))return e.map((e,t)=>t);n(5)}function wr(e){if(Ai(e))return Cr(e).map(t=>e[t]);if(_i(e))return Cr(e).map(t=>e.get(t));if(Si(e))return Array.from(e.values());if(pi(e))return e.slice();n(6)}function Tr(e){if(Ai(e))return Cr(e).map(t=>[t,e[t]]);if(_i(e))return Cr(e).map(t=>[t,e.get(t)]);if(Si(e))return Array.from(e.entries());if(pi(e))return e.map((e,t)=>[t,e]);n(7)}function Er(e,t,r){if(arguments.length===2&&!Si(e)){an();let n=t;try{for(let t in n)Er(e,t,n[t])}finally{on()}return}Ai(e)?e[A].set_(t,r):_i(e)?e.set(t,r):Si(e)?e.add(t):pi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),t<0&&n(42,t),an(),t>=e.length&&(e.length=t+1),e[t]=r,on()):n(8)}function Dr(e,t){Ai(e)?e[A].delete_(t):_i(e)||Si(e)?e.delete(t):pi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),e.splice(t,1)):n(9)}function Or(e,t){if(Ai(e))return e[A].has_(t);if(_i(e)||Si(e))return e.has(t);if(pi(e))return t>=0&&t<e.length;n(10)}function kr(e,t){if(Or(e,t)){if(Ai(e))return e[A].get_(t);if(_i(e))return e.get(t);if(pi(e))return e[t];n(11)}}function Ar(e,t,r){if(Ai(e))return e[A].defineProperty_(t,r);n(39)}function jr(e){if(Ai(e))return e[A].ownKeys_();n(38)}function Mr(e,t,n,r){return p(n)?Pr(e,t,n,r):Nr(e,t,n)}function Nr(e,t,r){let i=Ni(e);if(pi(e))r&&t({observableKind:`array`,object:i.proxy_,debugObjectName:i.atom_.name_,type:`splice`,index:0,added:i.values_.slice(),addedCount:i.values_.length,removed:[],removedCount:0});else if(_i(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with maps.");else if(Si(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with sets.");else if(Ai(e))r===!0&&n("`observe` doesn't support the fire immediately property for observable objects.");else return Fr(i,t,r);return Xr(i,t)}function Pr(e,t,n,r){return Fr(Ni(e,t),n,r)}function Fr(e,t,n){if(At(e)){let r=!0,i;return Bn(()=>{let a=e.get();if(!r||n){let n=Ht();t({observableKind:`computed`,debugObjectName:e.name_,type:ri,object:e,newValue:a,oldValue:i}),Ut(n)}r=!1,i=a})}return n&&t({observableKind:`value`,debugObjectName:e.name_,object:e,type:ri,newValue:e.value_,oldValue:void 0}),Xr(e,t)}function Ir(e,t,n){return e.set(t,n),n}function Lr(e,t){if(typeof e!=`object`||!e||e instanceof Date||!xr(e))return e;if(Ot(e)||At(e))return Lr(e.get(),t);if(t.has(e))return t.get(e);if(pi(e)){let n=Ir(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=Lr(e,t)}),n}if(Si(e)){let n=Ir(t,e,new Set);return e.forEach(e=>{n.add(Lr(e,t))}),n}if(_i(e)){let n=Ir(t,e,new Map);return e.forEach((e,r)=>{n.set(r,Lr(e,t))}),n}else{let n=Ir(t,e,{});return jr(e).forEach(r=>{o.propertyIsEnumerable.call(e,r)&&(n[r]=Lr(e[r],t))}),n}}function Rr(e,t){return t&&n(`toJS no longer supports options`),Lr(e,new Map)}function zr(e,t=void 0){an();try{return e.apply(t)}finally{on()}}function Br(e,t,n){return arguments.length===1||t&&typeof t==`object`?Hr(e,t):Vr(e,t,n||{})}function Vr(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[A].isDisposed)if(a(),n.onError)n.onError(e);else throw e},n.timeout)}n.name=n.name||`When@`+u();let i=bt(n.name+`-effect`,t);var a=Bn(t=>{wt(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function Hr(e,t){var i;if(t&&t.onError)return n(`the options 'onError' and 'promise' cannot be combined`);if(t!=null&&(i=t.signal)!=null&&i.aborted)return r(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let a,o,s=new Promise((n,i)=>{var s;let c=Vr(e,n,r({},t,{onError:i}));a=()=>{c(),i(Error(`WHEN_CANCELLED`))},o=()=>{c(),i(Error(`WHEN_ABORTED`))},t==null||(s=t.signal)==null||s.addEventListener==null||s.addEventListener(`abort`,o)}).finally(()=>{var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,o)});return s.cancel=a,s}function Ur(e){return e[A]}let Wr={has(e,t){return Ur(e).has_(t)},get(e,t){return Ur(e).get_(t)},set(e,t,n){return m(t)?Ur(e).set_(t,n,!0)??!0:!1},deleteProperty(e,t){return m(t)?Ur(e).delete_(t,!0)??!0:!1},defineProperty(e,t,n){return Ur(e).defineProperty_(t,n)??!0},ownKeys(e){return Ur(e).ownKeys_()},preventExtensions(e){n(13)}};function Gr(e,t){var n;return e=Di(e,t),(n=e[A]).proxy_??(n.proxy_=new Proxy(e,Wr))}function Kr(e){return e.interceptors_!==void 0&&e.interceptors_.length>0}function qr(e,t){let n=e.interceptors_;return n?n.push(t):n=e.interceptors_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Jr(e,t){let r=Ht();try{let r=[...e.interceptors_||[]];for(let e=0,i=r.length;e<i&&(t=r[e](t),t&&!t.type&&n(14),t);e++);return t}finally{Ut(r)}}function Yr(e){return e.changeListeners_!==void 0&&e.changeListeners_.length>0}function Xr(e,t){let n=e.changeListeners_;return n?n.push(t):n=e.changeListeners_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Zr(e,t){let n=Ht(),r=e.changeListeners_;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Ut(n)}}function Qr(e,t,n){return Fi(()=>{let r=Di(e,n)[A];T(t).forEach(e=>ti(r,e,t[e]))}),e}let $r=Symbol(`mobx-keys`);function ei(e,t,r){return!g(e)&&!g(Object.getPrototypeOf(e))&&n(`'makeAutoObservable' can only be used for classes that don't have a superclass`),Ai(e)&&n(`makeAutoObservable can only be used on objects not already made observable`),g(e)?Xn(e,e,t,r):(Fi(()=>{let n=Di(e,r)[A];if(!e[$r]){let t=Object.getPrototypeOf(e),n=new Set([...T(e),...T(t)]);n.delete(`constructor`),n.delete(A),v(t,$r,n)}e[$r].forEach(e=>ti(n,e,t&&e in t?t[e]:!0))}),e)}function ti(e,t,r){if(r===!0&&(r=e.defaultAnnotation_),r===!1)return;Mi(e,r,t),t in e.target_||n(1,r.annotationType_,`${e.name_}.${t.toString()}`);let a=e.target_;for(;a&&a!==o;){let n=i(a,t);if(n){let i=r.make_(e,t,n,a);if(i===0)return;if(i===1)break}a=Object.getPrototypeOf(a)}ji(e,r,t)}let ni=`splice`,ri=`update`,ii={get(e,t){let n=e[A];return t===A?n:t===`length`?n.getArrayLength_():typeof t==`string`&&!isNaN(t)?n.get_(parseInt(t)):D(si,t)?si[t]:e[t]},set(e,t,n){let r=e[A];return t===`length`?r.setArrayLength_(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.set_(parseInt(t),n),!0},preventExtensions(){n(15)}};var ai=class{constructor(e=`ObservableArray@`+u(),t,n){this.owned_=void 0,this.atom_=void 0,this.values_=[],this.interceptors_=void 0,this.changeListeners_=void 0,this.enhancer_=void 0,this.dehancer=void 0,this.proxy_=void 0,this.lastKnownLength_=0,this.owned_=n,this.atom_=new re(e),this.enhancer_=(n,r)=>t(n,r,e+`[..]`)}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}dehanceValues_(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e}getArrayLength_(){return this.atom_.reportObserved(),this.values_.length}setArrayLength_(e){(!Number.isInteger(e)||e<0)&&n(40,e);let t=this.values_.length;if(e!==t)if(e>t){let n=Array.from({length:e-t});this.spliceWithArray_(t,0,n)}else this.spliceWithArray_(e,t-e)}updateArrayLength_(e,t){e!==this.lastKnownLength_&&n(16),this.lastKnownLength_+=t}spliceWithArray_(e,t,n){Ft(this.atom_);let r=this.values_.length;if(e===void 0?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=arguments.length===1?r-e:t==null?0:Math.max(0,Math.min(t,r-e)),n===void 0&&(n=s),Kr(this)){let r=Jr(this,{object:this.proxy_,type:ni,index:e,removedCount:t,added:n});if(!r)return s;t=r.removedCount,n=r.added}n=n.length===0?n:n.map(e=>this.enhancer_(e,void 0));{let e=n.length-t;this.updateArrayLength_(r,e)}let i=this.spliceItemsIntoValues_(e,t,n);return(t!==0||n.length!==0)&&this.notifyArraySplice_(e,n,i),this.dehanceValues_(i)}spliceItemsIntoValues_(e,t,n){if(n.length<1e4)return this.values_.splice(e,t,...n);{let r=this.values_.slice(e,e+t),i=this.values_.slice(e+t);this.values_.length+=n.length-t;for(let t=0;t<n.length;t++)this.values_[e+t]=n[t];for(let t=0;t<i.length;t++)this.values_[e+n.length+t]=i[t];return r}}notifyArrayChildUpdate_(e,t,n){let r=!this.owned_&&bn(),i=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,type:ri,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(this,a),r&&wn()}notifyArraySplice_(e,t,n){let r=!this.owned_&&bn(),i=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,debugObjectName:this.atom_.name_,type:ni,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(this,a),r&&wn()}get_(e){return this.atom_.reportObserved(),this.dehanceValue_(this.values_[e])}set_(e,t){let n=this.values_;if(e<n.length){Ft(this.atom_);let r=n[e];if(Kr(this)){let n=Jr(this,{type:ri,object:this.proxy_,index:e,newValue:t});if(!n)return;t=n.newValue}t=this.enhancer_(t,r),t!==r&&(n[e]=t,this.notifyArrayChildUpdate_(e,t,r))}else{let r=Array.from({length:e+1-n.length});r[r.length-1]=t,this.spliceWithArray_(n.length,0,r)}}};function oi(e,t,n=`ObservableArray@`+u(),r=!1){return Fi(()=>{let i=new ai(n,t,r);y(i.values_,A,i);let a=new Proxy(i.values_,ii);return i.proxy_=a,e&&e.length&&i.spliceWithArray_(0,0,e),a})}var si={clear(){return this.splice(0)},replace(e){let t=this[A];return t.spliceWithArray_(0,t.values_.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[A];switch(arguments.length){case 0:return[];case 1:return r.spliceWithArray_(e);case 2:return r.spliceWithArray_(e,t)}return r.spliceWithArray_(e,t,n)},spliceWithArray(e,t,n){return this[A].spliceWithArray_(e,t,n)},push(...e){let t=this[A];return t.spliceWithArray_(t.values_.length,0,e),t.values_.length},pop(){return this.splice(Math.max(this[A].values_.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[A];return t.spliceWithArray_(0,0,e),t.values_.length},reverse(){return M.trackingDerivation&&n(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){M.trackingDerivation&&n(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[A],n=t.dehanceValues_(t.values_).indexOf(e);return n>-1?(this.splice(n,1),!0):!1}};ci(`at`,li),ci(`concat`,li),ci(`flat`,li),ci(`includes`,li),ci(`indexOf`,li),ci(`join`,li),ci(`lastIndexOf`,li),ci(`slice`,li),ci(`toString`,li),ci(`toLocaleString`,li),ci(`toSorted`,li),ci(`toSpliced`,li),ci(`with`,li),ci(`every`,ui),ci(`filter`,ui),ci(`find`,ui),ci(`findIndex`,ui),ci(`findLast`,ui),ci(`findLastIndex`,ui),ci(`flatMap`,ui),ci(`forEach`,ui),ci(`map`,ui),ci(`some`,ui),ci(`toReversed`,ui),ci(`reduce`,di),ci(`reduceRight`,di);function ci(e,t){typeof Array.prototype[e]==`function`&&(si[e]=t(e))}function li(e){return function(){let t=this[A];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_);return n[e].apply(n,arguments)}}function ui(e){return function(t,n){let r=this[A];return r.atom_.reportObserved(),r.dehanceValues_(r.values_)[e]((e,r)=>t.call(n,e,r,this))}}function di(e){return function(){let t=this[A];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_),r=arguments[0];return arguments[0]=(e,t,n)=>r(e,t,n,this),n[e].apply(n,arguments)}}let fi=b(`ObservableArrayAdministration`,ai);function pi(e){return h(e)&&fi(e[A])}let mi={},hi=`delete`;var gi=class{constructor(e,t=ue,n=`ObservableMap@`+u()){this.enhancer_=void 0,this.name_=void 0,this[A]=mi,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,Fi(()=>{this.keysAtom_=ae(`${this.name_}.keys()`),this.data_=new Map,this.hasMap_=new Map,e&&this.merge(e)})}has_(e){return this.data_.has(e)}has(e){if(!M.trackingDerivation)return this.has_(e);let t=this.hasMap_.get(e);if(!t){let n=t=new Dt(this.has_(e),fe,`${this.name_}.${E(e)}?`,!1);this.hasMap_.set(e,n),n.onBUOL=new Set([()=>this.hasMap_.delete(e)])}return t.get()}set(e,t){let n=this.has_(e);if(Kr(this)){let r=Jr(this,{type:n?ri:`add`,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.updateValue_(e,t):this.addValue_(e,t),this}delete(e){if(Ft(this.keysAtom_),Kr(this)&&!Jr(this,{type:hi,object:this,name:e}))return!1;if(this.has_(e)){let t=bn(),n=Yr(this),r=n||t?{observableKind:`map`,debugObjectName:this.name_,type:hi,object:this,oldValue:this.data_.get(e).value_,name:e}:null;return t&&Sn(r),zr(()=>{var t;this.keysAtom_.reportChanged(),(t=this.hasMap_.get(e))==null||t.setNewValue_(!1),this.data_.get(e).setNewValue_(void 0),this.data_.delete(e)}),n&&Zr(this,r),t&&wn(),!0}return!1}updateValue_(e,t){let n=this.data_.get(e);if(t=n.prepareNewValue_(t),t!==M.UNCHANGED){let r=bn(),i=Yr(this),a=i||r?{observableKind:`map`,debugObjectName:this.name_,type:ri,object:this,oldValue:n.value_,name:e,newValue:t}:null;r&&Sn(a),n.setNewValue_(t),i&&Zr(this,a),r&&wn()}}addValue_(e,t){Ft(this.keysAtom_),zr(()=>{var n;let r=new Dt(t,this.enhancer_,`${this.name_}.${E(e)}`,!1);this.data_.set(e,r),t=r.value_,(n=this.hasMap_.get(e))==null||n.setNewValue_(!0),this.keysAtom_.reportChanged()});let n=bn(),r=Yr(this),i=r||n?{observableKind:`map`,debugObjectName:this.name_,type:`add`,object:this,name:e,newValue:t}:null;n&&Sn(i),r&&Zr(this,i),n&&wn()}get(e){return this.has(e)?this.dehanceValue_(this.data_.get(e).get()):this.dehanceValue_(void 0)}getOrInsert(e,t){return this.has(e)||this.set(e,t),this.get(e)}getOrInsertComputed(e,t){return this.has(e)||this.set(e,t(e)),this.get(e)}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}keys(){return this.keysAtom_.reportObserved(),this.data_.keys()}values(){let e=this,t=this.keys();return vi({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:e.get(r)}}})}entries(){let e=this,t=this.keys();return vi({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:[r,e.get(r)]}}})}[Symbol.iterator](){return this.entries()}forEach(e,t){for(let[n,r]of this)e.call(t,r,n,this)}merge(e){return _i(e)&&(e=new Map(e)),zr(()=>{g(e)?w(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):x(e)?(S(e)||n(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&n(20,e)}),this}clear(){zr(()=>{Vt(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return zr(()=>{let t=yi(e),n=new Map,r=!1;for(let e of this.data_.keys())if(!t.has(e))if(this.delete(e))r=!0;else{let t=this.data_.get(e);n.set(e,t)}for(let[e,i]of t.entries()){let t=this.data_.has(e);if(this.set(e,i),this.data_.has(e)){let i=this.data_.get(e);n.set(e,i),t||(r=!0)}}if(!r)if(this.data_.size!==n.size)this.keysAtom_.reportChanged();else{let e=this.data_.keys(),t=n.keys(),r=e.next(),i=t.next();for(;!r.done;){if(r.value!==i.value){this.keysAtom_.reportChanged();break}r=e.next(),i=t.next()}}this.data_=n}),this}get size(){return this.keysAtom_.reportObserved(),this.data_.size}toString(){return`[object ObservableMap]`}toJSON(){return Array.from(this)}get[Symbol.toStringTag](){return`Map`}},_i=b(`ObservableMap`,gi);function vi(e){return e[Symbol.toStringTag]=`MapIterator`,Vi(e)}function yi(e){if(x(e)||_i(e))return e;if(Array.isArray(e))return new Map(e);if(g(e)){let t=new Map;for(let n in e)t.set(n,e[n]);return t}else return n(21,e)}let bi={};var xi=class{constructor(e,t=ue,n=`ObservableSet@`+u()){this.name_=void 0,this[A]=bi,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,this.enhancer_=(e,r)=>t(e,r,n),Fi(()=>{this.atom_=ae(this.name_),e&&this.replace(e)})}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){zr(()=>{Vt(()=>{for(let e of this.data_.values())this.delete(e)})})}forEach(e,t){for(let n of this)e.call(t,n,n,this)}get size(){return this.atom_.reportObserved(),this.data_.size}add(e){if(Ft(this.atom_),Kr(this)){let t=Jr(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){zr(()=>{e=this.enhancer_(e,void 0),this.data_.add(e),this.atom_.reportChanged()});let t=bn(),n=Yr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:`add`,object:this,newValue:e}:null;t&&Sn(r),n&&Zr(this,r),t&&wn()}return this}delete(e){if(Kr(this)&&!Jr(this,{type:hi,object:this,oldValue:e}))return!1;if(this.has(e)){let t=bn(),n=Yr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:hi,object:this,oldValue:e}:null;return t&&Sn(r),zr(()=>{this.atom_.reportChanged(),this.data_.delete(e)}),n&&Zr(this,r),t&&wn(),!0}return!1}has(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))}entries(){let e=this.values();return Ci({next(){let{value:t,done:n}=e.next();return n?{value:void 0,done:n}:{value:[t,t],done:n}}})}keys(){return this.values()}values(){this.atom_.reportObserved();let e=this,t=this.data_.values();return Ci({next(){let{value:n,done:r}=t.next();return r?{value:void 0,done:r}:{value:e.dehanceValue_(n),done:r}}})}intersection(e){return new Set(this).intersection(e)}union(e){return new Set(this).union(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}replace(e){return Si(e)&&(e=new Set(e)),Array.isArray(e)||C(e)?zr(()=>{let t=C(e)?e:new Set(e);if(t.size===0){this.clear();return}if(this.data_.size===0){t.forEach(e=>this.add(e));return}for(let e of this.data_.values())t.has(this.dehanceValue_(e))||this.delete(e);t.forEach(e=>this.add(e))}):e!=null&&n(41,e),this}toJSON(){return Array.from(this)}toString(){return`[object ObservableSet]`}[Symbol.iterator](){return this.values()}get[Symbol.toStringTag](){return`Set`}},Si=b(`ObservableSet`,xi);function Ci(e){return e[Symbol.toStringTag]=`SetIterator`,Vi(e)}let wi=Object.create(null),Ti=`remove`;var Ei=class{constructor(e,t=new Map,r,i=Ve){this.target_=void 0,this.values_=void 0,this.name_=void 0,this.defaultAnnotation_=void 0,this.keysAtom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.proxy_=void 0,this.isPlainObject_=void 0,this.appliedAnnotations_=void 0,this.pendingKeys_=void 0,this.lazyComputedKeys_=void 0,this.lazyObservableKeys_=void 0,this.target_=e,this.values_=t,this.name_=r,this.defaultAnnotation_=i,this.keysAtom_=new re(`${this.name_}.keys`),this.isPlainObject_=g(this.target_),Ui(this.defaultAnnotation_)||n(`defaultAnnotation must be valid annotation`),this.appliedAnnotations_={}}getObservablePropValue_(e){return(this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e)).get()}materializeLazyComputed_(e){let t=this.lazyComputedKeys_?.get(e);if(!t)return;this.lazyComputedKeys_.delete(e),this.lazyComputedKeys_.size===0&&(this.lazyComputedKeys_=void 0);let n=t();return this.values_.set(e,n),n}materializeLazyObservable_(e){let t=this.lazyObservableKeys_?.get(e);if(!t)return;this.lazyObservableKeys_.delete(e),this.lazyObservableKeys_.size===0&&(this.lazyObservableKeys_=void 0);let n=t();return this.values_.set(e,n),n}setObservablePropValue_(e,t){let n=this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e);if(n instanceof kt)return n.set(t),!0;if(Kr(this)){let n=Jr(this,{type:ri,object:this.proxy_||this.target_,name:e,newValue:t});if(!n)return null;t=n.newValue}if(t=n.prepareNewValue_(t),t!==M.UNCHANGED){let r=Yr(this),i=bn(),a=r||i?{type:ri,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,oldValue:n.value_,name:e,newValue:t}:null;i&&Sn(a),n.setNewValue_(t),r&&Zr(this,a),i&&wn()}return!0}get_(e){return M.trackingDerivation&&!D(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return D(this.target_,e)?this.values_.has(e)?this.setObservablePropValue_(e,t):n?Reflect.set(this.target_,e,t):(this.target_[e]=t,!0):this.extend_(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.defaultAnnotation_,n)}has_(e){if(!M.trackingDerivation)return e in this.target_;this.pendingKeys_||=new Map;let t=this.pendingKeys_.get(e);return t||(t=new Dt(e in this.target_,fe,`${this.name_}.${E(e)}?`,!1),this.pendingKeys_.set(e,t)),t.get()}extend_(e,t,n,r=!1){if(n===!0&&(n=this.defaultAnnotation_),n===!1)return this.defineProperty_(e,t,r);Mi(this,n,e);let i=n.extend_(this,e,t,r);return i&&ji(this,n,e),i}defineProperty_(e,t,n=!1){Ft(this.keysAtom_);try{an();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=Jr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t.value});if(!n)return null;let{newValue:i}=n;t.value!==i&&(t=r({},t,{value:i}))}if(n){if(!Reflect.defineProperty(this.target_,e,t))return!1}else a(this.target_,e,t);this.notifyPropertyAddition_(e,t.value)}finally{on()}return!0}defineObservableProperty_(e,t,n,r=!1){Ft(this.keysAtom_);try{an();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=Jr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let o=ki(e),s={configurable:M.safeDescriptors?this.isPlainObject_:!0,enumerable:!0,get:o.get,set:o.set};if(r){if(!Reflect.defineProperty(this.target_,e,s))return!1}else a(this.target_,e,s);let c=new Dt(t,n,`${this.name_}.${e.toString()}`,!1);this.values_.set(e,c),this.notifyPropertyAddition_(e,c.value_)}finally{on()}return!0}defineComputedProperty_(e,t,n=!1){Ft(this.keysAtom_);try{an();let r=this.delete_(e);if(!r)return r;if(Kr(this)&&!Jr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:void 0}))return null;t.name||=`${this.name_}.${e.toString()}`,t.context=this.proxy_||this.target_;let i=ki(e),o={configurable:M.safeDescriptors?this.isPlainObject_:!0,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.target_,e,o))return!1}else a(this.target_,e,o);this.values_.set(e,new kt(t)),this.notifyPropertyAddition_(e,void 0)}finally{on()}return!0}delete_(e,t=!1){if(Ft(this.keysAtom_),!D(this.target_,e))return!0;if(Kr(this)&&!Jr(this,{object:this.proxy_||this.target_,name:e,type:Ti}))return null;try{var n;an();let r=Yr(this),a=bn(),o=this.values_.get(e),s;if(!o&&(r||a)&&(s=i(this.target_,e)?.value),t){if(!Reflect.deleteProperty(this.target_,e))return!1}else delete this.target_[e];if(delete this.appliedAnnotations_[e],o&&(this.values_.delete(e),o instanceof Dt&&(s=o.value_),un(o)),this.keysAtom_.reportChanged(),(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(e in this.target_),r||a){let t={type:Ti,observableKind:`object`,object:this.proxy_||this.target_,debugObjectName:this.name_,oldValue:s,name:e};a&&Sn(t),r&&Zr(this,t),a&&wn()}}finally{on()}return!0}notifyPropertyAddition_(e,t){var n;let r=Yr(this),i=bn();if(r||i){let n=r||i?{type:`add`,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,name:e,newValue:t}:null;i&&Sn(n),r&&Zr(this,n),i&&wn()}(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(!0),this.keysAtom_.reportChanged()}ownKeys_(){return this.keysAtom_.reportObserved(),T(this.target_)}keys_(){return this.keysAtom_.reportObserved(),Object.keys(this.target_)}};function Di(e,t){if(t&&Ai(e)&&n(`Options can't be provided for already observable objects.`),D(e,A))return Ni(e)instanceof Ei||n(`Cannot convert '${Pi(e)}' into observable object:\nThe target is already observable of different type.\nExtending builtins is not supported.`),e;Object.isExtensible(e)||n(`Cannot make the designated object observable; it is not extensible`);let r=t?.name??`${g(e)?`ObservableObject`:e.constructor.name}@${u()}`;return v(e,A,new Ei(e,new Map,String(r),nt(t))),e}let Oi=b(`ObservableObjectAdministration`,Ei);function ki(e){return wi[e]||(wi[e]={get(){return this[A].getObservablePropValue_(e)},set(t){return this[A].setObservablePropValue_(e,t)}})}function Ai(e){return h(e)?Oi(e[A]):!1}function ji(e,t,n){e.appliedAnnotations_[n]=t}function Mi(e,t,r){if(Ui(t)||n(`Cannot annotate '${e.name_}.${r.toString()}': Invalid annotation.`),!ge(t)&&D(e.appliedAnnotations_,r)){let i=`${e.name_}.${r.toString()}`,a=e.appliedAnnotations_[r].annotationType_,o=t.annotationType_;n(`Cannot apply '${o}' to '${i}':\nThe field is already annotated with '${a}'.\nRe-annotating fields is not allowed.\nUse 'override' annotation for methods overridden by subclass.`)}}function P(e,t){if(typeof e==`object`&&e){if(pi(e))return t!==void 0&&n(23),e[A].atom_;if(Si(e))return e.atom_;if(_i(e)){if(t===void 0)return e.keysAtom_;let r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,Pi(e)),r}if(Ai(e)){if(!t)return n(26);let r=e[A],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,Pi(e)),i}if(ie(e)||At(e)||vn(e))return e}else if(p(e)&&vn(e[A]))return e[A];n(28)}function Ni(e,t){if(e||n(29),t!==void 0)return Ni(P(e,t));if(ie(e)||At(e)||vn(e)||_i(e)||Si(e))return e;if(e[A])return e[A];n(24,e)}function Pi(e,t){let n;if(t!==void 0)n=P(e,t);else if(zn(e))return e.name;else n=Ai(e)||_i(e)||Si(e)?Ni(e):P(e);return n.name_}function Fi(e){let t=Ht(),n=Tt(!0);an();try{return e()}finally{on(),Et(n),Ut(t)}}let Ii=o.toString;function Li(e,t,n=-1){return Ri(e,t,n)}function Ri(e,t,n,r,i){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!==e)return t!==t;let a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;let o=Ii.call(e);if(o!==Ii.call(t))return!1;switch(o){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++;break}e=zi(e),t=zi(t);let s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;let n=e.constructor,r=t.constructor;if(n!==r&&!(p(n)&&n instanceof n&&p(r)&&r instanceof r)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];let c=r.length;for(;c--;)if(r[c]===e)return i[c]===t;if(r.push(e),i.push(t),s){if(c=e.length,c!==t.length)return!1;for(;c--;)if(!Ri(e[c],t[c],n-1,r,i))return!1}else{let a=Object.keys(e),o=a.length;if(Object.keys(t).length!==o)return!1;for(let s=0;s<o;s++){let o=a[s];if(!(D(t,o)&&Ri(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function zi(e){return pi(e)?e.slice():x(e)||_i(e)||C(e)||Si(e)?Array.from(e.entries()):e}let Bi=globalThis.Iterator?.prototype||{};function Vi(e){return e[Symbol.iterator]=Hi,r(Object.create(Bi),e)}function Hi(){return this}function Ui(e){return e instanceof Object&&typeof e.annotationType_==`string`&&p(e.make_)&&p(e.extend_)}{let e=globalThis;[`Symbol`,`Map`,`Set`,`Proxy`].forEach(t=>{e[t]===void 0&&n(`MobX requires global '${t}' to be available or polyfilled`)})}typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Tn,extras:{getDebugName:Pi},$mobx:A}),e.$mobx=A,e.FlowCancellationError=rr,e.ObservableMap=gi,e.ObservableSet=xi,e.Reaction=pn,e._allowStateChanges=wt,e._allowStateChangesInsideComputed=Rn,e._allowStateReadsEnd=Wt,e._allowStateReadsStart=j,e._autoAction=Fn,e._autoActionBound=Ln,e._endAction=Ct,e._getAdministration=Ni,e._getGlobalState=Zt,e._interceptReads=pr,e._isComputingDerivation=Pt,e._resetGlobalState=Qt,e._startAction=St,e.action=Pn,e.actionBound=In,e.autorun=Bn,e.compareDefault=le,e.compareIdentity=oe,e.compareShallow=ce,e.compareStructural=se,e.computed=ht,e.computedStruct=mt,e.configure=Yn,e.createAtom=ae,e.defineProperty=Ar,e.entries=Tr,e.extendObservable=Xn,e.flow=cr,e.flowBound=lr,e.flowResult=dr,e.get=kr,e.getAtom=P,e.getDebugName=Pi,e.getDependencyTree=Zn,e.getObserverTree=$n,e.has=Or,e.intercept=mr,e.isAction=zn,e.isBoxedObservable=Ot,e.isComputed=vr,e.isComputedProp=yr,e.isFlow=fr,e.isFlowCancellationError=ir,e.isObservable=xr,e.isObservableArray=pi,e.isObservableMap=_i,e.isObservableObject=Ai,e.isObservableProp=Sr,e.isObservableSet=Si,e.keys=Cr,e.makeAutoObservable=ei,e.makeObservable=Qr,e.observable=ut,e.observableDeep=ct,e.observableRef=ot,e.observableShallow=st,e.observableStruct=lt,e.observe=Mr,e.onBecomeObserved=Gn,e.onBecomeUnobserved=Kn,e.onReactionError=mn,e.override=he,e.ownKeys=jr,e.reaction=Un,e.remove=Dr,e.runInAction=Rn,e.set=Er,e.spy=Tn,e.toJS=Rr,e.transaction=zr,e.untracked=Vt,e.values=wr,e.when=Br})),X=De(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=uw():t.exports=dw()}))();function fw(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(fw);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(fw)}default:return!1}}function pw(e){if(Array.isArray(e))return Object.freeze(e.map(pw));if(typeof e==`object`&&e){let t=Object.create(null),n=Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t));for(let[e,r]of n)t[e]=pw(r);return Object.freeze(t)}return e}function mw(e){let t=typeof e;if(t===`string`||t===`number`||t===`boolean`)return t;throw TypeError(`Variable values must be string|number|boolean (got ${t})`)}function hw(e){return typeof e==`string`?e:String(e)}function gw(e){if(typeof e==`number`)return e;if(typeof e==`boolean`)return+!!e;let t=e.trim();if(t===``)throw TypeError(`Cannot cast empty string to number`);let n=Number(t);if(!Number.isFinite(n))throw TypeError(`Cannot cast ${JSON.stringify(e)} to number`);return n}function _w(e){if(typeof e==`boolean`)return e;if(typeof e==`number`){if(e===0||e===1)return e===1;throw TypeError(`Cannot cast number ${e} to bool (only 0 and 1 are accepted)`)}if(e===`true`)return!0;if(e===`false`)return!1;throw TypeError(`Cannot cast ${JSON.stringify(e)} to bool (expected "true" or "false")`)}var vw=class extends Error{constructor(e,t){super(t),this.variable=e}};function yw(e){return e instanceof vw?e:e instanceof Error&&e.cause!==void 0?yw(e.cause):void 0}const bw=e=>Eo(e);var xw=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n,r){this.name=e,this.type=t,this.clock=r,bw(n)||jw(e,t,n,`initial value`),this.cell=X.observable.box(n,{deep:!1}),this.lastChangedAt=bw(n)?null:r.now()}read(){let e=this.cell.get();if(bw(e))throw new vw(this.name,`variable "${this.name}" has no value yet: nothing has written it`);return e}set(e){bw(e)||jw(this.name,this.type,e,`set value`),!(0,X.compareStructural)(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}stored(){return this.cell.get()}},Sw=class{cell;constructor(e,t,n){if(this.cell=(0,X.computed)(t,{keepAlive:!0,...n!==void 0&&{equals:n}}),typeof this.cell.suspend_!=`function`)throw TypeError(`${e}: this MobX's computed has no suspend_; release() cannot unsubscribe it`);if(typeof this.cell.keepAlive_!=`boolean`)throw TypeError(`${e}: this MobX's computed has no keepAlive_ flag; release() cannot lift it`)}read(){return this.cell.get()}release(){this.cell.keepAlive_=!1,this.cell.suspend_()}},Cw=class{constructor(e){this.deriver=e}read(){return this.deriver()}},ww=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new Sw(`Variable "${e}"`,()=>{let e=n();return jw(this.name,this.type,e,`computed result`),e})}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}},Tw=class{kind=`projection`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new Cw(()=>{let e=n();return jw(this.name,this.type,e,`projection result`),e})}read(){return this.cell.read()}lastUpdatedMs(){return null}},Ew=class{kind=`document`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.clock=n,this.cell=X.observable.box(Aw(t),{deep:!1}),this.lastChangedAt=t.kind===`pending`?null:n.now()}read(){return this.cell.get()}set(e){let t=Aw(e);kw(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}},Dw=class{kind=`document`;cell;constructor(e,t){this.name=e,this.cell=new Sw(`Variable "${e}"`,()=>Aw(t()),kw)}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}};function Ow(e){return JSON.stringify(e)}function kw(e,t){return Ow(e)===Ow(t)}function Aw(e){return e.kind===`ok`?{kind:`ok`,value:pw(e.value)}:e}function jw(e,t,n,r){let i=mw(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var Mw=class{constructor(e,t=null){this.clock=e,this.parent=t}nodes=X.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new xw(e,t,n,this.clock))}defineDocument(e,t){this.declare(e,new Ew(e,t,this.clock))}defineDerivedDocument(e,t){this.declare(e,new Dw(e,t))}defineComputed(e,t,n){this.defineDerived(e,t,`computed`,n)}defineDerived(e,t,n,r){let i=e=>this.read(e),a=n===`computed`?ww:Tw;this.declare(e,new a(e,t,()=>r(i)))}derive(e,t,n){if(this.refuseDisposed(`Derived value "${e}"`),t===`projection`)return new Cw(n);let r=new Sw(`Derived value "${e}"`,n);return this.kept.push(r),r}kept=[];read(e){return this.requireVar(e).read()}readDocument(e){let t=this.requireNode(e);if(t.kind!==`document`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a document`);return t.read()}stored(e){let t=this.requireNode(e);if(t.kind===`document`)return t.read();if(t.kind!==`box`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a written node`);return t.stored()}setDocument(e,t){let n=this.requireOwn(e);if(!(n instanceof Ew))throw TypeError(n.kind===`document`?`Variable "${e}" is a derived document: what it reads decides it, and nothing writes it`:`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,X.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireOwn(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,X.runInAction)(()=>n.set(t))}runInAction(e){(0,X.runInAction)(e)}has(e){return this.nodes.has(e)||(this.parent?.has(e)??!1)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`){let e=t.read();return e.kind===`pending`?e:F(Ow(e))}try{return F(String(t.read()))}catch(e){return yw(e)===void 0?F(` failed:${e instanceof Error?e.message:String(e)}`):So(`unread`)}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.parent?.names()??[],...this.nodes.keys()]}dispose(){if(this.disposed)return 0;this.disposed=!0;let e=0;return(0,X.runInAction)(()=>{for(let t of this.nodes.values())(t instanceof ww||t instanceof Dw)&&(t.release(),e++);for(let e of this.kept)e.release()}),e+this.kept.length}disposed=!1;requireNode(e){let t=this.nodes.get(e)??this.parent?.requireNode(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireOwn(e){let t=this.nodes.get(e);if(t!==void 0)return t;throw this.parent?.has(e)?Error(`Variable "${e}" lives in the directory's store; a session's view cannot write it`):ReferenceError(`Unknown variable "${e}"`)}requireVar(e){let t=this.requireNode(e);if(t.kind===`document`)throw TypeError(`Variable "${e}" is a document; read its fields by path (.${e}.<field>)`);return t}refuseDisposed(e){if(this.disposed)throw Error(`${e}: cannot declare on a disposed store`)}declare(e,t){if(this.refuseDisposed(`Variable "${e}"`),this.has(e))throw Error(`Variable "${e}" is already declared`);(0,X.runInAction)(()=>this.nodes.set(e,t))}},Nw=class extends Error{name=`TemplateError`;kind=`EvalError`;pos;source;constructor(e,t,n={}){super(e,{cause:n.cause}),this.pos=t,this.source=n.source}get sourceSnippet(){return this.source?Hw(this.source,this.pos):``}toString(){let e=`${this.name}: ${this.message}\n at line ${this.pos.line}, column ${this.pos.column}`,t=this.sourceSnippet;return t?`${e}\n\n${t}`:e}},Pw=class extends Nw{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},Fw=class extends Nw{name=`EvalError`;kind=`EvalError`},Iw=class extends Fw{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=Uw(e,n.available??[]),i=r.length===0?``:` (did you mean: ${r.join(`, `)}?)`;super(`function ${JSON.stringify(e)} is not registered${i}`,t,n),this.funcName=e,this.suggestions=r}},Lw=class extends Fw{name=`ArgCountError`;kind=`ArgCountError`;funcName;accepted;got;constructor(e,t,n,r,i={}){let a=t.minimum===t.maximum?`${t.minimum}`:`at least ${t.minimum}`;super(`wrong number of args for ${e}: want ${a} got ${n}`,r,i),this.funcName=e,this.accepted=t,this.got=n}},Rw=class extends Fw{name=`TypeMismatchError`;kind=`TypeMismatchError`;funcName;argIndex;expected;receivedSummary;constructor(e,t,n,r,i,a={}){super(`function ${JSON.stringify(e)} arg ${t}: expected ${n}, but a ${r} flowed in. Pass it through \`unstyled\` (or your engine's flatten function) to convert.`,i,a),this.funcName=e,this.argIndex=t,this.expected=n,this.receivedSummary=r}},zw=class extends Rw{constructor(e,t,n,r,i={}){super(e,t,`integer`,String(n),r,i),this.message=Number.isInteger(Number(n))?`integer out of range: ${String(n)}`:`expected integer; found ${String(n)}`}},Bw=class extends Fw{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},Vw=class extends Fw{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function Hw(e,t){let n=e.split(`
56
+ `)}},Gee=class extends Error{constructor(e){super(e.map(e=>e.message).join(`
57
+ `)),this.errors=e,this.name=`DroppedPlacements`}};function J(e,t){return Ab(e)(t)}function Ab(e){let t,n=()=>(t??={node:Kee(e)},t.node);return t=>qee(e,n,t)}function Kee(e){try{return Fa(e)}catch(e){if(e instanceof Pa)return;throw e}}function qee(e,t,n){let r=n.some(e=>/^\d+$/.test(e))?Jee(e,t(),n):void 0;if(r!==void 0)return r;let i=0,a;for(let t of n){if(t===``||/^\d+$/.test(t))continue;let n=Yee(e,i,t);if(n===-1)return a===void 0?void 0:jb(e,a);i=n,a=n}return a===void 0?void 0:jb(e,a)}function Jee(e,t,n){if(t===void 0)return;let r=t,i,a=!1;for(let e of n){let t=r.kind===`array`&&/^\d+$/.test(e),n=r.kind===`array`?t?r.elements[Number(e)]:void 0:Ia(r,e)?.value;if(n===void 0)break;a||=t,r=n,i=n}return i===void 0||!a?void 0:jb(e,i.span.start)}function Yee(e,t,n){let r=n.replace(/[\\^$.*+?()[\]{}|]/g,`\\$&`),i=RegExp(`(?:["']${r}["']|\\b${r}\\b)\\s*:`,`g`);i.lastIndex=t;let a=i.exec(e);return a?a.index:-1}function jb(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Xee(e,t){try{return Fa(t),null}catch(n){if(!(n instanceof Pa))throw n;return`${e}:${jb(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function Zee(e,t){if(t.length===0)return`${e}: invalid config (no details)`;let n=[`Invalid config in ${e} (${t.length} issue${t.length===1?``:`s`}):`];for(let e of t){let t=[];e.line!==void 0&&t.push(`line ${e.line}${e.col===void 0?``:`:${e.col}`}`),e.path&&t.push(e.path);let r=t.length>0?`[${t.join(` • `)}] `:``;n.push(` ${r}${e.message}`)}return n.join(`
58
+ `)}function Mb(e,t,n,r){let i=n[r];return typeof i==`string`?i:(e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${Ib(i)}`,line:J(e.source,[...t.split(`.`),r])}),null)}function Qee(e,t,n,r){let i=n.default;if(i!==void 0){if(!(r===`string`&&typeof i==`string`||r===`number`&&typeof i==`number`||r===`boolean`&&typeof i==`boolean`)){e.issues.push({path:`${t}.default`,message:`default must be a ${r}, got ${Ib(i)}`,line:J(e.source,[...t.split(`.`),`default`])});return}return i}}function Nb(e,t,n,r){let i=n[r];if(i!==void 0){if(typeof i!=`string`){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${Ib(i)}`,line:J(e.source,[...t.split(`.`),r])});return}return i}}function Pb(e,t,n){let r=Nb(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${py(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[...t.split(`.`),`palette`])});return}return r}}function Fb(e,t,n,r,i){let a=n[r];if(a!==void 0){if(typeof a!=`string`||!i.includes(a)){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be one of: ${i.join(`, `)}; got ${Y(a)}`,line:J(e.source,[...t.split(`.`),r])});return}return a}}function Ib(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Y(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function Lb(e,t,n,r){return Zy(r)?(Bb(e,n,r,t.noun,new Set(Object.keys(t.fields)),Rb(e,t.removed??{},n,r)),zb(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${Ib(r)}`,line:J(e.source,n.split(`.`))}),null)}function Rb(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)Vb(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function zb(e,t,n,r){let i=t,a={},o=!0;for(let[t,s]of Object.entries(i)){let i=s.parse(e,n,t,r);i===void 0?s.required&&(o=!1):a[t]=i}return o?a:null}const $ee=new Set;function Bb(e,t,n,r,i,a=$ee){for(let o of Object.keys(n))!i.has(o)&&!a.has(`${t}.${o}`)&&e.issues.push({path:`${t}.${o}`,message:`Unknown ${r} "${o}". Expected one of: ${[...i].join(`, `)}`,line:J(e.source,[...t.split(`.`),o])})}function Vb(e,t,n){return e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))}),null}function Hb(e,t,n,r){if(!Zy(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${Ib(r)}`,line:J(e.source,n.split(`.`))}),null;let i=t.arms,a=Object.keys(i),o=Object.keys(r).filter(e=>e in i),s=Object.keys(r).filter(e=>!(e in i));for(let r of s)e.issues.push({path:`${n}.${r}`,message:`Unknown ${t.noun} key "${r}". Expected exactly one of: ${a.join(`, `)}`,line:J(e.source,[...n.split(`.`),r])});if(o.length===0)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)}`,line:J(e.source,n.split(`.`))}),null;if(o.length>1)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)} (found: ${o.join(`, `)})`,line:J(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function ete(e,t,n,r){if(!Zy(r))return e.issues.push({path:n,message:`${n} must be an object, got ${Ib(r)}`,line:J(e.source,n.split(`.`))}),null;let i=r[t.tag];if(typeof i!=`string`)return e.issues.push({path:`${n}.${t.tag}`,message:`${n}.${t.tag} must be a string, got ${Ib(i)}`,line:J(e.source,n.split(`.`))}),null;let a=t.arms;if(!Object.hasOwn(a,i)){let o=Object.hasOwn(t.retired,i)?t.retired[i](r):`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`;return e.issues.push({path:`${n}.${t.tag}`,message:o,line:J(e.source,[...n.split(`.`),t.tag])}),null}let o=a[i],s=e.issues.length,c=o.parse(e,n,r),l=new Set(e.issues.slice(s).map(e=>e.path));return Bb(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function tte(e,t,n){return{json:ste(Xb(n),e,t),keys:new Set([e,...Object.keys(n)])}}function Ub(e){return(...t)=>e()(...t)}function nte(e,...t){return(n,r,i)=>{let a=e(n,r,i);if(a===null)return null;for(let e of t){if(e.ok(a))continue;let{field:t,message:i}=e.issue(a),o=t===``?r:`${r}.${t}`;return n.issues.push({path:o,message:i,line:J(n.source,o.split(`.`))}),null}return a}}function Wb(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Nb(e,t,r,n)}}function Gb(){return{required:!1,json:{type:`boolean`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`boolean`){e.issues.push({path:`${t}.${n}`,message:`${n} must be a boolean, got ${Ib(i)}`,line:J(e.source,[n])});return}return i}}}}function rte(e){let{min:t,max:n}=e;return{required:!1,json:{type:`integer`,minimum:t,maximum:n},parse:(e,r,i,a)=>{let o=a[i];if(o!==void 0){if(typeof o!=`number`||!Number.isInteger(o)||o<t||o>n){e.issues.push({path:`${r}.${i}`,message:`${i} must be an integer between ${t} and ${n}, got ${Y(o)}`,line:J(e.source,[i])});return}return o}}}}function Kb(e={}){let{min:t}=e;return{required:!1,json:{type:`number`,...t!==void 0&&{minimum:t}},parse:(e,n,r,i)=>{let a=i[r];if(a!==void 0){if(typeof a!=`number`||!Number.isFinite(a)||t!==void 0&&a<t){let i=t===void 0?`a finite number`:`a finite number >= ${t}`;e.issues.push({path:`${n}.${r}`,message:`${r} must be ${i}, got ${Y(a)}`,line:J(e.source,[r])});return}return a}}}}function ite(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Pb(e,t,r)}}function qb(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Mb(e,t,r,n)??void 0}}function Jb(e,t){return u(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function ate(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=Mb(e,t,r,n);if(i===null)return;let a=Jb(`${t}.${n}`,i);return a===null?i:Vb(e,`${t}.${n}`,a)??void 0}}}function Yb(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>Fb(t,n,i,r,e)}}function Xb(e,t={closed:!0}){let n=e,r={},i=[];for(let[e,t]of Object.entries(n))r[e]=t.json,t.required&&i.push(e);return{type:`object`,properties:r,...i.length>0&&{required:i},...t.closed&&{additionalProperties:!1}}}function ote(e){return Xb(e.fields)}function ste(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function cte(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function Zb(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const Qb=(e,t)=>Array.from({length:e*2},(e,n)=>({lit:n%2==0,seconds:t})),$b=[...Qb(3,1),...Qb(3,.25)],lte=$b.reduce((e,{seconds:t})=>e+t,0),ute={min:15,max:600,step:15},dte=(e,t)=>e+t,fte=e=>e-lte,ex=(e,t,{previews:n=[],shown:r=`true`}={})=>({label:e,place:t,previews:n,shown:r}),tx=(e,t,n={})=>({spec:Yb(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e,...n}}}),nx=e=>t=>e.includes(t)?`🧪 ${t}`:t,pte={spec:Gb(),domain:`bool`,parse:Yy},mte=e=>({spec:rte(e),domain:e,parse:t=>Xy(t,e)});function rx(e,t,n,r={}){return{kind:`session`,...tx(e,r.optionDomain,{library:r.library,labelOf:r.labelOf}),floor:t,control:n,themeDefault:r.themeDefault??!1}}function ix(e,t){return{kind:`session`,...pte,floor:e,control:t,themeDefault:!1}}function ax(e,t,n){return{kind:`session`,...mte(e),floor:t,control:n,themeDefault:!1}}function ox(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const sx=e=>({kind:`text`,spec:e}),hte={required:!1,json:{enum:[...By]},parse:(e,t,n,r)=>{if(r[n]===`auto`){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: "auto" is not supported — the render daemon runs detached, so terminal detection would read the daemon's environment, not your terminal's. Pick an explicit depth: ${By.join(`, `)}`,line:J(e.source,[...t.split(`.`),n])});return}return Fb(e,t,r,n,By)}},gte={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=Nb(e,t,r,n);return Sy(i)?i:Pb(e,t,r)}},_te={required:!1,json:{anyOf:[{enum:[...jy]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Sy(i)?i:Fb(e,t,r,n,jy)}},cx=/^[^\r\n]*\S[^\r\n]*$/u,lx=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),vte={required:!1,json:{type:`string`,pattern:cx.source,not:{pattern:lx.source}},parse:(e,t,n,r)=>{let i=Nb(e,t,r,n);if(i===void 0||cx.test(i)&&!lx.test(i))return i;e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: must be one line of visible text other than a close glyph ("✖", "✕") — the settings menu needs a glyph to click`,line:J(e.source,[...t.split(`.`),n])})}},yte=Object.fromEntries($c.map(e=>[Zc[e].switch.setting,ix(!1,ex(Zc[e].label,`toggles`))])),bte={claude:`Claude Code's status line`,tmux:`the tmux status line, while this pane is shown`},xte={groups:[{id:`renderer`,label:`draw the bar in`}],entry:e=>({group:`renderer`,description:bte[e]})},ux={palette:ox(`theme`,gte,{themes:`themes`},ex(`🎨 theme`,`door`)),preset:ox(`preset`,Wb(),{from:`presets`},ex(`▦ preset`,`door`,{previews:[`layout`,`presetDelete`]})),style:ox(`style`,Wb(),{from:`styles`},ex(`◐ style`,`gear`,{previews:[`palette`]}),{themeDefault:!0}),effect:ox(`effect`,_te,{from:jy},ex(`✨ effect`,`look`)),endcaps:rx(Ry,`powerline`,ex(`✦ endcaps`,`look`),{optionDomain:`endcaps`}),variation:rx(Uy,`accent`,ex(`🎼 variation`,`gear`,{previews:[`layout`]}),{optionDomain:`variations`,labelOf:nx(dv),themeDefault:!0}),shade:rx(Wy,`middle`,ex(`🔆 shade`,`gear`,{previews:[`layout`]}),{optionDomain:`shades`,labelOf:nx(ev),themeDefault:!0}),transitions:ix(!1,ex(`fade in/out`,`look`)),animationSpeed:rx(Ny,`1x`,ex(`speed`,`look`)),autoWrap:ix(!0,ex(`wrap`,`config`)),padding:ax({...Jy,step:1},1,ex(`padding`,`config`)),updateNotice:ix(!0,ex(`update notice`,`config`)),menuTimeout:ax(ute,120,ex(`menu timeout`,`config`)),renderer:rx(Yc,`claude`,ex(`renderer`,`config`,{shown:Xc}),{optionDomain:`renderers`,library:xte}),...yte,colorCompatibility:{kind:`config`,...tx(By,`colorCompatibilities`),spec:hte,floor:`truecolor`},default_empty_value:sx(Wb()),default_separator:sx(Wb()),menuGlyph:sx(vte)},dx=Object.entries(ux),fx=dx.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),Ste=dx.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),px=dx.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),mx=dx.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function hx(e){return ux[e]}const gx=e=>hx(e).floor;function _x(e){let t=ux[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const vx=e=>`${e}.effective`,yx=e=>{let t=ux[e];return t.kind===`selection`?t.sessionKey:e},bx=Object.fromEntries(Ste.map(e=>{let t=yx(e);return[t,{configKey:e,sessionKey:t,effectiveVar:vx(t),...ux[e].control}]})),xx=Object.keys(bx),Sx=Object.values(bx),Cx=fx.filter(e=>ux[e].kind===`config`).map(e=>({configKey:e,effectiveVar:vx(e)})),wx=new Set(Cx.map(e=>e.configKey)),Tx=new Map([...Sx,...Cx].map(e=>[e.configKey,e.effectiveVar])),Ex=new Map(Sx.map(e=>[e.sessionKey,e.effectiveVar]));function Dx(e){return Object.fromEntries(xx.map(t=>[t,e(t)]))}const Ox=new Map(xx.map(e=>[bx[e].sessionKey,e])),kx=new Map;function Ax(e){let t=Mx(e);if(t===null)throw Error(`Palette "${e}" did not resolve in the theme registry — allowed names and the registry are inconsistent`);return t}function jx(e,t){return e===`bar`?t:Ax(e)}function Mx(e){let t=kx.get(e);if(t!==void 0)return t;let n=Jd(e);return n===null?null:(kx.set(e,n),n)}function Nx(e,t){return Px(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>tf(e,t))}const Px=B_();function Fx(e){let t=Mx(e);return t===null?null:{kind:`decided`,name:e,value:t}}function Ix(e,t,n){let r=Fx(e);return r===null?(n(Ay(t,`palette`,`"${e}" names no installed theme${py(e)}`)),Rx()):r}function Lx(e,t,n){return Cy(e,t,n,Rx(),Fx)}function Rx(){return{kind:`decided`,name:my,value:Ax(my)}}const zx=/^[A-Za-z_][A-Za-z0-9_]*$/;function Bx(e){return`#${e+1}`}const Vx={rows:{}};function Hx(e){return`rows`in e}function Ux(e){return Object.fromEntries(e.map((e,t)=>[Bx(t),e]))}function Cte(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:Ux(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:Ux([n])}}function Wx(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function Gx(e){return Hx(e)?Wx(e):e}function*Kx(e,t){if(!Hx(e)){yield*lb(e,t);return}yield[Wx(e),t];for(let[n,r]of Object.entries(e.rows))yield*lb(r,`${t}.rows.${n}`)}function qx(e,t){return Hx(e)?{...t,...e,rows:{...t.rows,...e.rows}}:Cte(e)}function Jx(e,t){return t.reduce((e,t)=>{let n=t.id??t.seg,r=[...ob(Wx(e.root))].flatMap(e=>e.kind===`segment`?[e]:[]);if(r.some(e=>e.name===t.seg&&(t.id===void 0||nb(e)===t.id)))return e;let i=r.find(e=>nb(e)===n);if(i!==void 0)return Yx(e,t,`as "${n}", but placement "${n}" is already segment "${i.name}" — give the cell its own id`);let a={kind:`segment`,name:t.seg,...t.id!==void 0&&{id:t.id},insertedBy:t.by},o=Object.entries(e.root.rows).map(([e,n])=>[e,n,Xx(n,t.anchor,a,t.relation)]);return o.some(([,,e])=>e!==null)?{...e,root:{...e.root,rows:Object.fromEntries(o.map(([e,t,n])=>[e,n??t]))}}:Yx(e,t,`${t.relation} "${t.anchor}", but there is no placement "${t.anchor}"`)},{root:e,unplaced:[]})}function Yx(e,t,n){return{...e,unplaced:[...e.unplaced,{cell:t,reason:n}]}}function Xx(e,t,n,r){if(e.kind===`segment`&&nb(e)===t){let{when:t,...i}=e;return{kind:`container`,direction:`horizontal`,children:r===`before`?[n,i]:[i,n],...t!==void 0&&{when:t}}}return e.kind===`container`?Zx(e,t,n,r):Qx(e,t,n,r)}function Zx(e,t,n,r){let i=e.children.findIndex(e=>e.kind===`segment`&&nb(e)===t);if(i>=0){let t=r===`before`?i:i+1,{when:a}=e.children[i];return{...e,children:[...e.children.slice(0,t),{...n,...a!==void 0&&{when:a}},...e.children.slice(t)]}}for(let[i,a]of e.children.entries()){let o=a.kind===`container`?Zx(a,t,n,r):Qx(a,t,n,r);if(o!==null)return{...e,children:e.children.map((e,t)=>t===i?o:e)}}return null}function Qx(e,t,n,r){let i=!1,a=ab(e,e=>{let a=Zx(e,t,n,r);return i=a!==null,a??e});return i?a:null}function $x(e){if(!Hx(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const eS=`default`,tS={};function nS(e){return[...new Set([eS,...Object.keys(e)])]}function rS(e,t,n){return by(void 0,e,t,eS,n)}function iS(e,t){let n={[eS]:tS,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${eS}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function aS(e,t){let n=iS(e.presets,t).root??Vx;return{node:Wx(qx(n,e.root)),path:$x(n)?`presets.${t}.root`:`root`}}function oS(e,t,n){if(t.length===0)return{config:e,notices:[]};let r=Jx(e.root,t),i=Object.entries(e.presets).filter(([,e])=>$x(e.root??Vx)).map(([n,r])=>({name:n,preset:r,...Jx(qx(r.root??Vx,e.root),t)})),a=new Map,o=e=>({cell:t,reason:n})=>{let r=a.get(t)??new Map;r.set(n,[...r.get(n)??[],e]),a.set(t,r)};(n.root?r.unplaced:[]).forEach(o(`the root`));for(let{name:e,unplaced:t}of i.filter(({name:e})=>n.presets.has(e)))t.forEach(o(`preset "${e}"`));return{config:{...e,root:r.root,presets:{...e.presets,...Object.fromEntries(i.map(({name:e,preset:t,root:n})=>[e,{...t,root:Wx(n)}]))}},notices:[...a].flatMap(([e,t])=>[...t].map(([t,n])=>sS(e,`${t} (in ${n.join(`, `)})`)))}}function sS(e,t){return`${e.by.file}: ${e.by.entry} places "${e.seg}" ${t}`}function cS(e,t){return{...e.globals,...iS(e.presets,t).globals}}const lS=new Map;function uS(e,t,n={}){lS.set(e,{permanent:!0,resolve:t,...n})}uS(`themes`,()=>gy(),{paletteOf:e=>Ax(e)});const dS=`placementThemes`;uS(dS,_y,{paletteOf:(e,t)=>jx(e,t.palette)});for(let{name:e,members:t,library:n,labelOf:r}of mx)uS(e,()=>t,{library:n,labelOf:r});function wte(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>Nx(n.basePalette,e.styles[t])}],[`presets`,{members:nS(e.presets)}]])}function fS(e){return[...new Set([...lS.keys(),...e.keys()])]}function pS(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=lS.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf,library:r.library,labelOf:r.labelOf};throw Error(hS(e,t))}const mS=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function hS(e,t){let n=mS.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${fS(t).join(`, `)})`}const gS=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`slash`,`run`,`do`];function _S(e){return JSON.stringify([e.run,Object.entries(e.env),e.cwd,e.refreshes])}function*vS(e){let t=[];yS(e,(e,n)=>(t.push([n,e]),e)),yield*t}function yS(e,t){if(`copy`in e)return{...e,copy:t(e.copy,`copy`)};if(`open`in e)return{...e,open:t(e.open,`open`)};if(`preset`in e&&e.preset===`delete`)return{...e,name:t(e.name,`name`)};if(`run`in e){let n=e.run.map((e,n)=>t(e,`run.${n}`));return{...e,run:n,env:Object.fromEntries(Object.entries(e.env).map(([e,n])=>[e,t(n,`env.${e}`)]))}}return e}function bS(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}const xS=`groups.`,SS=`menus.`,CS=`menupages.`,wS=`edit.`,TS=`candybar.`,ES=[xS,SS,CS,wS,TS];function DS(e){return ES.some(t=>e.startsWith(t))}const OS=`${TS}menu`,kS=ha,AS={variable:OS,key:OS,member:kS},jS=`${TS}diagnostics`,MS=`${da}://`,NS=`dispatch`,PS=`set-state`,FS=`step-state`,IS=`copy-text`,LS=`open-in-vscode`,RS=`toolbar-toggle`,zS=`set-config`,BS=`step-config`,VS=`save`,HS=`save-preset`,US=`save-theme-default`,WS=`delete-preset`,GS=`reset-config`,KS=`apply-layout-op`,qS=`undo`,JS=`redo`,YS=`back`,XS=`rewind`,ZS=`apply-update`,QS=`doctor-run`,$S=`doctor-fix`,eC=`doctor-mark`,tC=`probe`,nC=[NS,tC];function Tte(e){return nC.includes(e)}const rC=`slash`,iC=`repo-config`,aC=`copy-diagnostic`,oC=`range`,sC=[...nC,oC],cC=(e,t)=>`step ${e} ${t.startsWith(`-`)?`down`:`up`} by ${t.replace(`-`,``)}`,lC=(e,t)=>e.startsWith(t)?e.slice(t.length):e;function Ete(e,t){if(e===jS)return`${t===`0`?`close`:`open`} diagnostics`;let n=`set ${e} to ${t}`;if(!DS(e))return n;let r=lC(lC(e,CS),SS);return e.startsWith(`menupages.`)?`turn ${r} to page ${Number(t)+1}`:t===`closed`?`close ${r}`:t===`open`?`open ${r}`:e.startsWith(`menus.`)?`open ${t}`:n}function Dte(e){let t=[...e];return t.length<=60?e:`${t.slice(0,28).join(``)}...${t.slice(-28).join(``)}`}const Ote={[PS]:([,...e])=>e.flatMap((t,n)=>n%2==0?[Ete(t,e[n+1])]:[]),[FS]:([,e,t])=>[cC(e,t)],[IS]:([,e])=>[`copy ${Dte(e)}`],[LS]:([,e])=>[`open ${e} in vs code`],[RS]:()=>[`toggle the toolbar`],[zS]:([,e,t])=>[`save ${e} as ${t}`],[BS]:([,e,t])=>[`save ${cC(e,t)}`],[VS]:()=>[`save settings`],[HS]:()=>[`save as a new preset`],[US]:()=>[`save this look for the theme`],[WS]:([,e])=>[`delete preset ${e}`],[GS]:([,...e])=>e.map(e=>`reset ${e}`),[KS]:([,e,t])=>[`edit ${t} in ${e}`],[qS]:()=>[`undo`],[JS]:()=>[`redo`],[YS]:()=>[`go back`],[XS]:()=>[`cancel edits`],[ZS]:()=>[`update cc-candybar`],[QS]:()=>[`run doctor`],[$S]:([,e])=>[`fix ${e}`],[eC]:([,e,t])=>[`mark ${e} ${t}`],[rC]:([,e])=>[`type ${e}`],run:([,e])=>[`run ${e}`],[iC]:([,e,t])=>[`mark config in ${e} ${t}`],[aC]:()=>[`copy diagnostic`]},kte=e=>encodeURIComponent(e).replaceAll(`%20`,`+`).replaceAll(`%2F`,`/`).replaceAll(`%3A`,`:`);function Ate(e){let t=e=>e.verb===`set-state`||e.verb===`step-state`,[n=`nothing`,...r]=[...e.filter(e=>!t(e)),...e.filter(t)].flatMap(e=>Ote[e.verb](e.args));return r.length>0?`${n} and ${r.length} more`:n}function uC(e){return e.map(encodeURIComponent).join(`/`)}function jte(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function dC(e,t,n=Ate(t)){let r=t.map(e=>`e=${encodeURIComponent(`${e.verb}/${uC(e.args)}`)}`);return fC(e,NS,[`does=${kte(n)}`,...r].join(`&`))}function Mte(e,t){return fC(e,tC,encodeURIComponent(t))}function fC(e,t,n){return`${MS}to/${e}/${t}/${n}`}function pC(e){return new r(e).getAll(`e`).map(_C)}const mC=new Set([PS,GS]);function hC(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&gC(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function gC(e,t){if(e.verb!==t.verb||!mC.has(e.verb))return;let[n,r]=[_C(e.value),_C(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function _C(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}function vC(e){if(!e.startsWith(MS))return{ok:!1,problem:`expected a ${MS} link, got: ${e}`};let t=e.slice(MS.length);if(!t.startsWith(`to/`))return{ok:!1,problem:`the link is in ${t.includes(`/`)?`the direct verb form ${MS}<verb>/…`:`the bare copy form ${MS}<value>`}, which names no renderer: ${e}`};let n=t.slice(3),r=n.indexOf(`/`);if(r===-1)return{ok:!1,problem:`the link names a renderer and no click: ${e}`};try{return bC(n.slice(r+1),We(n.slice(0,r)))}catch(e){return{ok:!1,problem:e.message}}}function yC(e){if(!pa(e))return null;let t=e.slice(MS.length).split(`%`)[0];if(!t.startsWith(`to/`))return`to/`.startsWith(t)?null:`in a grammar older than names, which names no renderer`;let[,,n,...r]=t.split(`/`);return n===void 0||r.length===0||sC.includes(n)?null:`naming the verb "${n}", which a link never names: a link names ${sC.join(`, `)}`}function bC(e,t){let n=e.indexOf(`/`);if(n===-1)return{ok:!1,problem:`the link carries no verb: ${e}`};let r=e.slice(0,n);try{return{ok:!0,to:t,verb:decodeURIComponent(r),value:e.slice(n+1)}}catch{return{ok:!1,problem:`the link's verb is malformed: ${r}`}}}const xC=[`plugins`,`repo`];function SC({scope:e,name:t}){return`${e}.${t}`}function CC(e){return t=>t===e||t.startsWith(`${e}.`)}const wC=`self`;function TC(e){return xC.find(t=>e===t||e.startsWith(`${t}.`))}function EC(e,t){let n=TC(e);if(n===void 0||n===e)return``;let r=xC.filter(e=>e!==n).map(t=>`${t}${e.slice(n.length)}`).find(t);return r===void 0?``:` ("${r}" is declared: a repository's own plugins are named under repo., installed ones under plugins., and a name in one is never looked up in the other)`}const DC=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*OC(e){let t=e.indexOf(`{{`);for(;t!==-1;){let n=``,r=t+2,i=[[0,r]];for(;r<e.length&&!e.startsWith(`}}`,r);){if(e.startsWith(`/*`,r)){let t=e.indexOf(`*/`,r+2);r=t===-1?e.length:t+2,i.push([n.length,r]);continue}let t=r,a=e[r];if(r+=1,a===`"`||a===`'`||a==="`"){for(;r<e.length&&e[r]!==a;)r+=e[r]===`\\`&&a!=="`"?2:1;r+=1}n+=e.slice(t,r)}if(r>=e.length)return;yield{text:n,at:e=>{let[t,n]=i[0];for(let[r,a]of i)r<=e&&([t,n]=[r,a]);return n+e-t}},t=e.indexOf(`{{`,r+2)}}const kC=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,AC=RegExp(`^(?:(\\$)(?:\\.(${kC}))?|\\.(${kC})?)(?=[\\s)]|$)`);function jC(e,t,n){let r=AC.exec(e.trimStart());if(r===null)return null;let[i,a]=r[1]===void 0?[t,r[3]]:[n,r[2]];return i===null?null:a===void 0?i:`${i}${a}.`}const MC=/^(\w+)\b\s*([\s\S]*)$/;function*NC(e,t){let n=[t];for(let r of OC(e)){let e=r.text.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=MC.exec(e)??[],o=n[n.length-1],s=n.length>1?n[n.length-2]:o;if(i===`end`){n.length>1&&n.pop();continue}if(i===`else`){yield{code:e,dot:s,block:r};let i=/^with\b([\s\S]*)$/.exec(a);n[n.length-1]=i===null?s:jC(i[1],s,t);continue}yield{code:e,dot:o,block:r},i===`if`&&n.push(o),i===`with`&&n.push(jC(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const PC=/(?<![.$])\btemplate\s+$/;function*FC(e,t,n){let r=0;for(let i of[...e.matchAll(DC)]){let a=i.index+i[0].length;PC.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:jC(e.slice(a),t,n),index:i.index}),r=a}}function*IC(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...NC(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...FC(s,c,i)]){let i=Object.hasOwn(t,e.name)?t[e.name]:void 0,a=`${e.name}\0${e.at??`\0`}`;i===void 0||o.has(e.name)||n.has(a)||(n.add(a),yield*r(i,e.at,e.name,new Set([...o,e.name])))}}}yield*r(e,``,null,new Set)}function LC(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const RC=new WeakMap;function zC(e,t){let n=RC.get(t);return n===void 0&&(n=LC(e=>[...IC(e,t)]),RC.set(t,n)),n(e)}const BC=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${kC})`,`g`);function*VC({code:e,dot:t,root:n}){let r=e.replace(DC,``);for(let e of[...r.matchAll(BC)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function HC(e,t){let n=new Map;for(let r of zC(e,t))for(let e of VC(r))n.has(e)||n.set(e,r.via);return n}const UC=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,WC={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*GC(e){let t=0,n=0,r=`action`;for(let i of[...e.matchAll(DC)]){let a=e.slice(t,i.index),o=UC.exec(a);o===null?a.trim()!==``&&(n=0):(n=WC[o[1]],r=o[1]===`action`?`action`:`options`),n>0&&(yield{name:i[0].slice(1,-1),site:r,index:i.index},n--),t=i.index+i[0].length}}function KC(e,t){let n=new Map;for(let{code:r,via:i}of zC(e,t))for(let{name:e,site:t}of GC(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}function qC(e,t){let n=new Map;for(let{code:r,via:i}of zC(e,t))for(let e of r.matchAll(DC)){let t=e[0].slice(1,-1),r=yC(t);if(r===null)continue;let a=`${t}\0${i??`\0`}`;n.has(a)||n.set(a,{literal:t,problem:r,via:i})}return[...n.values()]}const JC=e=>Object.keys(WC).filter(t=>WC[t]>=e).join(`|`),YC=RegExp(`(?<![\\w.$])(?:(?:${JC(1)})\\s+|(?:${JC(2)})\\s+""\\s+)(?=[^\\s"\`)|}])`);function XC(e,t){for(let{code:n}of zC(e,t))if(YC.test(n.replace(DC,`""`)))return!0;return!1}const ZC=/(?<![\w.$])[A-Za-z_]\w*/g;function QC(e,t){let n=new Set;for(let{code:r}of zC(e,t))for(let[e]of r.replace(DC,``).matchAll(ZC))n.add(e);return n}function $C(e,t){return new Set([...ew(e,t)].filter(e=>Object.hasOwn(t,e)))}function ew(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of zC(e,t))for(let{name:e}of FC(r,i,a))n.add(e);return n}const tw=e=>RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.${e}(?![A-Za-z0-9_])`,`g`);function nw(e,t,n){let r=tw(t),i=CC(t),a=[];for(let{dot:t,block:n}of NC(e,``)){let e=n.text.replace(DC,e=>` `.repeat(e.length));for(let i of e.matchAll(r))(i[1]===`$`?``:t)===``&&a.push(n.at(i.index+i[1].length+1));for(let{name:e,index:r}of[...FC(n.text,t,``),...GC(n.text)])i(e)&&a.push(n.at(r+1))}return[...new Set(a)].sort((e,t)=>t-e).reduce((e,r)=>e.slice(0,r)+n+e.slice(r+t.length),e)}function*rw(e){for(let[t,n]of Object.entries(e.variables))yield[t,n,[`variables`,t]];for(let[t,n]of Object.entries(e.segments))for(let[e,r]of Object.entries(n.vars??{}))yield[`${t}.${e}`,r,[`segments`,t,`vars`,e]]}function*iw(e){for(let[t,n]of rw(e))yield[t,n]}function aw(e,t){let n=e.split(`.`);for(let e=n.length;e>0;e--){let r=n.slice(0,e).join(`.`);if(t.has(r))return[r]}let r=`${e}.`;return[...t].filter(e=>e.startsWith(r))}function ow(e,t){return aw(e,t.names).some(n=>!e.startsWith(`${n}.`)||t.documents.has(n))}function sw(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),cw(r)&&n.add(e)};for(let[t,n]of iw(e))r(t,n);return{names:t,documents:n,helpers:e.helpers}}function cw(e){return e.kind===`dropped`||e.kind===`source`||(e.kind===`shell`||e.kind===`file`)&&db(e.parse)===`json`}var lw=De((e=>{function t(e,...t){throw Error(`[MobX] minified error nr: ${e}${t.length?` `+t.map(String).join(`,`):``}. See mobx.js.org/errors`)}function n(e){let t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function r(e){return typeof e==`function`}function i(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function a(e){return typeof e==`object`&&!!e}function o(e){if(!a(e))return!1;let t=Object.getPrototypeOf(e);if(t==null)return!0;let n=p(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===Bt}function s(e){let t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function c(e,t,n){It(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function l(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return a(e)&&!0===e[n]}}function u(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function d(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function f(e){return e===null?null:typeof e==`object`?``+e:e}function p(e,t){return Lt.hasOwnProperty.call(e,t)}function m(e,t){return!!(e&t)}function h(e,t,n){return n?e|=t:e&=~t,e}function g(e,t=Vt,n=Vt){let r=new Wt(e);return t!==Vt&&(r.onBOL=new Set([t])),n!==Vt&&(r.onBUOL=new Set([n])),r}function _(e,t){return kt(e,t)}function v(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||Qe(e)?e:Array.isArray(e)?sn.array(e,{name:n}):o(e)?sn.object(e,void 0,{name:n}):u(e)?sn.map(e,{name:n}):d(e)?sn.set(e,{name:n}):typeof e!=`function`||Ve(e)||Ye(e)?e:s(e)?Gn(e):Ln(n,e)}function y(e){return e}function b(e,t){return{t:e,i:t,o:x,u:S}}function x(e,t,n,r){var i;return(i=this.i)!=null&&i.bound?this.u(e,t,n,!1)===null?0:1:r===e.h?this.u(e,t,n,!1)===null?0:2:Ve(n.value)?1:(It(r,t,w(e,this,t,n,!1)),2)}function S(e,t,n,r){let i=w(e,this,t,n);return e.l(t,i,r)}function C(e,n,r){let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>{var t;return he(s.i?.name??a.toString(),e,(t=s.i?.autoAction)!=null&&t)};return i==`field`?function(e){var t;let n=e;return Ve(n)||(n=c(n)),(t=s.i)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n}:i==`method`?(Ve(n)||(n=c(n)),(l=s.i)!=null&&l.bound&&o(function(){let e=this,t=e[a].bind(e);t.isMobxAction=!0,e[a]=t}),n):void t(43,s.t,String(a),i);var l}function w(e,t,n,r,i=N.safeDescriptors){var a,o,s;let{value:c}=r;return(a=t.i)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:he(t.i?.name??n.toString(),c,(o=t.i?.autoAction)!=null&&o,(s=t.i)!=null&&s.bound?e.v??e.h:void 0),configurable:!i||e.p,enumerable:!1,writable:!i}}function T(e,t){return{t:e,i:t,o:E,u:ee}}function E(e,t,n,r){var i;return r===e.h?this.u(e,t,n,!1)===null?0:2:(i=this.i)!=null&&i.bound&&(!p(e.h,t)||!Ye(e.h[t]))&&this.u(e,t,n,!1)===null?0:Ye(n.value)?1:(It(r,t,te(e,0,0,n,!1,!1)),2)}function ee(e,t,n,r){let i=te(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function D(e,t,n){var r;let{name:i,addInitializer:a}=n;return Ye(t)||(t=Gn(t)),(r=e.i)!=null&&r.bound&&a(function(){let e=this,t=e[i].bind(e);t.isMobXFlow=!0,e[i]=t}),t}function te(e,t,n,r,i,a=N.safeDescriptors){let{value:o}=r;return Ye(o)||(o=Gn(o)),i&&(o=o.bind(e.v??e.h),o.isMobXFlow=!0),{value:o,configurable:!a||e.p,enumerable:!1,writable:!a}}function O(e,t){return{t:e,i:t,o:k,u:ne}}function k(e,t,n){return this.u(e,t,n,!1)===null?0:1}function ne(e,t,n,r){return e.m(t,Pt({},this.i,{get:n.get,set:n.set}),r)}function A(e,t,n){function r(e){let n=Pt({},i.i,{get:t,context:e});return n.name||=`ObservableObject.${a.toString()}`,new yn(n)}let i=e,{name:a,addInitializer:o}=n,s;return o(function(){let e=St(this)[j],n=this,i=e.j.get(a);i instanceof yn&&i.derivation!==t&&e.j.delete(a),(e.O??=new Map).set(a,()=>r(n))}),function(){let e=this[j],n=e.j.get(a);if(n instanceof yn&&n.derivation!==t){let e=s?.get(this);return e||(e=r(this),(s??=new WeakMap).set(this,e)),e.get()}return e._(a)}}function re(e,t){return{t:e,i:t,o:ie,u:ae}}function ie(e,t,n){return this.u(e,t,n,!1)===null?0:1}function ae(e,t,n,r){return e.S(t,n.value,this.i?.A??v,r)}function oe(e,t,n){function r(e,t){let n=St(e)[j];return(n.V??=new Map).set(o,()=>new _n(t,i.i?.A??v,`ObservableObject.${o.toString()}`,!1)),n}let i=e,{kind:a,name:o}=n;if(a===`accessor`)return{get(){return(this[j]??r(this,t.get.call(this)))._(o)},set(e){return(this[j]??r(this,e)).M(o,e)},init(e){return r(this,e),e}}}function se(e){return{t:Jt,i:e,o:ce,u:le}}function ce(e,t,n,r){var i,a,o;if(n.get)return dn.o(e,t,n,r);if(n.set){let i=Ve(n.set)?n.set:he(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!N.safeDescriptors||e.p,set:i})===null?0:2:(It(r,t,{configurable:!0,set:i}),2)}if(r!==e.h&&typeof n.value==`function`)return s(n.value)?((o=this.i)!=null&&o.autoBind?Kn:Gn).o(e,t,n,r):((a=this.i)!=null&&a.autoBind?zn:Ln).o(e,t,n,r);let c=!1===this.i?.deep?nn:sn;return typeof n.value==`function`&&(i=this.i)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),c.o(e,t,n,r)}function le(e,t,n,r){var i;return n.get?dn.u(e,t,n,r):n.set?e.l(t,{configurable:!N.safeDescriptors||e.p,set:he(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.i)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),(!1===this.i?.deep?nn:sn).u(e,t,n,r))}function ue(e,t){return Pt(function(n,r){if(r&&typeof r.kind==`string`)return t(e,n,r)},e)}function de(e){return e||Xt}function fe(e){return ue(e,oe)}function pe(e){return!0===e.deep?v:!1===e.deep?y:(t=e.defaultDecorator)&&(n=(r=t.i)?.A)!=null?n:v;var t,n,r}function me(e){return ue(e,A)}function he(e,t,n=!1,r){function i(){return ge(0,n,t,r||this,arguments)}return i.isMobxAction=!0,i.toString=()=>t.toString(),hn&&(gn.value=e,It(i,`name`,gn)),i}function ge(e,t,n,r,i){let a=_e(0,t);try{return n.apply(r,i)}catch(e){throw a.N=e,e}finally{ve(a)}}function _e(e,t){let n=N.trackingDerivation,r=!t||!n;je();let i=N.allowStateChanges;r&&Te();let a={R:r,k:n,C:i,I:N.allowStateReads,P:!1,T:0,B:mn++,D:pn};return pn=a.B,a}function ve(e){pn!==e.B&&t(30),pn=e.D,e.N!==void 0&&(N.suppressReactionErrors=!0),Me(),e.R&&Ee(e.k),N.suppressReactionErrors=!1}function ye(e,t){let n=function(e){let t=N.allowStateChanges;return N.allowStateChanges=e,t}(e);try{return t()}finally{(function(e){N.allowStateChanges=e})(n)}}function be(e){return e instanceof xn}function xe(e){switch(e.K){case 0:return!1;case-1:case 2:return!0;case 1:{let t=Te(),n=e.L,r=n.length;for(let i=0;i<r;i++){let r=n[i];if(bn(r)){if(N.disableErrorBoundaries)r.get();else try{r.get()}catch{return Ee(t),!0}if(e.K===2)return Ee(t),!0}}return De(e),Ee(t),!1}}}function Se(e,t,n){De(e),e.$=Array(e.U===0?100:e.L.length),e.W=0,e.U=++N.runId;let r=N.trackingDerivation,i;if(N.trackingDerivation=e,N.inBatch++,!0===N.disableErrorBoundaries)i=t.call(n);else try{i=t.call(n)}catch(e){i=new xn(e)}return N.inBatch--,N.trackingDerivation=r,function(e){let t=e.L,n=e.L=e.$,r=0,i=0,a=e.W;for(let e=0;e<a;e++){let t=n[e];t.diffValue===0&&(t.diffValue=1,i!==e&&(n[i]=t),i++),t.K>r&&(r=t.K)}for(n.length=i,e.$=null,a=t.length;a--;){let n=t[a];n.diffValue===0&&ke(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,Oe(t,e))}r!==0&&(e.K=r,e.q())}(e),i}function Ce(e){let t=e.L;e.L=[];let n=t.length;for(;n--;)ke(t[n],e);e.K=-1}function we(e){let t=Te();try{return e()}finally{Ee(t)}}function Te(){let e=N.trackingDerivation;return N.trackingDerivation=null,e}function Ee(e){N.trackingDerivation=e}function De(e){if(e.K===0)return;e.K=0;let t=e.L,n=t.length;for(;n--;)t[n].F=0}function Oe(e,t){(e.H??=new Set).add(t),e.F>t.K&&(e.F=t.K)}function ke(e,t){let n=e.H;n&&(n.delete(t),n.size===0&&Ae(e))}function Ae(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,N.pendingUnobservations.push(e))}function je(){N.inBatch++}function Me(){--N.inBatch===0&&(Ie(),!N.isRunningUnobservations&&N.pendingUnobservations.length>0&&function(){N.isRunningUnobservations=!0;try{let e=N.pendingUnobservations;for(let t=0;t<e.length;t++){let n=e[t];n.isPendingUnobservation=!1,n.H&&n.H.size!==0||(n.H=null,n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof yn&&n.G())}N.pendingUnobservations=[]}finally{N.isRunningUnobservations=!1}}())}function Ne(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.L)==null||t.forEach(Ne))}function Pe(e){let t=N.trackingDerivation;return t===null?((!e.H||e.H.size===0)&&N.inBatch>0&&Ae(e),!1):(t.U!==e.J&&(e.J=t.U,t.$[t.W++]=e,!e.isBeingObserved&&N.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function Fe(e){var t;e.F!==2&&(e.F=2,(t=e.H)==null||t.forEach(e=>{e.K===0&&e.q(),e.K=2}))}function Ie(){N.inBatch>0||N.isRunningReactions||On(Le)}function Le(){N.isRunningReactions=!0;let e=N.pendingReactions,t=0;for(;e.length>0;){++t===Dn&&(console.error(`[mobx] cycle in reaction: ${e[0]}`),e.splice(0));let n=e.splice(0);for(let e=0,t=n.length;e<t;e++)n[e].X()}N.isRunningReactions=!1}function Re(e){return ue(e,C)}function ze(e){return function(t,n){return n&&typeof n.kind==`string`?C(e?Pn:Mn,t,n):r(t)?he(t.name||`<unnamed action>`,t,e):r(n)?he(t,n,e):i(t)?Re(b(e?jn:An,{name:t,autoAction:e})):void 0}}function Be(e){return ge(0,!1,e,this,void 0)}function Ve(e){return r(e)&&!0===e.isMobxAction}function He(e,t=zt){function n(){e(a)}var r;let i=t?.name??`Autorun`,a;if(t.scheduler||t.delay){let e=Ue(t),r=!1;a=new En(i,()=>{r||(r=!0,e(()=>{r=!1,a.isDisposed||a.track(n)}))},t.onError,t.requiresObservable)}else a=new En(i,function(){this.track(n)},t.onError,t.requiresObservable);return t!=null&&(r=t.signal)!=null&&r.aborted||a.Y(),a.Z(t?.signal)}function Ue(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Bn}function We(e,t,n,i){let a=typeof i==`function`?Tt(t,n):Tt(t),o=r(i)?i:n,s=`${e}L`;return a[s]?a[s].add(o):a[s]=new Set([o]),function(){let e=a[s];e&&(e.delete(o),e.size===0&&delete a[s])}}function Ge(e,t,n,r){let i=Ut(t);return Ot(()=>{let t=St(e,r)[j];Ht(i).forEach(e=>{t.u(e,i[e],!n||!(e in n)||n[e])})}),e}function Ke(e){let t={name:e.tt};var n;return e.L&&e.L.length>0&&(t.dependencies=(n=e.L,Array.from(new Set(n))).map(Ke)),t}function qe(e){let t={name:e.tt};return function(e){return!!e.H&&e.H.size>0}(e)&&(t.observers=Array.from(function(e){return e.H??new Set}(e),qe)),t}function Je(e){r(e.cancel)&&e.cancel()}function Ye(e){return!0===e?.isMobXFlow}function Xe(e,t){var n;if(t===void 0)return bn(e);if(!1===wt(e))return!1;let r=e[j];return(n=r.O)!=null&&n.has(t)?!0:r.j.has(t)?bn(Tt(e,t)):!1}function Ze(e,t){if(!e)return!1;if(t!==void 0){if(wt(e)){var n,r;let i=e[j];return i.j.has(t)||!((n=i.O)==null||!n.has(t))||!((r=i.V)==null||!r.has(t))}return!1}return wt(e)||!!e[j]||Gt(e)||kn(e)||bn(e)}function Qe(e){return Ze(e)}function $e(e){return wt(e)?e[j].nt():ir(e)||sr(e)?Array.from(e.keys()):yt(e)?e.map((e,t)=>t):void t(5)}function et(e,n){return wt(e)?e[j].et(n):ir(e)||sr(e)?e.has(n):yt(e)?n>=0&&n<e.length:void t(10)}function tt(e){if(wt(e))return e[j].it();t(38)}function nt(e,t,n){if(bn(e)){let r,i=!0;return He(()=>{let a=e.get();if(!i||n){let n=Te();t({observableKind:`computed`,debugObjectName:e.tt,type:Xn,object:e,newValue:a,oldValue:r}),Ee(n)}i=!1,r=a})}return n&&t({observableKind:`value`,debugObjectName:e.tt,object:e,type:Xn,newValue:e.rt,oldValue:void 0}),ft(e,t)}function rt(e,t,n){return e.set(t,n),n}function it(e,t){if(typeof e!=`object`||!e||e instanceof Date||!Qe(e))return e;if(vn(e)||bn(e))return it(e.get(),t);if(t.has(e))return t.get(e);if(yt(e)){let n=rt(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=it(e,t)}),n}if(sr(e)){let n=rt(t,e,new Set);return e.forEach(e=>{n.add(it(e,t))}),n}if(ir(e)){let n=rt(t,e,new Map);return e.forEach((e,r)=>{n.set(r,it(e,t))}),n}{let n=rt(t,e,{});return tt(e).forEach(r=>{Lt.propertyIsEnumerable.call(e,r)&&(n[r]=it(e[r],t))}),n}}function at(e,t){je();try{return e.apply(t)}finally{Me()}}function ot(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[j].isDisposed){if(a(),!n.onError)throw e;n.onError(e)}},n.timeout)}n.name=`When`;let i=he(`When-effect`,t);var a=He(t=>{ye(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function st(e){return e[j]}function ct(e){return e.st!==void 0&&e.st.length>0}function lt(e,t){let r=e.st;return r?r.push(t):r=e.st=[t],n(()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)})}function ut(e,n){let r=Te();try{let r=[...e.st||[]];for(let e=0,i=r.length;e<i&&((n=r[e](n))&&!n.type&&t(14),n);e++);return n}finally{Ee(r)}}function dt(e){return e.ot!==void 0&&e.ot.length>0}function ft(e,t){let r=e.ot;return r?r.push(t):r=e.ot=[t],n(()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)})}function pt(e,t){let n=Te(),r=e.ot;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Ee(n)}}function mt(e,n,r){if(!0===r&&(r=e.ut),!1===r)return;n in e.h||t(1,r.t,`${e.tt}.${n.toString()}`);let i=e.h;for(;i&&i!==Lt;){let t=Ft(i,n);if(t){let a=r.o(e,n,t,i);if(a===0)return;if(a===1)break}i=Object.getPrototypeOf(i)}}function ht(e,t){typeof Array.prototype[e]==`function`&&($n[e]=t(e))}function gt(e){return function(){let t=this[j];t.ct.reportObserved();let n=t.ht(t.j);return n[e].apply(n,arguments)}}function _t(e){return function(t,n){let r=this[j];return r.ct.reportObserved(),r.ht(r.j)[e]((e,r)=>t.call(n,e,r,this))}}function vt(e){return function(){let t=this[j];t.ct.reportObserved();let n=t.ht(t.j),r=arguments[0];return arguments[0]=(e,t,n)=>r(e,t,n,this),n[e].apply(n,arguments)}}function yt(e){return a(e)&&er(e[j])}function bt(e){return e[Symbol.toStringTag]=`MapIterator`,Mt(e)}function xt(e){return e[Symbol.toStringTag]=`SetIterator`,Mt(e)}function St(e,t){if(p(e,j))return e;let n=t?.name??`ObservableObject`;return c(e,j,new ur(e,new Map,String(n),function(e){return e?e.defaultDecorator??function(e){let t=!1!==e.deep,n=!!e.autoBind,r=!t|(n?2:0);return M[r]??(M[r]=se({deep:t,autoBind:n}))}(e):void 0}(t))),e}function Ct(e){return cr[e]||(cr[e]={get(){return this[j]._(e)},set(t){return this[j].M(e,t)}})}function wt(e){return!!a(e)&&dr(e[j])}function Tt(e,n){if(typeof e==`object`&&e){if(yt(e))return n!==void 0&&t(23),e[j].ct;if(sr(e))return e.ct;if(ir(e)){if(n===void 0)return e.lt;let r=e.ft.get(n)||e.dt.get(n);return r||t(25,n,Dt(e)),r}if(wt(e)){if(!n)return t(26);let r=e[j],i=r.j.get(n)??r.vt(n)??r.bt(n);return i||t(27,n,Dt(e)),i}if(Gt(e)||bn(e)||kn(e))return e}else if(r(e)&&kn(e[j]))return e[j];t(28)}function Et(e,n){return e||t(29),n===void 0?Gt(e)||bn(e)||kn(e)||ir(e)||sr(e)?e:e[j]?e[j]:void t(24,e):Et(Tt(e,n))}function Dt(e,t){let n;if(t!==void 0)n=Tt(e,t);else{if(Ve(e))return e.name;n=wt(e)||ir(e)||sr(e)?Et(e):Tt(e)}return n.tt}function Ot(e){let t=Te();je();try{return e()}finally{Me(),Ee(t)}}function kt(e,t,n=-1){return At(e,t,n)}function At(e,t,n,i,a){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!=e)return t!=t;let o=typeof e;if(o!==`function`&&o!==`object`&&typeof t!=`object`)return!1;let s=fr.call(e);if(s!==fr.call(t))return!1;switch(s){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++}e=jt(e),t=jt(t);let c=s===`[object Array]`;if(!c){if(typeof e!=`object`||typeof t!=`object`)return!1;let n=e.constructor,i=t.constructor;if(n!==i&&!(r(n)&&n instanceof n&&r(i)&&i instanceof i)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),a||=[];let l=(i||=[]).length;for(;l--;)if(i[l]===e)return a[l]===t;if(i.push(e),a.push(t),c){if(l=e.length,l!==t.length)return!1;for(;l--;)if(!At(e[l],t[l],n-1,i,a))return!1}else{let r=Object.keys(e),o=r.length;if(Object.keys(t).length!==o)return!1;for(let s=0;s<o;s++){let o=r[s];if(!p(t,o)||!At(e[o],t[o],n-1,i,a))return!1}}return i.pop(),a.pop(),!0}function jt(e){return yt(e)?e.slice():u(e)||ir(e)||d(e)||sr(e)?Array.from(e.entries()):e}function Mt(e){return e[Symbol.iterator]=Nt,Pt(Object.create(pr),e)}function Nt(){return this}Object.defineProperty(e,`__esModule`,{value:!0});let Pt=Object.assign,Ft=Object.getOwnPropertyDescriptor,It=Object.defineProperty,Lt=Object.prototype,Rt=[];Object.freeze(Rt);let zt={};Object.freeze(zt);let Bt=Object.toString(),Vt=()=>{},Ht=Reflect.ownKeys,Ut=Object.getOwnPropertyDescriptors,j=Symbol(`mobx administration`);var Wt=class{constructor(e=`Atom`){this.tt=void 0,this.yt=0,this.H=null,this.J=0,this.F=-1,this.onBOL=void 0,this.onBUOL=void 0,this.tt=e}get isBeingObserved(){return m(this.yt,1)}set isBeingObserved(e){this.yt=h(this.yt,1,e)}get isPendingUnobservation(){return m(this.yt,2)}set isPendingUnobservation(e){this.yt=h(this.yt,2,e)}get diffValue(){return+!!m(this.yt,4)}set diffValue(e){this.yt=h(this.yt,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return Pe(this)}reportChanged(){je(),Fe(this),Me()}toString(){return this.tt}};let Gt=l(`Atom`,Wt),Kt=Object.is,qt={t:`override`,o:function(){return 0},u:function(){t(44,this.t)}},Jt=`true`,Yt=se(),M=[Yt],Xt={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Xt);let Zt=re(`observable`),Qt=re(`observable.ref`,{A:y}),$t=re(`observable.shallow`,{A:function(e,t,n){return e==null||wt(e)||yt(e)||ir(e)||sr(e)?e:Array.isArray(e)?sn.array(e,{name:n,deep:!1}):o(e)?sn.object(e,void 0,{name:n,deep:!1}):u(e)?sn.map(e,{name:n,deep:!1}):d(e)?sn.set(e,{name:n,deep:!1}):void 0}}),en=re(`observable.struct`,{A:function(e,t){return kt(e,t)?t:e}}),tn={box(e,t){let n=de(t);return new _n(e,pe(n),n.name,!0,n.equals)},array(e,t){let n=de(t);return function(e,t,n=`ObservableArray`,r=!1){return Ot(()=>{let i=new Qn(n,t,r);It(i.j,j,{enumerable:!1,writable:!1,configurable:!0,value:i});let a=new Proxy(i.j,Zn);return i.v=a,e&&e.length&&i.wt(0,0,e),a})}(e,pe(n),n.name)},map(e,t){let n=de(t);return new rr(e,pe(n),n.name)},set(e,t){let n=de(t);return new or(e,pe(n),n.name)},object:(e,t,n)=>Ot(()=>Ge(function(e,t){var n;return(n=(e=St(e,t))[j]).v??(n.v=new Proxy(e,qn))}({},n),e,t))},nn=fe(Qt),rn=fe($t),an=fe(Zt),on=fe(en);var sn=Pt(function(e,t,n){return t&&typeof t.kind==`string`?oe(Zt,e,t):Qe(e)?e:o(e)?sn.object(e,t,n):Array.isArray(e)?sn.array(e,t):u(e)?sn.map(e,t):d(e)?sn.set(e,t):typeof e==`object`&&e?e:sn.box(e,t)},Zt,tn);let cn=`computed`,ln=O(cn),un=me(O(`computed.struct`,{equals:_})),dn=function(e,t){if(t&&typeof t.kind==`string`)return A(ln,e,t);if(o(e))return me(O(cn,e));let n=o(t)?t:{};return n.get=e,n.name||=e.name||``,new yn(n)};var fn;Pt(dn,ln);let pn=0,mn=1,hn=(fn=Ft(()=>{},`name`)?.configurable)!=null&&fn,gn={value:`action`,configurable:!0,writable:!1,enumerable:!1};var _n=class extends Wt{constructor(e,t,n=`ObservableValue`,r=!0,i=Kt){super(n),this.A=void 0,this.tt=void 0,this.xt=void 0,this.gt=!1,this.st=void 0,this.ot=void 0,this.rt=void 0,this.dehancer=void 0,this.A=t,this.tt=n,this.xt=i,this.rt=t(e,void 0,n)}dehanceValue(e){return this.dehancer===void 0?e:this.dehancer(e)}set(e){(e=this.jt(e))!==N.UNCHANGED&&this.Ot(e)}jt(e){if(ct(this)){let t=ut(this,{object:this,type:Xn,newValue:e});if(!t)return N.UNCHANGED;e=t.newValue}return e=this.A(e,this.rt,this.tt),this.xt(this.rt,e)?N.UNCHANGED:e}Ot(e){let t=this.rt;this.rt=e,this.reportChanged(),dt(this)&&pt(this,{type:Xn,object:this,newValue:e,oldValue:t})}get(){return this.reportObserved(),this.dehanceValue(this.rt)}raw(){return this.rt}toJSON(){return this.get()}toString(){return`${this.tt}[${this.rt}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let vn=l(`ObservableValue`,_n);var yn=class{constructor(e){this.K=-1,this.L=[],this.$=null,this.H=null,this.U=0,this.J=0,this.F=0,this.W=0,this.rt=new xn(null),this.tt=void 0,this._t=void 0,this.yt=0,this.derivation=void 0,this.St=void 0,this.At=void 0,this.xt=void 0,this.Vt=void 0,this.Mt=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||t(31),this.derivation=e.get,this.tt=e.name||`ComputedValue`,e.set&&(this.St=he(`ComputedValue-setter`,e.set)),this.xt=e.equals||Kt,this.At=e.context,this.Vt=e.requiresReaction,this.Mt=!!e.keepAlive}q(){(function(e){var t;e.F===0&&(e.F=1,(t=e.H)==null||t.forEach(e=>{e.K===0&&(e.K=1,e.q())}))})(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return m(this.yt,1)}set isComputing(e){this.yt=h(this.yt,1,e)}get isRunningSetter(){return m(this.yt,2)}set isRunningSetter(e){this.yt=h(this.yt,2,e)}get isBeingObserved(){return m(this.yt,4)}set isBeingObserved(e){this.yt=h(this.yt,4,e)}get isPendingUnobservation(){return m(this.yt,8)}set isPendingUnobservation(e){this.yt=h(this.yt,8,e)}get diffValue(){return+!!m(this.yt,16)}set diffValue(e){this.yt=h(this.yt,16,e===1)}get(){if(this.isComputing&&t(32,this.tt,this.derivation),N.inBatch!==0||this.H&&this.H.size!==0||this.Mt){let e=this.isBeingObserved;if(Pe(this),xe(this)){let e=N.trackingContext;e||!this.Mt&&!this.isBeingObserved||(N.trackingContext=this),this.trackAndCompute()&&function(e){var t;e.F!==2&&(e.F=2,(t=e.H)==null||t.forEach(t=>{t.K===1?t.K=2:t.K===0&&(e.F=0)}))}(this),N.trackingContext=e}else !e&&this.isBeingObserved&&this.L.forEach(Ne)}else xe(this)&&(this.Nt(),je(),this.rt=this.Rt(!1),Me());let e=this.rt;if(be(e))throw e.cause;return e}set(e){if(this.St){this.isRunningSetter&&t(33,this.tt),this.isRunningSetter=!0;try{this.St.call(this.At,e)}finally{this.isRunningSetter=!1}}else t(34,this.tt)}trackAndCompute(){let e=this.rt,t=this.K===-1,n=this.Rt(!0),r=t||be(e)||be(n)||!this.xt(e,n);return r&&(this.rt=n),r}Rt(e){let t;if(this.isComputing=!0,e)t=Se(this,this.derivation,this.At);else if(!0===N.disableErrorBoundaries)t=this.derivation.call(this.At);else try{t=this.derivation.call(this.At)}catch(e){t=new xn(e)}return this.isComputing=!1,t}G(){this.Mt||(Ce(this),this.rt=void 0)}Nt(){}toString(){return`${this.tt}[${this.derivation.toString()}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let bn=l(`ComputedValue`,yn);var xn=class{constructor(e){this.cause=void 0,this.cause=e}};let Sn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Cn=class{constructor(){this.version=7,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.isRunningUnobservations=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.safeDescriptors=!0}};let wn=!0,Tn=!1,N=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(wn=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(wn=!1),wn?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Cn):(setTimeout(()=>{Tn||t(35)},1),new Cn)}();var En=class{constructor(e=`Reaction`,t,n,r){this.tt=void 0,this.Et=void 0,this.kt=void 0,this.Ct=void 0,this.L=[],this.$=[],this.K=-1,this.U=0,this.W=0,this.yt=0,this.It=void 0,this.tt=e,this.Et=t,this.kt=n,this.Ct=r}get isDisposed(){return m(this.yt,1)}set isDisposed(e){this.yt=h(this.yt,1,e)}get isScheduled(){return m(this.yt,2)}set isScheduled(e){this.yt=h(this.yt,2,e)}get isTrackPending(){return m(this.yt,4)}set isTrackPending(e){this.yt=h(this.yt,4,e)}get isRunning(){return m(this.yt,8)}set isRunning(e){this.yt=h(this.yt,8,e)}get diffValue(){return+!!m(this.yt,16)}set diffValue(e){this.yt=h(this.yt,16,e===1)}q(){this.Y()}Y(){this.isScheduled||(this.isScheduled=!0,N.pendingReactions.push(this),Ie())}X(){if(!this.isDisposed){je(),this.isScheduled=!1;let e=N.trackingContext;if(N.trackingContext=this,xe(this)){this.isTrackPending=!0;try{this.Et()}catch(e){this.Pt(e)}}N.trackingContext=e,Me()}}track(e){if(this.isDisposed)return;je(),this.isRunning=!0;let t=N.trackingContext;N.trackingContext=this;let n=Se(this,e,void 0);N.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Ce(this),be(n)&&this.Pt(n.cause),Me()}Pt(e){if(this.kt)this.kt(e,this);else{if(N.disableErrorBoundaries)throw e;N.suppressReactionErrors||console.error(`[mobx] uncaught error in '${this}'`,e),N.globalReactionErrorHandlers.forEach(t=>t(e,this))}}dispose(){var e;this.isDisposed||(this.isDisposed=!0,(e=this.It)==null||e.call(this),this.isRunning||(je(),Ce(this),Me()))}Z(e){let t=()=>this.dispose();return e!=null&&e.addEventListener&&!this.isDisposed&&(e.addEventListener(`abort`,t),this.It=()=>e.removeEventListener==null?void 0:e.removeEventListener(`abort`,t)),t[j]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.tt}]`}};let Dn=100,On=e=>e(),kn=l(`Reaction`,En),An=`action`,jn=`autoAction`,Mn=b(An),Nn=b(`action.bound`,{bound:!0}),Pn=b(jn,{autoAction:!0}),Fn=b(`autoAction.bound`,{autoAction:!0,bound:!0}),In=ze(!1);Pt(In,Mn);let Ln=ze(!0);Pt(Ln,Pn);let Rn=Re(Nn),zn=Re(Fn),Bn=e=>e(),Vn=`always`;var Hn=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};let Un=T(`flow`),Wn=T(`flow.bound`,{bound:!0}),Gn=Pt(function(e,t){if(t&&typeof t.kind==`string`)return D(Un,e,t);let n=e,i=n.name||`flow`,a=function(){let e=arguments,t=In(i,n).apply(this,e),a,o,s=new Promise(function(e,n){function s(e){let r;o=void 0;try{r=In(i,t.next).call(t,e)}catch(e){return n(e)}l(r)}function c(e){let r;o=void 0;try{r=In(i,t.throw).call(t,e)}catch(e){return n(e)}l(r)}function l(t){if(!r(t?.then))return t.done?e(t.value):(o=Promise.resolve(t.value),o.then(s,c));t.then(l,n)}a=n,s(void 0)});return s.cancel=In(i,function(){try{o&&Je(o);let e=t.return(void 0),n=Promise.resolve(e.value);n.then(Vt,Vt),Je(n),a(new Hn)}catch(e){a(e)}}),s};return a.isMobXFlow=!0,a},Un),Kn=ue(Wn,D),qn={has:(e,t)=>st(e).et(t),get:(e,t)=>st(e).Tt(t),set(e,t,n){var r;return!!i(t)&&((r=st(e).Bt(t,n,!0))==null||r)},deleteProperty(e,t){var n;return!!i(t)&&((n=st(e).Dt(t,!0))==null||n)},defineProperty(e,t,n){var r;return(r=st(e).l(t,n))==null||r},ownKeys:e=>st(e).it(),preventExtensions(e){t(13)}},Jn=Symbol(`mobx-keys`),Yn=`splice`,Xn=`update`,Zn={get(e,t){let n=e[j];return t===j?n:t===`length`?n.Kt():typeof t!=`string`||isNaN(t)?p($n,t)?$n[t]:e[t]:n.Tt(parseInt(t))},set(e,t,n){let r=e[j];return t===`length`?r.Lt(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.Bt(parseInt(t),n),!0},preventExtensions(){t(15)}};var Qn=class{constructor(e=`ObservableArray`,t,n){this.$t=void 0,this.ct=void 0,this.j=[],this.st=void 0,this.ot=void 0,this.A=void 0,this.dehancer=void 0,this.v=void 0,this.Ut=0,this.$t=n,this.ct=new Wt(e),this.A=(e,n)=>t(e,n,`ObservableArray[..]`)}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}ht(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e}Kt(){return this.ct.reportObserved(),this.j.length}Lt(e){(!Number.isInteger(e)||e<0)&&t(40,e);let n=this.j.length;if(e!==n)if(e>n){let t=Array.from({length:e-n});this.wt(n,0,t)}else this.wt(e,n-e)}zt(e,n){e!==this.Ut&&t(16),this.Ut+=n}wt(e,t,n){let r=this.j.length;if(e===void 0?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=arguments.length===1?r-e:t==null?0:Math.max(0,Math.min(t,r-e)),n===void 0&&(n=Rt),ct(this)){let r=ut(this,{object:this.v,type:Yn,index:e,removedCount:t,added:n});if(!r)return Rt;t=r.removedCount,n=r.added}n=n.length===0?n:n.map(e=>this.A(e,void 0));let i=this.qt(e,t,n);return t===0&&n.length===0||this.Ft(e,n,i),this.ht(i)}qt(e,t,n){if(n.length<1e4)return this.j.splice(e,t,...n);{let r=this.j.slice(e,e+t),i=this.j.slice(e+t);this.j.length+=n.length-t;for(let t=0;t<n.length;t++)this.j[e+t]=n[t];for(let t=0;t<i.length;t++)this.j[e+n.length+t]=i[t];return r}}Ht(e,t,n){let r=dt(this),i=r?{observableKind:`array`,object:this.v,type:Xn,debugObjectName:this.ct.tt,index:e,newValue:t,oldValue:n}:null;this.ct.reportChanged(),r&&pt(this,i)}Ft(e,t,n){let r=dt(this),i=r?{observableKind:`array`,object:this.v,debugObjectName:this.ct.tt,type:Yn,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;this.ct.reportChanged(),r&&pt(this,i)}Tt(e){return this.ct.reportObserved(),this.Wt(this.j[e])}Bt(e,t){let n=this.j;if(e<n.length){let r=n[e];if(ct(this)){let n=ut(this,{type:Xn,object:this.v,index:e,newValue:t});if(!n)return;t=n.newValue}(t=this.A(t,r))!==r&&(n[e]=t,this.Ht(e,t,r))}else{let r=Array.from({length:e+1-n.length});r[r.length-1]=t,this.wt(n.length,0,r)}}},$n={clear(){return this.splice(0)},replace(e){let t=this[j];return t.wt(0,t.j.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[j];switch(arguments.length){case 0:return[];case 1:return r.wt(e);case 2:return r.wt(e,t)}return r.wt(e,t,n)},spliceWithArray(e,t,n){return this[j].wt(e,t,n)},push(...e){let t=this[j];return t.wt(t.j.length,0,e),t.j.length},pop(){return this.splice(Math.max(this[j].j.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[j];return t.wt(0,0,e),t.j.length},reverse(){return N.trackingDerivation&&t(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){N.trackingDerivation&&t(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[j],n=t.ht(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};ht(`at`,gt),ht(`concat`,gt),ht(`flat`,gt),ht(`includes`,gt),ht(`indexOf`,gt),ht(`join`,gt),ht(`lastIndexOf`,gt),ht(`slice`,gt),ht(`toString`,gt),ht(`toLocaleString`,gt),ht(`toSorted`,gt),ht(`toSpliced`,gt),ht(`with`,gt),ht(`every`,_t),ht(`filter`,_t),ht(`find`,_t),ht(`findIndex`,_t),ht(`findLast`,_t),ht(`findLastIndex`,_t),ht(`flatMap`,_t),ht(`forEach`,_t),ht(`map`,_t),ht(`some`,_t),ht(`toReversed`,_t),ht(`reduce`,vt),ht(`reduceRight`,vt);let er=l(`ObservableArrayAdministration`,Qn),tr={},nr=`delete`;var rr=class{constructor(e,t=v,n=`ObservableMap`){this.A=void 0,this.tt=void 0,this[j]=tr,this.ft=void 0,this.dt=void 0,this.lt=void 0,this.st=void 0,this.ot=void 0,this.dehancer=void 0,this.A=t,this.tt=n,Ot(()=>{this.lt=g(`ObservableMap.keys()`),this.ft=new Map,this.dt=new Map,e&&this.merge(e)})}et(e){return this.ft.has(e)}has(e){if(!N.trackingDerivation)return this.et(e);let t=this.dt.get(e);if(!t){let n=t=new _n(this.et(e),y,`ObservableMap.key?`,!1);this.dt.set(e,n),n.onBUOL=new Set([()=>this.dt.delete(e)])}return t.get()}set(e,t){let n=this.et(e);if(ct(this)){let r=ut(this,{type:n?Xn:`add`,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.Gt(e,t):this.Jt(e,t),this}delete(e){if(ct(this)&&!ut(this,{type:nr,object:this,name:e}))return!1;if(this.et(e)){let t=dt(this),n=t?{observableKind:`map`,debugObjectName:this.tt,type:nr,object:this,oldValue:this.ft.get(e).rt,name:e}:null;return at(()=>{var t;this.lt.reportChanged(),(t=this.dt.get(e))==null||t.Ot(!1),this.ft.get(e).Ot(void 0),this.ft.delete(e)}),t&&pt(this,n),!0}return!1}Gt(e,t){let n=this.ft.get(e);if((t=n.jt(t))!==N.UNCHANGED){let r=dt(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:Xn,object:this,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&pt(this,i)}}Jt(e,t){at(()=>{var n;let r=new _n(t,this.A,`ObservableMap.key`,!1);this.ft.set(e,r),t=r.rt,(n=this.dt.get(e))==null||n.Ot(!0),this.lt.reportChanged()});let n=dt(this);n&&pt(this,n?{observableKind:`map`,debugObjectName:this.tt,type:`add`,object:this,name:e,newValue:t}:null)}get(e){return this.has(e)?this.Wt(this.ft.get(e).get()):this.Wt(void 0)}getOrInsert(e,t){return this.has(e)||this.set(e,t),this.get(e)}getOrInsertComputed(e,t){return this.has(e)||this.set(e,t(e)),this.get(e)}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}keys(){return this.lt.reportObserved(),this.ft.keys()}values(){let e=this,t=this.keys();return bt({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:e.get(r)}}})}entries(){let e=this,t=this.keys();return bt({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:[r,e.get(r)]}}})}[Symbol.iterator](){return this.entries()}forEach(e,t){for(let[n,r]of this)e.call(t,r,n,this)}merge(e){return ir(e)&&(e=new Map(e)),at(()=>{o(e)?function(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>Lt.propertyIsEnumerable.call(e,t))]:t}(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):u(e)?(function(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}(e)||t(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&t(20,e)}),this}clear(){at(()=>{we(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return at(()=>{let n=function(e){if(u(e)||ir(e))return e;if(Array.isArray(e))return new Map(e);if(o(e)){let t=new Map;for(let n in e)t.set(n,e[n]);return t}return t(21,e)}(e),r=new Map,i=!1;for(let e of this.ft.keys())if(!n.has(e))if(this.delete(e))i=!0;else{let t=this.ft.get(e);r.set(e,t)}for(let[e,t]of n.entries()){let n=this.ft.has(e);if(this.set(e,t),this.ft.has(e)){let t=this.ft.get(e);r.set(e,t),n||(i=!0)}}if(!i)if(this.ft.size!==r.size)this.lt.reportChanged();else{let e=this.ft.keys(),t=r.keys(),n=e.next(),i=t.next();for(;!n.done;){if(n.value!==i.value){this.lt.reportChanged();break}n=e.next(),i=t.next()}}this.ft=r}),this}get size(){return this.lt.reportObserved(),this.ft.size}toString(){return`[object ObservableMap]`}toJSON(){return Array.from(this)}get[Symbol.toStringTag](){return`Map`}},ir=l(`ObservableMap`,rr);let ar={};var or=class{constructor(e,t=v,n=`ObservableSet`){this.tt=void 0,this[j]=ar,this.ft=new Set,this.ct=void 0,this.ot=void 0,this.st=void 0,this.dehancer=void 0,this.A=void 0,this.tt=n,this.A=(e,r)=>t(e,r,n),Ot(()=>{this.ct=g(this.tt),e&&this.replace(e)})}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){at(()=>{we(()=>{for(let e of this.ft.values())this.delete(e)})})}forEach(e,t){for(let n of this)e.call(t,n,n,this)}get size(){return this.ct.reportObserved(),this.ft.size}add(e){if(ct(this)){let t=ut(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){at(()=>{e=this.A(e,void 0),this.ft.add(e),this.ct.reportChanged()});let t=dt(this);t&&pt(this,t?{observableKind:`set`,debugObjectName:this.tt,type:`add`,object:this,newValue:e}:null)}return this}delete(e){if(ct(this)&&!ut(this,{type:nr,object:this,oldValue:e}))return!1;if(this.has(e)){let t=dt(this),n=t?{observableKind:`set`,debugObjectName:this.tt,type:nr,object:this,oldValue:e}:null;return at(()=>{this.ct.reportChanged(),this.ft.delete(e)}),t&&pt(this,n),!0}return!1}has(e){return this.ct.reportObserved(),this.ft.has(this.Wt(e))}entries(){let e=this.values();return xt({next(){let{value:t,done:n}=e.next();return n?{value:void 0,done:n}:{value:[t,t],done:n}}})}keys(){return this.values()}values(){this.ct.reportObserved();let e=this,t=this.ft.values();return xt({next(){let{value:n,done:r}=t.next();return r?{value:void 0,done:r}:{value:e.Wt(n),done:r}}})}intersection(e){return new Set(this).intersection(e)}union(e){return new Set(this).union(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}replace(e){return sr(e)&&(e=new Set(e)),Array.isArray(e)||d(e)?at(()=>{let t=d(e)?e:new Set(e);if(t.size!==0)if(this.ft.size!==0){for(let e of this.ft.values())t.has(this.Wt(e))||this.delete(e);t.forEach(e=>this.add(e))}else t.forEach(e=>this.add(e));else this.clear()}):e!=null&&t(41,e),this}toJSON(){return Array.from(this)}toString(){return`[object ObservableSet]`}[Symbol.iterator](){return this.values()}get[Symbol.toStringTag](){return`Set`}},sr=l(`ObservableSet`,or);let cr=Object.create(null),lr=`remove`;var ur=class{constructor(e,t=new Map,n,r=Yt){this.h=void 0,this.j=void 0,this.tt=void 0,this.ut=void 0,this.lt=void 0,this.ot=void 0,this.st=void 0,this.v=void 0,this.p=void 0,this.Xt=void 0,this.Qt=void 0,this.O=void 0,this.V=void 0,this.h=e,this.j=t,this.tt=n,this.ut=r,this.lt=new Wt(`ObservableObject.keys`),this.p=o(this.h)}_(e){return(this.j.get(e)??this.vt(e)??this.bt(e)).get()}vt(e){let t=this.O?.get(e);if(!t)return;this.O.delete(e),this.O.size===0&&(this.O=void 0);let n=t();return this.j.set(e,n),n}bt(e){let t=this.V?.get(e);if(!t)return;this.V.delete(e),this.V.size===0&&(this.V=void 0);let n=t();return this.j.set(e,n),n}M(e,t){let n=this.j.get(e)??this.vt(e)??this.bt(e);if(n instanceof yn)return n.set(t),!0;if(ct(this)){let n=ut(this,{type:Xn,object:this.v||this.h,name:e,newValue:t});if(!n)return null;t=n.newValue}if((t=n.jt(t))!==N.UNCHANGED){let r=dt(this),i=r?{type:Xn,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&pt(this,i)}return!0}Tt(e){return N.trackingDerivation&&!p(this.h,e)&&this.et(e),this.h[e]}Bt(e,t,n=!1){return p(this.h,e)?this.j.has(e)?this.M(e,t):n?Reflect.set(this.h,e,t):(this.h[e]=t,!0):this.u(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.ut,n)}et(e){if(!N.trackingDerivation)return e in this.h;this.Qt||=new Map;let t=this.Qt.get(e);return t||(t=new _n(e in this.h,y,`ObservableObject.key?`,!1),this.Qt.set(e,t)),t.get()}u(e,t,n,r=!1){return!0===n&&(n=this.ut),!1===n?this.l(e,t,r):n.u(this,e,t,r)}l(e,t,n=!1){try{je();let r=this.Dt(e);if(!r)return r;if(ct(this)){let n=ut(this,{object:this.v||this.h,name:e,type:`add`,newValue:t.value});if(!n)return null;let{newValue:r}=n;t.value!==r&&(t=Pt({},t,{value:r}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else It(this.h,e,t);this.Yt(e,t.value)}finally{Me()}return!0}S(e,t,n,r=!1){try{je();let i=this.Dt(e);if(!i)return i;if(ct(this)){let n=ut(this,{object:this.v||this.h,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let a=Ct(e),o={configurable:!N.safeDescriptors||this.p,enumerable:!0,get:a.get,set:a.set};if(r){if(!Reflect.defineProperty(this.h,e,o))return!1}else It(this.h,e,o);let s=new _n(t,n,`ObservableObject.key`,!1);this.j.set(e,s),this.Yt(e,s.rt)}finally{Me()}return!0}m(e,t,n=!1){try{je();let r=this.Dt(e);if(!r)return r;if(ct(this)&&!ut(this,{object:this.v||this.h,name:e,type:`add`,newValue:void 0}))return null;t.name||=`ObservableObject.key`,t.context=this.v||this.h;let i=Ct(e),a={configurable:!N.safeDescriptors||this.p,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.h,e,a))return!1}else It(this.h,e,a);this.j.set(e,new yn(t)),this.Yt(e,void 0)}finally{Me()}return!0}Dt(e,t=!1){if(!p(this.h,e))return!0;if(ct(this)&&!ut(this,{object:this.v||this.h,name:e,type:lr}))return null;try{var n;je();let r=dt(this),i=this.j.get(e),a;if(i||!r||(a=Ft(this.h,e)?.value),t){if(!Reflect.deleteProperty(this.h,e))return!1}else delete this.h[e];i&&(this.j.delete(e),i instanceof _n&&(a=i.rt),Fe(i)),this.lt.reportChanged(),(n=this.Qt)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&pt(this,{type:lr,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{Me()}return!0}Yt(e,t){var n;let r=dt(this);r&&r&&pt(this,r?{type:`add`,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,name:e,newValue:t}:null),(n=this.Qt)==null||(n=n.get(e))==null||n.set(!0),this.lt.reportChanged()}it(){return this.lt.reportObserved(),Ht(this.h)}nt(){return this.lt.reportObserved(),Object.keys(this.h)}};let dr=l(`ObservableObjectAdministration`,ur),fr=Lt.toString,pr=globalThis.Iterator?.prototype||{};e.$mobx=j,e.FlowCancellationError=Hn,e.ObservableMap=rr,e.ObservableSet=or,e.Reaction=En,e._allowStateChanges=ye,e._allowStateChangesInsideComputed=Be,e._allowStateReadsEnd=function(e){N.allowStateReads=e},e._allowStateReadsStart=function(e){let t=N.allowStateReads;return N.allowStateReads=e,t},e._autoAction=Ln,e._autoActionBound=zn,e._endAction=ve,e._getAdministration=Et,e._getGlobalState=function(){return N},e._interceptReads=function(e,t,n){let r;return ir(e)||yt(e)||vn(e)?r=Et(e):wt(e)&&(r=Et(e,t)),r.dehancer=typeof t==`function`?t:n,()=>{r.dehancer=void 0}},e._isComputingDerivation=function(){return N.trackingDerivation!==null},e._resetGlobalState=function(){let e=new Cn;for(let t in e)Sn.indexOf(t)===-1&&(N[t]=e[t]);N.allowStateChanges=!N.enforceActions},e._startAction=_e,e.action=In,e.actionBound=Rn,e.autorun=He,e.compareDefault=Kt,e.compareIdentity=function(e,t){return e===t},e.compareShallow=function(e,t){return kt(e,t,1)},e.compareStructural=_,e.computed=dn,e.computedStruct=un,e.configure=function(e){!0===e.isolateGlobalState&&function(){if((N.pendingReactions.length||N.inBatch||N.isRunningReactions)&&t(36),Tn=!0,wn){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),N=new Cn}}();let{enforceActions:n}=e;if(n!==void 0){let e=n===Vn?Vn:n===`observed`;N.enforceActions=e,N.allowStateChanges=!0!==e&&e!==Vn}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(N[t]=!!e[t])}),N.allowStateReads=!N.observableRequiresReaction,e.reactionScheduler&&function(e){let t=On;On=n=>e(()=>t(n))}(e.reactionScheduler)},e.createAtom=g,e.defineProperty=function(e,n,r){if(wt(e))return e[j].l(n,r);t(39)},e.entries=function(e){return wt(e)?$e(e).map(t=>[t,e[t]]):ir(e)?$e(e).map(t=>[t,e.get(t)]):sr(e)?Array.from(e.entries()):yt(e)?e.map((e,t)=>[t,e]):void t(7)},e.extendObservable=Ge,e.flow=Gn,e.flowBound=Kn,e.flowResult=function(e){return e},e.get=function(e,n){if(et(e,n))return wt(e)?e[j].Tt(n):ir(e)?e.get(n):yt(e)?e[n]:void t(11)},e.getAtom=Tt,e.getDebugName=Dt,e.getDependencyTree=function(e,t){return Ke(Tt(e,t))},e.getObserverTree=function(e,t){return qe(Tt(e,t))},e.has=et,e.intercept=function(e,t,n){return r(n)?function(e,t,n){return lt(Et(e,t),n)}(e,t,n):function(e,t){return lt(Et(e),t)}(e,t)},e.isAction=Ve,e.isBoxedObservable=vn,e.isComputed=function(e){return Xe(e)},e.isComputedProp=function(e,t){return Xe(e,t)},e.isFlow=Ye,e.isFlowCancellationError=function(e){return e instanceof Hn},e.isObservable=Qe,e.isObservableArray=yt,e.isObservableMap=ir,e.isObservableObject=wt,e.isObservableProp=function(e,t){return Ze(e,t)},e.isObservableSet=sr,e.keys=$e,e.makeAutoObservable=function(e,t,n){return o(e)?Ge(e,e,t,n):(Ot(()=>{let r=St(e,n)[j];if(!e[Jn]){let t=Object.getPrototypeOf(e),n=new Set([...Ht(e),...Ht(t)]);n.delete(`constructor`),n.delete(j),c(t,Jn,n)}e[Jn].forEach(e=>mt(r,e,!t||!(e in t)||t[e]))}),e)},e.makeObservable=function(e,t,n){return Ot(()=>{let r=St(e,n)[j];Ht(t).forEach(e=>mt(r,e,t[e]))}),e},e.observable=sn,e.observableDeep=an,e.observableRef=nn,e.observableShallow=rn,e.observableStruct=on,e.observe=function(e,t,n,i){return r(n)?function(e,t,n,r){return nt(Et(e,t),n,r)}(e,t,n,i):function(e,t,n){let r=Et(e);if(yt(e))n&&t({observableKind:`array`,object:r.v,debugObjectName:r.ct.tt,type:`splice`,index:0,added:r.j.slice(),addedCount:r.j.length,removed:[],removedCount:0});else if(!ir(e)&&!sr(e)&&!wt(e))return nt(r,t,n);return ft(r,t)}(e,t,n)},e.onBecomeObserved=function(e,t,n){return We(`onBO`,e,t,n)},e.onBecomeUnobserved=function(e,t,n){return We(`onBUO`,e,t,n)},e.onReactionError=function(e){return N.globalReactionErrorHandlers.push(e),()=>{let t=N.globalReactionErrorHandlers.indexOf(e);t>=0&&N.globalReactionErrorHandlers.splice(t,1)}},e.override=qt,e.ownKeys=tt,e.reaction=function(e,t,n=zt){function r(){if(p=!1,h.isDisposed)return;let t=!1,r=d;h.track(()=>{let n=ye(!1,()=>e(h));t=f||!m(d,n),d=n}),(f&&n.fireImmediately||!f&&t)&&o(d,r,h),f=!1}var i;let a=n.name??`Reaction`,o=In(a,n.onError?(s=n.onError,c=t,function(){try{return c.apply(this,arguments)}catch(e){s.call(this,e)}}):t);var s,c;let l=!n.scheduler&&!n.delay,u=Ue(n),d,f=!0,p=!1,m=n.equals||Kt,h=new En(a,()=>{f||l?r():p||(p=!0,u(r))},n.onError,n.requiresObservable);return n!=null&&(i=n.signal)!=null&&i.aborted||h.Y(),h.Z(n?.signal)},e.remove=function(e,n){wt(e)?e[j].Dt(n):ir(e)||sr(e)?e.delete(n):yt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=Be,e.set=function e(n,r,i){if(arguments.length===2&&!sr(n)){je();let t=r;try{for(let r in t)e(n,r,t[r])}finally{Me()}return}wt(n)?n[j].Bt(r,i):ir(n)?n.set(r,i):sr(n)?n.add(r):yt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(42,r),je(),r>=n.length&&(n.length=r+1),n[r]=i,Me()):t(8)},e.spy=function(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}},e.toJS=function(e){return it(e,new Map)},e.transaction=at,e.untracked=we,e.values=function(e){return wt(e)?$e(e).map(t=>e[t]):ir(e)?$e(e).map(t=>e.get(t)):sr(e)?Array.from(e.values()):yt(e)?e.slice():void t(6)},e.when=function(e,t,n){return arguments.length===1||t&&typeof t==`object`?function(e,t){var n;if(t!=null&&(n=t.signal)!=null&&n.aborted)return Pt(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let r,i,a=new Promise((n,a)=>{var o;let s=ot(e,n,Pt({},t,{onError:a}));r=()=>{s(),a(Error(`WHEN_CANCELLED`))},i=()=>{s(),a(Error(`WHEN_ABORTED`))},t==null||(o=t.signal)==null||o.addEventListener==null||o.addEventListener(`abort`,i)}).finally(()=>{var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,i)});return a.cancel=r,a}(e,t):ot(e,t,n||{})}})),uw=De((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t={0:`Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'`,1(e,t){return`Cannot apply '${e}' to '${t.toString()}': Field not found.`},5:`'keys()' can only be used on observable objects, arrays, sets and maps`,6:`'values()' can only be used on observable objects, arrays, sets and maps`,7:`'entries()' can only be used on observable objects, arrays and maps`,8:`'set()' can only be used on observable objects, arrays and maps`,9:`'remove()' can only be used on observable objects, arrays and maps`,10:`'has()' can only be used on observable objects, arrays and maps`,11:`'get()' can only be used on observable objects, arrays and maps`,12:`Invalid annotation`,13:`Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,14:`Intercept handlers should return nothing or a change object`,15:`Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,16:`Modification exception: the internal structure of an observable array was changed.`,19(e){return`Cannot initialize from classes that inherit from Map: `+e.constructor.name},20(e){return`Cannot initialize map from `+e},21(e){return`Cannot convert to map from '${e}'`},23:`It is not possible to get index atoms from arrays`,24(e){return`Cannot obtain administration from `+e},25(e,t){return`the entry '${e}' does not exist in the observable map '${t}'`},26:`please specify a property`,27(e,t){return`no observable property '${e.toString()}' found on the observable object '${t}'`},28(e){return`Cannot obtain atom from `+e},29:`Expecting some object`,30:`invalid action stack. did you forget to finish an action?`,31:`missing option for computed: get`,32(e,t){return`Cycle detected in computation ${e}: ${t}`},33(e){return`The setter of computed value '${e}' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?`},34(e){return`[ComputedValue '${e}'] It is not possible to assign a new value to a computed value.`},35:"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`",36:`isolateGlobalState should be called before MobX is running any reactions`,37(e){return`[mobx] \`observableArray.${e}()\` mutates the array in-place, which is not allowed inside a derivation. Use \`array.slice().${e}()\` instead`},38:`'ownKeys()' can only be used on observable objects`,39:`'defineProperty()' can only be used on observable objects`,40(e){return`Out of range: `+e},41(e){return`Cannot initialize set from `+e},42(e){return`Invalid index: '${e}'`},43(e,t,n){return`Cannot apply '${e}' to '${t}' (kind: ${n}):\n'${e}' can only be used on properties with a function value.`},44(e){return`'${e}' can only be used with 'makeObservable'`}};function n(e,...n){{let r=typeof e==`string`?e:t[e];throw typeof r==`function`&&(r=r.apply(null,n)),Error(`[MobX] ${r}`)}}let r=Object.assign,i=Object.getOwnPropertyDescriptor,a=Object.defineProperty,o=Object.prototype,s=[];Object.freeze(s);let c={};Object.freeze(c);let l=Object.toString();function u(){return++M.mobxGuid}function d(e){let t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}let f=()=>{};function p(e){return typeof e==`function`}function m(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function h(e){return typeof e==`object`&&!!e}function g(e){if(!h(e))return!1;let t=Object.getPrototypeOf(e);if(t==null)return!0;let n=D(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===l}function _(e){let t=e?.constructor;return t?t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`:!1}function v(e,t,n){a(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function y(e,t,n){a(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function b(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return h(e)&&e[n]===!0}}function x(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function S(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function C(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function w(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let T=Reflect.ownKeys;function E(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function ee(e){return e===null?null:typeof e==`object`?``+e:e}function D(e,t){return o.hasOwnProperty.call(e,t)}let te=Object.getOwnPropertyDescriptors;function O(e,t){return!!(e&t)}function k(e,t,n){return n?e|=t:e&=~t,e}function ne(e,t){t.includes(e.kind)||n(`The decorator applied to '${String(e.name)}' cannot be used on a ${e.kind} element`)}let A=Symbol(`mobx administration`);var re=class{constructor(e=`Atom@`+u()){this.name_=void 0,this.flags_=0,this.observers_=null,this.lastAccessedBy_=0,this.lowestObserverState_=-1,this.onBOL=void 0,this.onBUOL=void 0,this.name_=e}get isBeingObserved(){return O(this.flags_,1)}set isBeingObserved(e){this.flags_=k(this.flags_,1,e)}get isPendingUnobservation(){return O(this.flags_,2)}set isPendingUnobservation(e){this.flags_=k(this.flags_,2,e)}get diffValue(){return+!!O(this.flags_,4)}set diffValue(e){this.flags_=k(this.flags_,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return ln(this)}reportChanged(){an(),un(this),on()}toString(){return this.name_}};let ie=b(`Atom`,re);function ae(e,t=f,n=f){let r=new re(e);return t!==f&&(r.onBOL=new Set([t])),n!==f&&(r.onBUOL=new Set([n])),r}function oe(e,t){return e===t}function se(e,t){return Li(e,t)}function ce(e,t){return Li(e,t,1)}let le=Object.is;function ue(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||xr(e)?e:Array.isArray(e)?ut.array(e,{name:n}):g(e)?ut.object(e,void 0,{name:n}):x(e)?ut.map(e,{name:n}):C(e)?ut.set(e,{name:n}):typeof e==`function`&&!zn(e)&&!fr(e)?_(e)?cr(e):Fn(n,e):e}function de(e,t,r){if(e==null||Ai(e)||pi(e)||_i(e)||Si(e))return e;if(Array.isArray(e))return ut.array(e,{name:r,deep:!1});if(g(e))return ut.object(e,void 0,{name:r,deep:!1});if(x(e))return ut.map(e,{name:r,deep:!1});if(C(e))return ut.set(e,{name:r,deep:!1});n(`The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets`)}function fe(e){return e}function pe(e,t){return xr(e)&&n(`observable.struct should not be used with observable values`),Li(e,t)?t:e}let me=`override`,he={annotationType_:me,make_:_e,extend_:ve};function ge(e){return e.annotationType_===me}function _e(e,t){return e.isPlainObject_&&n(`Cannot apply '${this.annotationType_}' to '${e.name_}.${t.toString()}':\n'${this.annotationType_}' cannot be used on plain objects.`),D(e.appliedAnnotations_,t)||n(`'${e.name_}.${t.toString()}' is annotated with '${this.annotationType_}', but no such annotated member was found on prototype.`),0}function ve(e,t,r,i){n(44,this.annotationType_)}function ye(e,t){return{annotationType_:e,options_:t,make_:be,extend_:xe}}function be(e,t,n,r){var i;return(i=this.options_)!=null&&i.bound?this.extend_(e,t,n,!1)===null?0:1:r===e.target_?this.extend_(e,t,n,!1)===null?0:2:zn(n.value)?1:(a(r,t,we(e,this,t,n,!1)),2)}function xe(e,t,n,r){let i=we(e,this,t,n);return e.defineProperty_(t,i,r)}function Se(e,t,r){ne(r,[`method`,`field`]);let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>bt(s.options_?.name??a.toString(),e,s.options_?.autoAction??!1);if(i==`field`)return function(e){var t;let n=e;return zn(n)||(n=c(n)),(t=s.options_)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n};if(i==`method`){var l;return zn(t)||(t=c(t)),(l=s.options_)!=null&&l.bound&&o(function(){let e=this,t=e[a].bind(e);t.isMobxAction=!0,e[a]=t}),t}n(43,s.annotationType_,String(a),i)}function Ce(e,{annotationType_:t},r,{value:i}){p(i)||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on properties with a function value.`)}function we(e,t,n,r,i=M.safeDescriptors){var a,o;Ce(e,t,n,r);let{value:s}=r;return(a=t.options_)!=null&&a.bound&&(s=s.bind(e.proxy_??e.target_)),{value:bt(t.options_?.name??n.toString(),s,t.options_?.autoAction??!1,(o=t.options_)!=null&&o.bound?e.proxy_??e.target_:void 0),configurable:i?e.isPlainObject_:!0,enumerable:!1,writable:!i}}function Te(e,t){return{annotationType_:e,options_:t,make_:Ee,extend_:De}}function Ee(e,t,n,r){var i;return r===e.target_?this.extend_(e,t,n,!1)===null?0:2:(i=this.options_)!=null&&i.bound&&(!D(e.target_,t)||!fr(e.target_[t]))&&this.extend_(e,t,n,!1)===null?0:fr(n.value)?1:(a(r,t,Ae(e,this,t,n,!1,!1)),2)}function De(e,t,n,r){let i=Ae(e,this,t,n,this.options_?.bound);return e.defineProperty_(t,i,r)}function Oe(e,t,n){var r;ne(n,[`method`]);let{name:i,addInitializer:a}=n;return fr(t)||(t=cr(t)),(r=e.options_)!=null&&r.bound&&a(function(){let e=this,t=e[i].bind(e);t.isMobXFlow=!0,e[i]=t}),t}function ke(e,{annotationType_:t},r,{value:i}){p(i)||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on properties with a generator function value.`)}function Ae(e,t,n,r,i,a=M.safeDescriptors){ke(e,t,n,r);let{value:o}=r;return fr(o)||(o=cr(o)),i&&(o=o.bind(e.proxy_??e.target_),o.isMobXFlow=!0),{value:o,configurable:a?e.isPlainObject_:!0,enumerable:!1,writable:!a}}function je(e,t){return{annotationType_:e,options_:t,make_:Me,extend_:Ne}}function Me(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Ne(e,t,n,i){return Fe(e,this,t,n),e.defineComputedProperty_(t,r({},this.options_,{get:n.get,set:n.set}),i)}function Pe(e,t,n){ne(n,[`getter`]);let i=e,{name:a,addInitializer:o}=n,s;function c(e,n){let o=r({},i.options_,{get:t,context:e});return o.name||=`${n.name_}.${a.toString()}`,new kt(o)}return o(function(){let e=Di(this)[A],n=this,r=e.values_.get(a);r instanceof kt&&r.derivation!==t&&e.values_.delete(a),(e.lazyComputedKeys_??=new Map).set(a,()=>c(n,e))}),function(){let e=this[A],n=e.values_.get(a);if(n instanceof kt&&n.derivation!==t){let t=s?.get(this);return t||(t=c(this,e),(s??=new WeakMap).set(this,t)),t.get()}return e.getObservablePropValue_(a)}}function Fe(e,{annotationType_:t},r,{get:i}){i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on getter(+setter) properties.`)}function Ie(e,t){return{annotationType_:e,options_:t,make_:Le,extend_:Re}}function Le(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Re(e,t,n,r){return Be(e,this,t,n),e.defineObservableProperty_(t,n.value,this.options_?.enhancer_??ue,r)}function ze(e,t,r){if(r.kind===`field`)throw n(`Please use \`@observable accessor ${String(r.name)}\` instead of \`@observable ${String(r.name)}\``);ne(r,[`accessor`]);let i=e,{kind:a,name:o}=r;if(a!==`accessor`)return;function s(e,t){let n=Di(e)[A];return(n.lazyObservableKeys_??=new Map).set(o,()=>new Dt(t,i.options_?.enhancer_??ue,`${n.name_}.${o.toString()}`,!1)),n}return{get(){return(this[A]??s(this,t.get.call(this))).getObservablePropValue_(o)},set(e){return(this[A]??s(this,e)).setObservablePropValue_(o,e)},init(e){return s(this,e),e}}}function Be(e,{annotationType_:t},r,i){`value`in i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' cannot be used on getter/setter properties`)}let Ve=He();function He(e){return{annotationType_:`true`,options_:e,make_:Ge,extend_:Ke}}let Ue=[Ve];function We(e){let t=e.deep!==!1,n=!!e.autoBind,r=!t|(n?2:0);return Ue[r]??(Ue[r]=He({deep:t,autoBind:n}))}function Ge(e,t,n,r){var i;if(n.get)return ht.make_(e,t,n,r);if(n.set){let i=zn(n.set)?n.set:bt(t.toString(),n.set);return r===e.target_?e.defineProperty_(t,{configurable:M.safeDescriptors?e.isPlainObject_:!0,set:i})===null?0:2:(a(r,t,{configurable:!0,set:i}),2)}if(r!==e.target_&&typeof n.value==`function`){var o;if(_(n.value)){var s;return((s=this.options_)!=null&&s.autoBind?lr:cr).make_(e,t,n,r)}return((o=this.options_)!=null&&o.autoBind?Ln:Fn).make_(e,t,n,r)}let c=this.options_?.deep===!1?ot:ut;return typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),c.make_(e,t,n,r)}function Ke(e,t,n,r){var i;return n.get?ht.extend_(e,t,n,r):n.set?e.defineProperty_(t,{configurable:M.safeDescriptors?e.isPlainObject_:!0,set:bt(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),(this.options_?.deep===!1?ot:ut).extend_(e,t,n,r))}function qe(e,t){return r(function(r,i){if(i&&typeof i.kind==`string`)return t(e,r,i);n(`Invalid arguments for \`${e.annotationType_}\``)},e)}let Je={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Je);function Ye(e){return e||Je}let Xe=Ie(`observable`),Ze=Ie(`observable.ref`,{enhancer_:fe}),Qe=Ie(`observable.shallow`,{enhancer_:de}),$e=Ie(`observable.struct`,{enhancer_:pe});function et(e){return qe(e,ze)}function tt(e){return e.deep===!0?ue:e.deep===!1?fe:rt(e.defaultDecorator)}function nt(e){return e?e.defaultDecorator??We(e):void 0}function rt(e){return e?e.options_?.enhancer_??ue:ue}function it(e,t,n){return t&&typeof t.kind==`string`?ze(Xe,e,t):xr(e)?e:g(e)?ut.object(e,t,n):Array.isArray(e)?ut.array(e,t):x(e)?ut.map(e,t):C(e)?ut.set(e,t):typeof e==`object`&&e?e:ut.box(e,t)}let at={box(e,t){let n=Ye(t);return new Dt(e,tt(n),n.name,!0,n.equals)},array(e,t){let n=Ye(t);return oi(e,tt(n),n.name)},map(e,t){let n=Ye(t);return new gi(e,tt(n),n.name)},set(e,t){let n=Ye(t);return new xi(e,tt(n),n.name)},object(e,t,n){return Fi(()=>Xn(Gr({},n),e,t))}},ot=et(Ze),st=et(Qe),ct=et(Xe),lt=et($e);var ut=r(it,Xe,at);let dt=`computed`;function ft(e){return qe(e,Pe)}let pt=je(dt),mt=ft(je(`computed.struct`,{equals:se})),ht=function(e,t){if(t&&typeof t.kind==`string`)return Pe(pt,e,t);if(g(e))return ft(je(dt,e));p(e)||n("First argument to `computed` should be an expression."),p(t)&&n("A setter as second argument is no longer supported, use `{ set: fn }` option instead");let r=g(t)?t:{};return r.get=e,r.name||=e.name||``,new kt(r)};r(ht,pt);let gt=0,_t=1,vt=i(()=>{},`name`)?.configurable??!1,yt={value:`action`,configurable:!0,writable:!1,enumerable:!1};function bt(e,t,r=!1,i){p(t)||n("`action` can only be invoked on functions"),(typeof e!=`string`||!e)&&n(`actions should have valid names, got: '${e}'`);function o(){return xt(e,r,t,i||this,arguments)}return o.isMobxAction=!0,o.toString=()=>t.toString(),vt&&(yt.value=e,a(o,`name`,yt)),o}function xt(e,t,n,r,i){let a=St(e,t,r,i);try{return n.apply(r,i)}catch(e){throw a.error_=e,e}finally{Ct(a)}}function St(e,t,n,r){let i=bn()&&!!e,a=0;i&&(a=Date.now(),Sn({type:N,name:e,object:n,arguments:r?Array.from(r):s}));let o=M.trackingDerivation,c=!t||!o;an();let l=M.allowStateChanges;c&&(Ht(),l=Tt(!0));let u=M.allowStateReads;j(!0);let d={runAsAction_:c,prevDerivation_:o,prevAllowStateChanges_:l,prevAllowStateReads_:u,notifySpy_:i,startTime_:a,actionId_:_t++,parentActionId_:gt};return gt=d.actionId_,d}function Ct(e){gt!==e.actionId_&&n(30),gt=e.parentActionId_,e.error_!==void 0&&(M.suppressReactionErrors=!0),Et(e.prevAllowStateChanges_),Wt(e.prevAllowStateReads_),on(),e.runAsAction_&&Ut(e.prevDerivation_),e.notifySpy_&&wn({time:Date.now()-e.startTime_}),M.suppressReactionErrors=!1}function wt(e,t){let n=Tt(e);try{return t()}finally{Et(n)}}function Tt(e){let t=M.allowStateChanges;return M.allowStateChanges=e,t}function Et(e){M.allowStateChanges=e}var Dt=class extends re{constructor(e,t,n=`ObservableValue@`+u(),r=!0,i=le){super(n),this.enhancer_=void 0,this.name_=void 0,this.equals_=void 0,this.hasUnreportedChange_=!1,this.interceptors_=void 0,this.changeListeners_=void 0,this.value_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,this.equals_=i,this.value_=t(e,void 0,n),r&&bn()&&xn({type:`create`,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:this.value_})}dehanceValue(e){return this.dehancer===void 0?e:this.dehancer(e)}set(e){let t=this.value_;if(e=this.prepareNewValue_(e),e!==M.UNCHANGED){let n=bn();n&&Sn({type:ri,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:e,oldValue:t}),this.setNewValue_(e),n&&wn()}}prepareNewValue_(e){if(Ft(this),Kr(this)){let t=Jr(this,{object:this,type:ri,newValue:e});if(!t)return M.UNCHANGED;e=t.newValue}return e=this.enhancer_(e,this.value_,this.name_),this.equals_(this.value_,e)?M.UNCHANGED:e}setNewValue_(e){let t=this.value_;this.value_=e,this.reportChanged(),Yr(this)&&Zr(this,{type:ri,object:this,newValue:e,oldValue:t})}get(){return this.reportObserved(),this.dehanceValue(this.value_)}raw(){return this.value_}toJSON(){return this.get()}toString(){return`${this.name_}[${this.value_}]`}valueOf(){return ee(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let Ot=b(`ObservableValue`,Dt);var kt=class{constructor(e){this.dependenciesState_=-1,this.observing_=[],this.newObserving_=null,this.observers_=null,this.runId_=0,this.lastAccessedBy_=0,this.lowestObserverState_=0,this.unboundDepsCount_=0,this.value_=new jt(null),this.name_=void 0,this.triggeredBy_=void 0,this.flags_=0,this.derivation=void 0,this.setter_=void 0,this.scope_=void 0,this.equals_=void 0,this.requiresReaction_=void 0,this.keepAlive_=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||n(31),this.derivation=e.get,this.name_=e.name||`ComputedValue@`+u(),e.set&&(this.setter_=bt(this.name_+`-setter`,e.set)),this.equals_=e.equals||le,this.scope_=e.context,this.requiresReaction_=e.requiresReaction,this.keepAlive_=!!e.keepAlive}onBecomeStale_(){fn(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return O(this.flags_,1)}set isComputing(e){this.flags_=k(this.flags_,1,e)}get isRunningSetter(){return O(this.flags_,2)}set isRunningSetter(e){this.flags_=k(this.flags_,2,e)}get isBeingObserved(){return O(this.flags_,4)}set isBeingObserved(e){this.flags_=k(this.flags_,4,e)}get isPendingUnobservation(){return O(this.flags_,8)}set isPendingUnobservation(e){this.flags_=k(this.flags_,8,e)}get diffValue(){return+!!O(this.flags_,16)}set diffValue(e){this.flags_=k(this.flags_,16,e===1)}get(){if(this.isComputing&&n(32,this.name_,this.derivation),M.inBatch===0&&(!this.observers_||this.observers_.size===0)&&!this.keepAlive_)Nt(this)&&(this.warnAboutUntrackedRead_(),an(),this.value_=this.computeValue_(!1),on());else{let e=this.isBeingObserved;if(ln(this),Nt(this)){let e=M.trackingContext;!e&&(this.keepAlive_||this.isBeingObserved)&&(M.trackingContext=this),this.trackAndCompute()&&dn(this),M.trackingContext=e}else !e&&this.isBeingObserved&&this.observing_.forEach(cn)}let e=this.value_;if(Mt(e))throw e.cause;return e}set(e){if(this.setter_){this.isRunningSetter&&n(33,this.name_),this.isRunningSetter=!0;try{this.setter_.call(this.scope_,e)}finally{this.isRunningSetter=!1}}else n(34,this.name_)}trackAndCompute(){let e=this.value_,t=this.dependenciesState_===-1,n=this.computeValue_(!0),r=t||Mt(e)||Mt(n)||!this.equals_(e,n);return r&&(this.value_=n,bn()&&xn({observableKind:`computed`,debugObjectName:this.name_,object:this.scope_,type:`update`,oldValue:e,newValue:n})),r}computeValue_(e){this.isComputing=!0;let t=Tt(!1),n;if(e)n=Lt(this,this.derivation,this.scope_);else if(M.disableErrorBoundaries===!0)n=this.derivation.call(this.scope_);else try{n=this.derivation.call(this.scope_)}catch(e){n=new jt(e)}return Et(t),this.isComputing=!1,n}suspend_(){this.keepAlive_||(Bt(this),this.value_=void 0)}warnAboutUntrackedRead_(){(typeof this.requiresReaction_==`boolean`?this.requiresReaction_:M.computedRequiresReaction)&&console.warn(`[mobx] Computed value '${this.name_}' is being read outside a reactive context. Doing a full recompute.`)}toString(){return`${this.name_}[${this.derivation.toString()}]`}valueOf(){return ee(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let At=b(`ComputedValue`,kt);var jt=class{constructor(e){this.cause=void 0,this.cause=e}};function Mt(e){return e instanceof jt}function Nt(e){switch(e.dependenciesState_){case 0:return!1;case-1:case 2:return!0;case 1:{let t=j(!0),n=Ht(),r=e.observing_,i=r.length;for(let a=0;a<i;a++){let i=r[a];if(At(i)){if(M.disableErrorBoundaries)i.get();else try{i.get()}catch{return Ut(n),Wt(t),!0}if(e.dependenciesState_===2)return Ut(n),Wt(t),!0}}return Gt(e),Ut(n),Wt(t),!1}}}function Pt(){return M.trackingDerivation!==null}function Ft(e){let t=!!e.observers_&&e.observers_.size>0;!M.allowStateChanges&&(t||M.enforceActions===`always`)&&console.warn(`[MobX] `+(M.enforceActions?`Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: `:`Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: `)+e.name_)}function It(e){!M.allowStateReads&&M.observableRequiresReaction&&console.warn(`[mobx] Observable '${e.name_}' being read outside a reactive context.`)}function Lt(e,t,n){let r=j(!0);Gt(e),e.newObserving_=Array(e.runId_===0?100:e.observing_.length),e.unboundDepsCount_=0,e.runId_=++M.runId;let i=M.trackingDerivation;M.trackingDerivation=e,M.inBatch++;let a;if(M.disableErrorBoundaries===!0)a=t.call(n);else try{a=t.call(n)}catch(e){a=new jt(e)}return M.inBatch--,M.trackingDerivation=i,zt(e),Rt(e),Wt(r),a}function Rt(e){e.observing_.length===0&&(typeof e.requiresObservable_==`boolean`?e.requiresObservable_:M.reactionRequiresObservable)&&console.warn(`[mobx] Derivation '${e.name_}' is created/updated without reading any observable value.`)}function zt(e){let t=e.observing_,n=e.observing_=e.newObserving_,r=0,i=0,a=e.unboundDepsCount_;for(let e=0;e<a;e++){let t=n[e];t.diffValue===0&&(t.diffValue=1,i!==e&&(n[i]=t),i++),t.dependenciesState_>r&&(r=t.dependenciesState_)}for(n.length=i,e.newObserving_=null,a=t.length;a--;){let n=t[a];n.diffValue===0&&nn(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,tn(t,e))}r!==0&&(e.dependenciesState_=r,e.onBecomeStale_())}function Bt(e){let t=e.observing_;e.observing_=[];let n=t.length;for(;n--;)nn(t[n],e);e.dependenciesState_=-1}function Vt(e){let t=Ht();try{return e()}finally{Ut(t)}}function Ht(){let e=M.trackingDerivation;return M.trackingDerivation=null,e}function Ut(e){M.trackingDerivation=e}function j(e){let t=M.allowStateReads;return M.allowStateReads=e,t}function Wt(e){M.allowStateReads=e}function Gt(e){if(e.dependenciesState_===0)return;e.dependenciesState_=0;let t=e.observing_,n=t.length;for(;n--;)t[n].lowestObserverState_=0}let Kt=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var qt=class{constructor(){this.version=7,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.isRunningUnobservations=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.safeDescriptors=!0}};let Jt=!0,Yt=!1,M=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Jt=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(Jt=!1),Jt?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new qt):(setTimeout(()=>{Yt||n(35)},1),new qt)}();function Xt(){if((M.pendingReactions.length||M.inBatch||M.isRunningReactions)&&n(36),Yt=!0,Jt){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),M=new qt}}function Zt(){return M}function Qt(){let e=new qt;for(let t in e)Kt.indexOf(t)===-1&&(M[t]=e[t]);M.allowStateChanges=!M.enforceActions}function $t(e){return!!e.observers_&&e.observers_.size>0}function en(e){return e.observers_??new Set}function tn(e,t){(e.observers_??=new Set).add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function nn(e,t){let n=e.observers_;n&&(n.delete(t),n.size===0&&rn(e))}function rn(e){e.isPendingUnobservation===!1&&(e.isPendingUnobservation=!0,M.pendingUnobservations.push(e))}function an(){M.inBatch++}function on(){--M.inBatch===0&&(gn(),!M.isRunningUnobservations&&M.pendingUnobservations.length>0&&sn())}function sn(){M.isRunningUnobservations=!0;try{let e=M.pendingUnobservations;for(let t=0;t<e.length;t++){let n=e[t];n.isPendingUnobservation=!1,(!n.observers_||n.observers_.size===0)&&(n.observers_=null,n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof kt&&n.suspend_())}M.pendingUnobservations=[]}finally{M.isRunningUnobservations=!1}}function cn(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.observing_)==null||t.forEach(cn))}function ln(e){It(e);let t=M.trackingDerivation;return t===null?((!e.observers_||e.observers_.size===0)&&M.inBatch>0&&rn(e),!1):(t.runId_!==e.lastAccessedBy_&&(e.lastAccessedBy_=t.runId_,t.newObserving_[t.unboundDepsCount_++]=e,!e.isBeingObserved&&M.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function un(e){var t;e.lowestObserverState_!==2&&(e.lowestObserverState_=2,(t=e.observers_)==null||t.forEach(e=>{e.dependenciesState_===0&&e.onBecomeStale_(),e.dependenciesState_=2}))}function dn(e){var t;e.lowestObserverState_!==2&&(e.lowestObserverState_=2,(t=e.observers_)==null||t.forEach(t=>{t.dependenciesState_===1?t.dependenciesState_=2:t.dependenciesState_===0&&(e.lowestObserverState_=0)}))}function fn(e){var t;e.lowestObserverState_===0&&(e.lowestObserverState_=1,(t=e.observers_)==null||t.forEach(e=>{e.dependenciesState_===0&&(e.dependenciesState_=1,e.onBecomeStale_())}))}var pn=class{constructor(e=`Reaction@`+u(),t,n,r){this.name_=void 0,this.onInvalidate_=void 0,this.errorHandler_=void 0,this.requiresObservable_=void 0,this.observing_=[],this.newObserving_=[],this.dependenciesState_=-1,this.runId_=0,this.unboundDepsCount_=0,this.flags_=0,this.removeAbortListener_=void 0,this.name_=e,this.onInvalidate_=t,this.errorHandler_=n,this.requiresObservable_=r}get isDisposed(){return O(this.flags_,1)}set isDisposed(e){this.flags_=k(this.flags_,1,e)}get isScheduled(){return O(this.flags_,2)}set isScheduled(e){this.flags_=k(this.flags_,2,e)}get isTrackPending(){return O(this.flags_,4)}set isTrackPending(e){this.flags_=k(this.flags_,4,e)}get isRunning(){return O(this.flags_,8)}set isRunning(e){this.flags_=k(this.flags_,8,e)}get diffValue(){return+!!O(this.flags_,16)}set diffValue(e){this.flags_=k(this.flags_,16,e===1)}onBecomeStale_(){this.schedule_()}schedule_(){this.isScheduled||(this.isScheduled=!0,M.pendingReactions.push(this),gn())}runReaction_(){if(!this.isDisposed){an(),this.isScheduled=!1;let e=M.trackingContext;if(M.trackingContext=this,Nt(this)){this.isTrackPending=!0;try{this.onInvalidate_(),this.isTrackPending&&bn()&&xn({name:this.name_,type:`scheduled-reaction`})}catch(e){this.reportExceptionInDerivation_(e)}}M.trackingContext=e,on()}}track(e){if(this.isDisposed)return;an();let t=bn(),n;t&&(n=Date.now(),Sn({name:this.name_,type:`reaction`})),this.isRunning=!0;let r=M.trackingContext;M.trackingContext=this;let i=Lt(this,e,void 0);M.trackingContext=r,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Bt(this),Mt(i)&&this.reportExceptionInDerivation_(i.cause),t&&wn({time:Date.now()-n}),on()}reportExceptionInDerivation_(e){if(this.errorHandler_){this.errorHandler_(e,this);return}if(M.disableErrorBoundaries)throw e;let t=`[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '${this}'`;M.suppressReactionErrors?console.warn(`[mobx] (error in reaction '${this.name_}' suppressed, fix error of causing action below)`):console.error(t,e),bn()&&xn({type:`error`,name:this.name_,message:t,error:``+e}),M.globalReactionErrorHandlers.forEach(t=>t(e,this))}dispose(){if(!this.isDisposed){var e;this.isDisposed=!0,(e=this.removeAbortListener_)==null||e.call(this),this.isRunning||(an(),Bt(this),on())}}getDisposer_(e){let t=()=>this.dispose();return e!=null&&e.addEventListener&&!this.isDisposed&&(e.addEventListener(`abort`,t),this.removeAbortListener_=()=>e.removeEventListener==null?void 0:e.removeEventListener(`abort`,t)),t[A]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.name_}]`}};function mn(e){return M.globalReactionErrorHandlers.push(e),()=>{let t=M.globalReactionErrorHandlers.indexOf(e);t>=0&&M.globalReactionErrorHandlers.splice(t,1)}}let hn=e=>e();function gn(){M.inBatch>0||M.isRunningReactions||hn(_n)}function _n(){M.isRunningReactions=!0;let e=M.pendingReactions,t=0;for(;e.length>0;){++t===100&&(console.error(`Reaction doesn't converge to a stable state after 100 iterations. Probably there is a cycle in the reactive function: ${e[0]}`),e.splice(0));let n=e.splice(0);for(let e=0,t=n.length;e<t;e++)n[e].runReaction_()}M.isRunningReactions=!1}let vn=b(`Reaction`,pn);function yn(e){let t=hn;hn=n=>e(()=>t(n))}function bn(){return!!M.spyListeners.length}function xn(e){if(!M.spyListeners.length)return;let t=M.spyListeners;for(let n=0,r=t.length;n<r;n++)t[n](e)}function Sn(e){xn(r({},e,{spyReportStart:!0}))}let Cn={type:`report-end`,spyReportEnd:!0};function wn(e){xn(e?r({},e,{type:`report-end`,spyReportEnd:!0}):Cn)}function Tn(e){return M.spyListeners.push(e),d(()=>{M.spyListeners=M.spyListeners.filter(t=>t!==e)})}let N=`action`,En=`autoAction`,Dn=`<unnamed action>`,On=ye(N),kn=ye(`action.bound`,{bound:!0}),An=ye(En,{autoAction:!0}),jn=ye(`autoAction.bound`,{autoAction:!0,bound:!0});function Mn(e){return qe(e,Se)}function Nn(e){return function(t,r){if(r&&typeof r.kind==`string`)return Se(e?An:On,t,r);if(p(t))return bt(t.name||Dn,t,e);if(p(r))return bt(t,r,e);if(m(t))return Mn(ye(e?En:N,{name:t,autoAction:e}));n("Invalid arguments for `action`")}}let Pn=Nn(!1);r(Pn,On);let Fn=Nn(!0);r(Fn,An);let In=Mn(kn),Ln=Mn(jn);function Rn(e){return xt(e.name||Dn,!1,e,this,void 0)}function zn(e){return p(e)&&e.isMobxAction===!0}function Bn(e,t=c){var r;p(e)||n(`Autorun expects a function as first argument`),zn(e)&&n(`Autorun does not accept actions since actions are untrackable`);let i=t?.name??(e.name||`Autorun@`+u()),a=!t.scheduler&&!t.delay,o;if(a)o=new pn(i,function(){this.track(s)},t.onError,t.requiresObservable);else{let e=Hn(t),n=!1;o=new pn(i,()=>{n||(n=!0,e(()=>{n=!1,o.isDisposed||o.track(s)}))},t.onError,t.requiresObservable)}function s(){e(o)}return t!=null&&(r=t.signal)!=null&&r.aborted||o.schedule_(),o.getDisposer_(t?.signal)}let Vn=e=>e();function Hn(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Vn}function Un(e,t,r=c){var i;(!p(e)||!p(t))&&n(`First and second argument to reaction should be functions`),g(r)||n(`Third argument of reactions should be an object`);let a=r.name??`Reaction@`+u(),o=Pn(a,r.onError?Wn(r.onError,t):t),s=!r.scheduler&&!r.delay,l=Hn(r),d=!0,f=!1,m,h=r.equals||le,_=new pn(a,()=>{d||s?v():f||(f=!0,l(v))},r.onError,r.requiresObservable);function v(){if(f=!1,_.isDisposed)return;let t=!1,n=m;_.track(()=>{let n=wt(!1,()=>e(_));t=d||!h(m,n),m=n}),(d&&r.fireImmediately||!d&&t)&&o(m,n,_),d=!1}return r!=null&&(i=r.signal)!=null&&i.aborted||_.schedule_(),_.getDisposer_(r?.signal)}function Wn(e,t){return function(){try{return t.apply(this,arguments)}catch(t){e.call(this,t)}}}function Gn(e,t,n){return qn(`onBO`,e,t,n)}function Kn(e,t,n){return qn(`onBUO`,e,t,n)}function qn(e,t,n,r){let i=typeof r==`function`?P(t,n):P(t),a=p(r)?r:n,o=`${e}L`;return i[o]?i[o].add(a):i[o]=new Set([a]),function(){let e=i[o];e&&(e.delete(a),e.size===0&&delete i[o])}}let Jn=`always`;function Yn(e){e.isolateGlobalState===!0&&Xt();let{enforceActions:t}=e;if(t!==void 0){let e=t===Jn?Jn:t===`observed`;M.enforceActions=e,M.allowStateChanges=!(e===!0||e===Jn)}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(M[t]=!!e[t])}),M.allowStateReads=!M.observableRequiresReaction,M.disableErrorBoundaries===!0&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),e.reactionScheduler&&yn(e.reactionScheduler)}function Xn(e,t,r,i){arguments.length>4&&n(`'extendObservable' expected 2-4 arguments`),typeof e!=`object`&&n(`'extendObservable' expects an object as first argument`),_i(e)&&n(`'extendObservable' should not be used on maps, use map.merge instead`),g(t)||n(`'extendObservable' only accepts plain objects as second argument`),(xr(t)||xr(r))&&n(`Extending an object with another observable (object) is not supported`);let a=te(t);return Fi(()=>{let t=Di(e,i)[A];T(a).forEach(e=>{t.extend_(e,a[e],r&&e in r?r[e]:!0)})}),e}function Zn(e,t){return Qn(P(e,t))}function Qn(e){let t={name:e.name_};return e.observing_&&e.observing_.length>0&&(t.dependencies=tr(e.observing_).map(Qn)),t}function $n(e,t){return er(P(e,t))}function er(e){let t={name:e.name_};return $t(e)&&(t.observers=Array.from(en(e),er)),t}function tr(e){return Array.from(new Set(e))}let nr=0;var rr=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};function ir(e){return e instanceof rr}function ar(e){return qe(e,Oe)}let or=Te(`flow`),sr=Te(`flow.bound`,{bound:!0}),cr=r(function(e,t){if(t&&typeof t.kind==`string`)return Oe(or,e,t);arguments.length!==1&&n(`Flow expects single argument with generator function`);let r=e,i=r.name||`<unnamed flow>`,a=function(){let e=this,t=arguments,n=++nr,a=Pn(`${i} - runid: ${n} - init`,r).apply(e,t),o,s,c=new Promise(function(e,t){let r=0;o=t;function c(e){s=void 0;let o;try{o=Pn(`${i} - runid: ${n} - yield ${r++}`,a.next).call(a,e)}catch(e){return t(e)}u(o)}function l(e){s=void 0;let o;try{o=Pn(`${i} - runid: ${n} - yield ${r++}`,a.throw).call(a,e)}catch(e){return t(e)}u(o)}function u(n){if(p(n?.then)){n.then(u,t);return}return n.done?e(n.value):(s=Promise.resolve(n.value),s.then(c,l))}c(void 0)});return c.cancel=Pn(`${i} - runid: ${n} - cancel`,function(){try{s&&ur(s);let e=a.return(void 0),t=Promise.resolve(e.value);t.then(f,f),ur(t),o(new rr)}catch(e){o(e)}}),c};return a.isMobXFlow=!0,a},or),lr=ar(sr);function ur(e){p(e.cancel)&&e.cancel()}function dr(e){return e}function fr(e){return e?.isMobXFlow===!0}function pr(e,t,r){let i;if(_i(e)||pi(e)||Ot(e))i=Ni(e);else if(Ai(e)){if(!m(t))return n(`InterceptReads can only be used with a specific property, not with an object in general`);i=Ni(e,t)}else return n(`Expected observable map, object or array as first array`);return i.dehancer===void 0?(i.dehancer=typeof t==`function`?t:r,()=>{i.dehancer=void 0}):n(`An intercept reader was already established`)}function mr(e,t,n){return p(n)?gr(e,t,n):hr(e,t)}function hr(e,t){return qr(Ni(e),t)}function gr(e,t,n){return qr(Ni(e,t),n)}function _r(e,t){var n;if(t===void 0)return At(e);if(Ai(e)===!1)return!1;let r=e[A];return(n=r.lazyComputedKeys_)!=null&&n.has(t)?!0:r.values_.has(t)?At(P(e,t)):!1}function vr(e){return arguments.length>1?n(`isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property`):_r(e)}function yr(e,t){return m(t)?_r(e,t):n(`isComputed expected a property name as second argument`)}function br(e,t){if(!e)return!1;if(t!==void 0){if(_i(e)||pi(e))return n(`isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.`);if(Ai(e)){var r,i;let n=e[A];return n.values_.has(t)||!!((r=n.lazyComputedKeys_)!=null&&r.has(t))||!!((i=n.lazyObservableKeys_)!=null&&i.has(t))}return!1}return Ai(e)||!!e[A]||ie(e)||vn(e)||At(e)}function xr(e){return arguments.length!==1&&n(`isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property`),br(e)}function Sr(e,t){return m(t)?br(e,t):n(`expected a property name as second argument`)}function Cr(e){if(Ai(e))return e[A].keys_();if(_i(e)||Si(e))return Array.from(e.keys());if(pi(e))return e.map((e,t)=>t);n(5)}function wr(e){if(Ai(e))return Cr(e).map(t=>e[t]);if(_i(e))return Cr(e).map(t=>e.get(t));if(Si(e))return Array.from(e.values());if(pi(e))return e.slice();n(6)}function Tr(e){if(Ai(e))return Cr(e).map(t=>[t,e[t]]);if(_i(e))return Cr(e).map(t=>[t,e.get(t)]);if(Si(e))return Array.from(e.entries());if(pi(e))return e.map((e,t)=>[t,e]);n(7)}function Er(e,t,r){if(arguments.length===2&&!Si(e)){an();let n=t;try{for(let t in n)Er(e,t,n[t])}finally{on()}return}Ai(e)?e[A].set_(t,r):_i(e)?e.set(t,r):Si(e)?e.add(t):pi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),t<0&&n(42,t),an(),t>=e.length&&(e.length=t+1),e[t]=r,on()):n(8)}function Dr(e,t){Ai(e)?e[A].delete_(t):_i(e)||Si(e)?e.delete(t):pi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),e.splice(t,1)):n(9)}function Or(e,t){if(Ai(e))return e[A].has_(t);if(_i(e)||Si(e))return e.has(t);if(pi(e))return t>=0&&t<e.length;n(10)}function kr(e,t){if(Or(e,t)){if(Ai(e))return e[A].get_(t);if(_i(e))return e.get(t);if(pi(e))return e[t];n(11)}}function Ar(e,t,r){if(Ai(e))return e[A].defineProperty_(t,r);n(39)}function jr(e){if(Ai(e))return e[A].ownKeys_();n(38)}function Mr(e,t,n,r){return p(n)?Pr(e,t,n,r):Nr(e,t,n)}function Nr(e,t,r){let i=Ni(e);if(pi(e))r&&t({observableKind:`array`,object:i.proxy_,debugObjectName:i.atom_.name_,type:`splice`,index:0,added:i.values_.slice(),addedCount:i.values_.length,removed:[],removedCount:0});else if(_i(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with maps.");else if(Si(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with sets.");else if(Ai(e))r===!0&&n("`observe` doesn't support the fire immediately property for observable objects.");else return Fr(i,t,r);return Xr(i,t)}function Pr(e,t,n,r){return Fr(Ni(e,t),n,r)}function Fr(e,t,n){if(At(e)){let r=!0,i;return Bn(()=>{let a=e.get();if(!r||n){let n=Ht();t({observableKind:`computed`,debugObjectName:e.name_,type:ri,object:e,newValue:a,oldValue:i}),Ut(n)}r=!1,i=a})}return n&&t({observableKind:`value`,debugObjectName:e.name_,object:e,type:ri,newValue:e.value_,oldValue:void 0}),Xr(e,t)}function Ir(e,t,n){return e.set(t,n),n}function Lr(e,t){if(typeof e!=`object`||!e||e instanceof Date||!xr(e))return e;if(Ot(e)||At(e))return Lr(e.get(),t);if(t.has(e))return t.get(e);if(pi(e)){let n=Ir(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=Lr(e,t)}),n}if(Si(e)){let n=Ir(t,e,new Set);return e.forEach(e=>{n.add(Lr(e,t))}),n}if(_i(e)){let n=Ir(t,e,new Map);return e.forEach((e,r)=>{n.set(r,Lr(e,t))}),n}else{let n=Ir(t,e,{});return jr(e).forEach(r=>{o.propertyIsEnumerable.call(e,r)&&(n[r]=Lr(e[r],t))}),n}}function Rr(e,t){return t&&n(`toJS no longer supports options`),Lr(e,new Map)}function zr(e,t=void 0){an();try{return e.apply(t)}finally{on()}}function Br(e,t,n){return arguments.length===1||t&&typeof t==`object`?Hr(e,t):Vr(e,t,n||{})}function Vr(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[A].isDisposed)if(a(),n.onError)n.onError(e);else throw e},n.timeout)}n.name=n.name||`When@`+u();let i=bt(n.name+`-effect`,t);var a=Bn(t=>{wt(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function Hr(e,t){var i;if(t&&t.onError)return n(`the options 'onError' and 'promise' cannot be combined`);if(t!=null&&(i=t.signal)!=null&&i.aborted)return r(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let a,o,s=new Promise((n,i)=>{var s;let c=Vr(e,n,r({},t,{onError:i}));a=()=>{c(),i(Error(`WHEN_CANCELLED`))},o=()=>{c(),i(Error(`WHEN_ABORTED`))},t==null||(s=t.signal)==null||s.addEventListener==null||s.addEventListener(`abort`,o)}).finally(()=>{var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,o)});return s.cancel=a,s}function Ur(e){return e[A]}let Wr={has(e,t){return Ur(e).has_(t)},get(e,t){return Ur(e).get_(t)},set(e,t,n){return m(t)?Ur(e).set_(t,n,!0)??!0:!1},deleteProperty(e,t){return m(t)?Ur(e).delete_(t,!0)??!0:!1},defineProperty(e,t,n){return Ur(e).defineProperty_(t,n)??!0},ownKeys(e){return Ur(e).ownKeys_()},preventExtensions(e){n(13)}};function Gr(e,t){var n;return e=Di(e,t),(n=e[A]).proxy_??(n.proxy_=new Proxy(e,Wr))}function Kr(e){return e.interceptors_!==void 0&&e.interceptors_.length>0}function qr(e,t){let n=e.interceptors_;return n?n.push(t):n=e.interceptors_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Jr(e,t){let r=Ht();try{let r=[...e.interceptors_||[]];for(let e=0,i=r.length;e<i&&(t=r[e](t),t&&!t.type&&n(14),t);e++);return t}finally{Ut(r)}}function Yr(e){return e.changeListeners_!==void 0&&e.changeListeners_.length>0}function Xr(e,t){let n=e.changeListeners_;return n?n.push(t):n=e.changeListeners_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Zr(e,t){let n=Ht(),r=e.changeListeners_;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Ut(n)}}function Qr(e,t,n){return Fi(()=>{let r=Di(e,n)[A];T(t).forEach(e=>ti(r,e,t[e]))}),e}let $r=Symbol(`mobx-keys`);function ei(e,t,r){return!g(e)&&!g(Object.getPrototypeOf(e))&&n(`'makeAutoObservable' can only be used for classes that don't have a superclass`),Ai(e)&&n(`makeAutoObservable can only be used on objects not already made observable`),g(e)?Xn(e,e,t,r):(Fi(()=>{let n=Di(e,r)[A];if(!e[$r]){let t=Object.getPrototypeOf(e),n=new Set([...T(e),...T(t)]);n.delete(`constructor`),n.delete(A),v(t,$r,n)}e[$r].forEach(e=>ti(n,e,t&&e in t?t[e]:!0))}),e)}function ti(e,t,r){if(r===!0&&(r=e.defaultAnnotation_),r===!1)return;Mi(e,r,t),t in e.target_||n(1,r.annotationType_,`${e.name_}.${t.toString()}`);let a=e.target_;for(;a&&a!==o;){let n=i(a,t);if(n){let i=r.make_(e,t,n,a);if(i===0)return;if(i===1)break}a=Object.getPrototypeOf(a)}ji(e,r,t)}let ni=`splice`,ri=`update`,ii={get(e,t){let n=e[A];return t===A?n:t===`length`?n.getArrayLength_():typeof t==`string`&&!isNaN(t)?n.get_(parseInt(t)):D(si,t)?si[t]:e[t]},set(e,t,n){let r=e[A];return t===`length`?r.setArrayLength_(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.set_(parseInt(t),n),!0},preventExtensions(){n(15)}};var ai=class{constructor(e=`ObservableArray@`+u(),t,n){this.owned_=void 0,this.atom_=void 0,this.values_=[],this.interceptors_=void 0,this.changeListeners_=void 0,this.enhancer_=void 0,this.dehancer=void 0,this.proxy_=void 0,this.lastKnownLength_=0,this.owned_=n,this.atom_=new re(e),this.enhancer_=(n,r)=>t(n,r,e+`[..]`)}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}dehanceValues_(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e}getArrayLength_(){return this.atom_.reportObserved(),this.values_.length}setArrayLength_(e){(!Number.isInteger(e)||e<0)&&n(40,e);let t=this.values_.length;if(e!==t)if(e>t){let n=Array.from({length:e-t});this.spliceWithArray_(t,0,n)}else this.spliceWithArray_(e,t-e)}updateArrayLength_(e,t){e!==this.lastKnownLength_&&n(16),this.lastKnownLength_+=t}spliceWithArray_(e,t,n){Ft(this.atom_);let r=this.values_.length;if(e===void 0?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=arguments.length===1?r-e:t==null?0:Math.max(0,Math.min(t,r-e)),n===void 0&&(n=s),Kr(this)){let r=Jr(this,{object:this.proxy_,type:ni,index:e,removedCount:t,added:n});if(!r)return s;t=r.removedCount,n=r.added}n=n.length===0?n:n.map(e=>this.enhancer_(e,void 0));{let e=n.length-t;this.updateArrayLength_(r,e)}let i=this.spliceItemsIntoValues_(e,t,n);return(t!==0||n.length!==0)&&this.notifyArraySplice_(e,n,i),this.dehanceValues_(i)}spliceItemsIntoValues_(e,t,n){if(n.length<1e4)return this.values_.splice(e,t,...n);{let r=this.values_.slice(e,e+t),i=this.values_.slice(e+t);this.values_.length+=n.length-t;for(let t=0;t<n.length;t++)this.values_[e+t]=n[t];for(let t=0;t<i.length;t++)this.values_[e+n.length+t]=i[t];return r}}notifyArrayChildUpdate_(e,t,n){let r=!this.owned_&&bn(),i=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,type:ri,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(this,a),r&&wn()}notifyArraySplice_(e,t,n){let r=!this.owned_&&bn(),i=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,debugObjectName:this.atom_.name_,type:ni,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(this,a),r&&wn()}get_(e){return this.atom_.reportObserved(),this.dehanceValue_(this.values_[e])}set_(e,t){let n=this.values_;if(e<n.length){Ft(this.atom_);let r=n[e];if(Kr(this)){let n=Jr(this,{type:ri,object:this.proxy_,index:e,newValue:t});if(!n)return;t=n.newValue}t=this.enhancer_(t,r),t!==r&&(n[e]=t,this.notifyArrayChildUpdate_(e,t,r))}else{let r=Array.from({length:e+1-n.length});r[r.length-1]=t,this.spliceWithArray_(n.length,0,r)}}};function oi(e,t,n=`ObservableArray@`+u(),r=!1){return Fi(()=>{let i=new ai(n,t,r);y(i.values_,A,i);let a=new Proxy(i.values_,ii);return i.proxy_=a,e&&e.length&&i.spliceWithArray_(0,0,e),a})}var si={clear(){return this.splice(0)},replace(e){let t=this[A];return t.spliceWithArray_(0,t.values_.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[A];switch(arguments.length){case 0:return[];case 1:return r.spliceWithArray_(e);case 2:return r.spliceWithArray_(e,t)}return r.spliceWithArray_(e,t,n)},spliceWithArray(e,t,n){return this[A].spliceWithArray_(e,t,n)},push(...e){let t=this[A];return t.spliceWithArray_(t.values_.length,0,e),t.values_.length},pop(){return this.splice(Math.max(this[A].values_.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[A];return t.spliceWithArray_(0,0,e),t.values_.length},reverse(){return M.trackingDerivation&&n(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){M.trackingDerivation&&n(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[A],n=t.dehanceValues_(t.values_).indexOf(e);return n>-1?(this.splice(n,1),!0):!1}};ci(`at`,li),ci(`concat`,li),ci(`flat`,li),ci(`includes`,li),ci(`indexOf`,li),ci(`join`,li),ci(`lastIndexOf`,li),ci(`slice`,li),ci(`toString`,li),ci(`toLocaleString`,li),ci(`toSorted`,li),ci(`toSpliced`,li),ci(`with`,li),ci(`every`,ui),ci(`filter`,ui),ci(`find`,ui),ci(`findIndex`,ui),ci(`findLast`,ui),ci(`findLastIndex`,ui),ci(`flatMap`,ui),ci(`forEach`,ui),ci(`map`,ui),ci(`some`,ui),ci(`toReversed`,ui),ci(`reduce`,di),ci(`reduceRight`,di);function ci(e,t){typeof Array.prototype[e]==`function`&&(si[e]=t(e))}function li(e){return function(){let t=this[A];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_);return n[e].apply(n,arguments)}}function ui(e){return function(t,n){let r=this[A];return r.atom_.reportObserved(),r.dehanceValues_(r.values_)[e]((e,r)=>t.call(n,e,r,this))}}function di(e){return function(){let t=this[A];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_),r=arguments[0];return arguments[0]=(e,t,n)=>r(e,t,n,this),n[e].apply(n,arguments)}}let fi=b(`ObservableArrayAdministration`,ai);function pi(e){return h(e)&&fi(e[A])}let mi={},hi=`delete`;var gi=class{constructor(e,t=ue,n=`ObservableMap@`+u()){this.enhancer_=void 0,this.name_=void 0,this[A]=mi,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,Fi(()=>{this.keysAtom_=ae(`${this.name_}.keys()`),this.data_=new Map,this.hasMap_=new Map,e&&this.merge(e)})}has_(e){return this.data_.has(e)}has(e){if(!M.trackingDerivation)return this.has_(e);let t=this.hasMap_.get(e);if(!t){let n=t=new Dt(this.has_(e),fe,`${this.name_}.${E(e)}?`,!1);this.hasMap_.set(e,n),n.onBUOL=new Set([()=>this.hasMap_.delete(e)])}return t.get()}set(e,t){let n=this.has_(e);if(Kr(this)){let r=Jr(this,{type:n?ri:`add`,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.updateValue_(e,t):this.addValue_(e,t),this}delete(e){if(Ft(this.keysAtom_),Kr(this)&&!Jr(this,{type:hi,object:this,name:e}))return!1;if(this.has_(e)){let t=bn(),n=Yr(this),r=n||t?{observableKind:`map`,debugObjectName:this.name_,type:hi,object:this,oldValue:this.data_.get(e).value_,name:e}:null;return t&&Sn(r),zr(()=>{var t;this.keysAtom_.reportChanged(),(t=this.hasMap_.get(e))==null||t.setNewValue_(!1),this.data_.get(e).setNewValue_(void 0),this.data_.delete(e)}),n&&Zr(this,r),t&&wn(),!0}return!1}updateValue_(e,t){let n=this.data_.get(e);if(t=n.prepareNewValue_(t),t!==M.UNCHANGED){let r=bn(),i=Yr(this),a=i||r?{observableKind:`map`,debugObjectName:this.name_,type:ri,object:this,oldValue:n.value_,name:e,newValue:t}:null;r&&Sn(a),n.setNewValue_(t),i&&Zr(this,a),r&&wn()}}addValue_(e,t){Ft(this.keysAtom_),zr(()=>{var n;let r=new Dt(t,this.enhancer_,`${this.name_}.${E(e)}`,!1);this.data_.set(e,r),t=r.value_,(n=this.hasMap_.get(e))==null||n.setNewValue_(!0),this.keysAtom_.reportChanged()});let n=bn(),r=Yr(this),i=r||n?{observableKind:`map`,debugObjectName:this.name_,type:`add`,object:this,name:e,newValue:t}:null;n&&Sn(i),r&&Zr(this,i),n&&wn()}get(e){return this.has(e)?this.dehanceValue_(this.data_.get(e).get()):this.dehanceValue_(void 0)}getOrInsert(e,t){return this.has(e)||this.set(e,t),this.get(e)}getOrInsertComputed(e,t){return this.has(e)||this.set(e,t(e)),this.get(e)}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}keys(){return this.keysAtom_.reportObserved(),this.data_.keys()}values(){let e=this,t=this.keys();return vi({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:e.get(r)}}})}entries(){let e=this,t=this.keys();return vi({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:[r,e.get(r)]}}})}[Symbol.iterator](){return this.entries()}forEach(e,t){for(let[n,r]of this)e.call(t,r,n,this)}merge(e){return _i(e)&&(e=new Map(e)),zr(()=>{g(e)?w(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):x(e)?(S(e)||n(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&n(20,e)}),this}clear(){zr(()=>{Vt(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return zr(()=>{let t=yi(e),n=new Map,r=!1;for(let e of this.data_.keys())if(!t.has(e))if(this.delete(e))r=!0;else{let t=this.data_.get(e);n.set(e,t)}for(let[e,i]of t.entries()){let t=this.data_.has(e);if(this.set(e,i),this.data_.has(e)){let i=this.data_.get(e);n.set(e,i),t||(r=!0)}}if(!r)if(this.data_.size!==n.size)this.keysAtom_.reportChanged();else{let e=this.data_.keys(),t=n.keys(),r=e.next(),i=t.next();for(;!r.done;){if(r.value!==i.value){this.keysAtom_.reportChanged();break}r=e.next(),i=t.next()}}this.data_=n}),this}get size(){return this.keysAtom_.reportObserved(),this.data_.size}toString(){return`[object ObservableMap]`}toJSON(){return Array.from(this)}get[Symbol.toStringTag](){return`Map`}},_i=b(`ObservableMap`,gi);function vi(e){return e[Symbol.toStringTag]=`MapIterator`,Vi(e)}function yi(e){if(x(e)||_i(e))return e;if(Array.isArray(e))return new Map(e);if(g(e)){let t=new Map;for(let n in e)t.set(n,e[n]);return t}else return n(21,e)}let bi={};var xi=class{constructor(e,t=ue,n=`ObservableSet@`+u()){this.name_=void 0,this[A]=bi,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,this.enhancer_=(e,r)=>t(e,r,n),Fi(()=>{this.atom_=ae(this.name_),e&&this.replace(e)})}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){zr(()=>{Vt(()=>{for(let e of this.data_.values())this.delete(e)})})}forEach(e,t){for(let n of this)e.call(t,n,n,this)}get size(){return this.atom_.reportObserved(),this.data_.size}add(e){if(Ft(this.atom_),Kr(this)){let t=Jr(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){zr(()=>{e=this.enhancer_(e,void 0),this.data_.add(e),this.atom_.reportChanged()});let t=bn(),n=Yr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:`add`,object:this,newValue:e}:null;t&&Sn(r),n&&Zr(this,r),t&&wn()}return this}delete(e){if(Kr(this)&&!Jr(this,{type:hi,object:this,oldValue:e}))return!1;if(this.has(e)){let t=bn(),n=Yr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:hi,object:this,oldValue:e}:null;return t&&Sn(r),zr(()=>{this.atom_.reportChanged(),this.data_.delete(e)}),n&&Zr(this,r),t&&wn(),!0}return!1}has(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))}entries(){let e=this.values();return Ci({next(){let{value:t,done:n}=e.next();return n?{value:void 0,done:n}:{value:[t,t],done:n}}})}keys(){return this.values()}values(){this.atom_.reportObserved();let e=this,t=this.data_.values();return Ci({next(){let{value:n,done:r}=t.next();return r?{value:void 0,done:r}:{value:e.dehanceValue_(n),done:r}}})}intersection(e){return new Set(this).intersection(e)}union(e){return new Set(this).union(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}replace(e){return Si(e)&&(e=new Set(e)),Array.isArray(e)||C(e)?zr(()=>{let t=C(e)?e:new Set(e);if(t.size===0){this.clear();return}if(this.data_.size===0){t.forEach(e=>this.add(e));return}for(let e of this.data_.values())t.has(this.dehanceValue_(e))||this.delete(e);t.forEach(e=>this.add(e))}):e!=null&&n(41,e),this}toJSON(){return Array.from(this)}toString(){return`[object ObservableSet]`}[Symbol.iterator](){return this.values()}get[Symbol.toStringTag](){return`Set`}},Si=b(`ObservableSet`,xi);function Ci(e){return e[Symbol.toStringTag]=`SetIterator`,Vi(e)}let wi=Object.create(null),Ti=`remove`;var Ei=class{constructor(e,t=new Map,r,i=Ve){this.target_=void 0,this.values_=void 0,this.name_=void 0,this.defaultAnnotation_=void 0,this.keysAtom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.proxy_=void 0,this.isPlainObject_=void 0,this.appliedAnnotations_=void 0,this.pendingKeys_=void 0,this.lazyComputedKeys_=void 0,this.lazyObservableKeys_=void 0,this.target_=e,this.values_=t,this.name_=r,this.defaultAnnotation_=i,this.keysAtom_=new re(`${this.name_}.keys`),this.isPlainObject_=g(this.target_),Ui(this.defaultAnnotation_)||n(`defaultAnnotation must be valid annotation`),this.appliedAnnotations_={}}getObservablePropValue_(e){return(this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e)).get()}materializeLazyComputed_(e){let t=this.lazyComputedKeys_?.get(e);if(!t)return;this.lazyComputedKeys_.delete(e),this.lazyComputedKeys_.size===0&&(this.lazyComputedKeys_=void 0);let n=t();return this.values_.set(e,n),n}materializeLazyObservable_(e){let t=this.lazyObservableKeys_?.get(e);if(!t)return;this.lazyObservableKeys_.delete(e),this.lazyObservableKeys_.size===0&&(this.lazyObservableKeys_=void 0);let n=t();return this.values_.set(e,n),n}setObservablePropValue_(e,t){let n=this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e);if(n instanceof kt)return n.set(t),!0;if(Kr(this)){let n=Jr(this,{type:ri,object:this.proxy_||this.target_,name:e,newValue:t});if(!n)return null;t=n.newValue}if(t=n.prepareNewValue_(t),t!==M.UNCHANGED){let r=Yr(this),i=bn(),a=r||i?{type:ri,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,oldValue:n.value_,name:e,newValue:t}:null;i&&Sn(a),n.setNewValue_(t),r&&Zr(this,a),i&&wn()}return!0}get_(e){return M.trackingDerivation&&!D(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return D(this.target_,e)?this.values_.has(e)?this.setObservablePropValue_(e,t):n?Reflect.set(this.target_,e,t):(this.target_[e]=t,!0):this.extend_(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.defaultAnnotation_,n)}has_(e){if(!M.trackingDerivation)return e in this.target_;this.pendingKeys_||=new Map;let t=this.pendingKeys_.get(e);return t||(t=new Dt(e in this.target_,fe,`${this.name_}.${E(e)}?`,!1),this.pendingKeys_.set(e,t)),t.get()}extend_(e,t,n,r=!1){if(n===!0&&(n=this.defaultAnnotation_),n===!1)return this.defineProperty_(e,t,r);Mi(this,n,e);let i=n.extend_(this,e,t,r);return i&&ji(this,n,e),i}defineProperty_(e,t,n=!1){Ft(this.keysAtom_);try{an();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=Jr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t.value});if(!n)return null;let{newValue:i}=n;t.value!==i&&(t=r({},t,{value:i}))}if(n){if(!Reflect.defineProperty(this.target_,e,t))return!1}else a(this.target_,e,t);this.notifyPropertyAddition_(e,t.value)}finally{on()}return!0}defineObservableProperty_(e,t,n,r=!1){Ft(this.keysAtom_);try{an();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=Jr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let o=ki(e),s={configurable:M.safeDescriptors?this.isPlainObject_:!0,enumerable:!0,get:o.get,set:o.set};if(r){if(!Reflect.defineProperty(this.target_,e,s))return!1}else a(this.target_,e,s);let c=new Dt(t,n,`${this.name_}.${e.toString()}`,!1);this.values_.set(e,c),this.notifyPropertyAddition_(e,c.value_)}finally{on()}return!0}defineComputedProperty_(e,t,n=!1){Ft(this.keysAtom_);try{an();let r=this.delete_(e);if(!r)return r;if(Kr(this)&&!Jr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:void 0}))return null;t.name||=`${this.name_}.${e.toString()}`,t.context=this.proxy_||this.target_;let i=ki(e),o={configurable:M.safeDescriptors?this.isPlainObject_:!0,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.target_,e,o))return!1}else a(this.target_,e,o);this.values_.set(e,new kt(t)),this.notifyPropertyAddition_(e,void 0)}finally{on()}return!0}delete_(e,t=!1){if(Ft(this.keysAtom_),!D(this.target_,e))return!0;if(Kr(this)&&!Jr(this,{object:this.proxy_||this.target_,name:e,type:Ti}))return null;try{var n;an();let r=Yr(this),a=bn(),o=this.values_.get(e),s;if(!o&&(r||a)&&(s=i(this.target_,e)?.value),t){if(!Reflect.deleteProperty(this.target_,e))return!1}else delete this.target_[e];if(delete this.appliedAnnotations_[e],o&&(this.values_.delete(e),o instanceof Dt&&(s=o.value_),un(o)),this.keysAtom_.reportChanged(),(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(e in this.target_),r||a){let t={type:Ti,observableKind:`object`,object:this.proxy_||this.target_,debugObjectName:this.name_,oldValue:s,name:e};a&&Sn(t),r&&Zr(this,t),a&&wn()}}finally{on()}return!0}notifyPropertyAddition_(e,t){var n;let r=Yr(this),i=bn();if(r||i){let n=r||i?{type:`add`,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,name:e,newValue:t}:null;i&&Sn(n),r&&Zr(this,n),i&&wn()}(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(!0),this.keysAtom_.reportChanged()}ownKeys_(){return this.keysAtom_.reportObserved(),T(this.target_)}keys_(){return this.keysAtom_.reportObserved(),Object.keys(this.target_)}};function Di(e,t){if(t&&Ai(e)&&n(`Options can't be provided for already observable objects.`),D(e,A))return Ni(e)instanceof Ei||n(`Cannot convert '${Pi(e)}' into observable object:\nThe target is already observable of different type.\nExtending builtins is not supported.`),e;Object.isExtensible(e)||n(`Cannot make the designated object observable; it is not extensible`);let r=t?.name??`${g(e)?`ObservableObject`:e.constructor.name}@${u()}`;return v(e,A,new Ei(e,new Map,String(r),nt(t))),e}let Oi=b(`ObservableObjectAdministration`,Ei);function ki(e){return wi[e]||(wi[e]={get(){return this[A].getObservablePropValue_(e)},set(t){return this[A].setObservablePropValue_(e,t)}})}function Ai(e){return h(e)?Oi(e[A]):!1}function ji(e,t,n){e.appliedAnnotations_[n]=t}function Mi(e,t,r){if(Ui(t)||n(`Cannot annotate '${e.name_}.${r.toString()}': Invalid annotation.`),!ge(t)&&D(e.appliedAnnotations_,r)){let i=`${e.name_}.${r.toString()}`,a=e.appliedAnnotations_[r].annotationType_,o=t.annotationType_;n(`Cannot apply '${o}' to '${i}':\nThe field is already annotated with '${a}'.\nRe-annotating fields is not allowed.\nUse 'override' annotation for methods overridden by subclass.`)}}function P(e,t){if(typeof e==`object`&&e){if(pi(e))return t!==void 0&&n(23),e[A].atom_;if(Si(e))return e.atom_;if(_i(e)){if(t===void 0)return e.keysAtom_;let r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,Pi(e)),r}if(Ai(e)){if(!t)return n(26);let r=e[A],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,Pi(e)),i}if(ie(e)||At(e)||vn(e))return e}else if(p(e)&&vn(e[A]))return e[A];n(28)}function Ni(e,t){if(e||n(29),t!==void 0)return Ni(P(e,t));if(ie(e)||At(e)||vn(e)||_i(e)||Si(e))return e;if(e[A])return e[A];n(24,e)}function Pi(e,t){let n;if(t!==void 0)n=P(e,t);else if(zn(e))return e.name;else n=Ai(e)||_i(e)||Si(e)?Ni(e):P(e);return n.name_}function Fi(e){let t=Ht(),n=Tt(!0);an();try{return e()}finally{on(),Et(n),Ut(t)}}let Ii=o.toString;function Li(e,t,n=-1){return Ri(e,t,n)}function Ri(e,t,n,r,i){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!==e)return t!==t;let a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;let o=Ii.call(e);if(o!==Ii.call(t))return!1;switch(o){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++;break}e=zi(e),t=zi(t);let s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;let n=e.constructor,r=t.constructor;if(n!==r&&!(p(n)&&n instanceof n&&p(r)&&r instanceof r)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];let c=r.length;for(;c--;)if(r[c]===e)return i[c]===t;if(r.push(e),i.push(t),s){if(c=e.length,c!==t.length)return!1;for(;c--;)if(!Ri(e[c],t[c],n-1,r,i))return!1}else{let a=Object.keys(e),o=a.length;if(Object.keys(t).length!==o)return!1;for(let s=0;s<o;s++){let o=a[s];if(!(D(t,o)&&Ri(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function zi(e){return pi(e)?e.slice():x(e)||_i(e)||C(e)||Si(e)?Array.from(e.entries()):e}let Bi=globalThis.Iterator?.prototype||{};function Vi(e){return e[Symbol.iterator]=Hi,r(Object.create(Bi),e)}function Hi(){return this}function Ui(e){return e instanceof Object&&typeof e.annotationType_==`string`&&p(e.make_)&&p(e.extend_)}{let e=globalThis;[`Symbol`,`Map`,`Set`,`Proxy`].forEach(t=>{e[t]===void 0&&n(`MobX requires global '${t}' to be available or polyfilled`)})}typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Tn,extras:{getDebugName:Pi},$mobx:A}),e.$mobx=A,e.FlowCancellationError=rr,e.ObservableMap=gi,e.ObservableSet=xi,e.Reaction=pn,e._allowStateChanges=wt,e._allowStateChangesInsideComputed=Rn,e._allowStateReadsEnd=Wt,e._allowStateReadsStart=j,e._autoAction=Fn,e._autoActionBound=Ln,e._endAction=Ct,e._getAdministration=Ni,e._getGlobalState=Zt,e._interceptReads=pr,e._isComputingDerivation=Pt,e._resetGlobalState=Qt,e._startAction=St,e.action=Pn,e.actionBound=In,e.autorun=Bn,e.compareDefault=le,e.compareIdentity=oe,e.compareShallow=ce,e.compareStructural=se,e.computed=ht,e.computedStruct=mt,e.configure=Yn,e.createAtom=ae,e.defineProperty=Ar,e.entries=Tr,e.extendObservable=Xn,e.flow=cr,e.flowBound=lr,e.flowResult=dr,e.get=kr,e.getAtom=P,e.getDebugName=Pi,e.getDependencyTree=Zn,e.getObserverTree=$n,e.has=Or,e.intercept=mr,e.isAction=zn,e.isBoxedObservable=Ot,e.isComputed=vr,e.isComputedProp=yr,e.isFlow=fr,e.isFlowCancellationError=ir,e.isObservable=xr,e.isObservableArray=pi,e.isObservableMap=_i,e.isObservableObject=Ai,e.isObservableProp=Sr,e.isObservableSet=Si,e.keys=Cr,e.makeAutoObservable=ei,e.makeObservable=Qr,e.observable=ut,e.observableDeep=ct,e.observableRef=ot,e.observableShallow=st,e.observableStruct=lt,e.observe=Mr,e.onBecomeObserved=Gn,e.onBecomeUnobserved=Kn,e.onReactionError=mn,e.override=he,e.ownKeys=jr,e.reaction=Un,e.remove=Dr,e.runInAction=Rn,e.set=Er,e.spy=Tn,e.toJS=Rr,e.transaction=zr,e.untracked=Vt,e.values=wr,e.when=Br})),X=De(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=lw():t.exports=uw()}))();function dw(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(dw);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(dw)}default:return!1}}function fw(e){if(Array.isArray(e))return Object.freeze(e.map(fw));if(typeof e==`object`&&e){let t=Object.create(null),n=Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t));for(let[e,r]of n)t[e]=fw(r);return Object.freeze(t)}return e}function pw(e){let t=typeof e;if(t===`string`||t===`number`||t===`boolean`)return t;throw TypeError(`Variable values must be string|number|boolean (got ${t})`)}function mw(e){return typeof e==`string`?e:String(e)}function hw(e){if(typeof e==`number`)return e;if(typeof e==`boolean`)return+!!e;let t=e.trim();if(t===``)throw TypeError(`Cannot cast empty string to number`);let n=Number(t);if(!Number.isFinite(n))throw TypeError(`Cannot cast ${JSON.stringify(e)} to number`);return n}function gw(e){if(typeof e==`boolean`)return e;if(typeof e==`number`){if(e===0||e===1)return e===1;throw TypeError(`Cannot cast number ${e} to bool (only 0 and 1 are accepted)`)}if(e===`true`)return!0;if(e===`false`)return!1;throw TypeError(`Cannot cast ${JSON.stringify(e)} to bool (expected "true" or "false")`)}var _w=class extends Error{constructor(e,t){super(t),this.variable=e}};function vw(e){return e instanceof _w?e:e instanceof Error&&e.cause!==void 0?vw(e.cause):void 0}const yw=e=>Eo(e);var bw=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n,r){this.name=e,this.type=t,this.clock=r,yw(n)||Aw(e,t,n,`initial value`),this.cell=X.observable.box(n,{deep:!1}),this.lastChangedAt=yw(n)?null:r.now()}read(){let e=this.cell.get();if(yw(e))throw new _w(this.name,`variable "${this.name}" has no value yet: nothing has written it`);return e}set(e){yw(e)||Aw(this.name,this.type,e,`set value`),!(0,X.compareStructural)(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}stored(){return this.cell.get()}},xw=class{cell;constructor(e,t,n){if(this.cell=(0,X.computed)(t,{keepAlive:!0,...n!==void 0&&{equals:n}}),typeof this.cell.suspend_!=`function`)throw TypeError(`${e}: this MobX's computed has no suspend_; release() cannot unsubscribe it`);if(typeof this.cell.keepAlive_!=`boolean`)throw TypeError(`${e}: this MobX's computed has no keepAlive_ flag; release() cannot lift it`)}read(){return this.cell.get()}release(){this.cell.keepAlive_=!1,this.cell.suspend_()}},Sw=class{constructor(e){this.deriver=e}read(){return this.deriver()}},Cw=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new xw(`Variable "${e}"`,()=>{let e=n();return Aw(this.name,this.type,e,`computed result`),e})}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}},ww=class{kind=`projection`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new Sw(()=>{let e=n();return Aw(this.name,this.type,e,`projection result`),e})}read(){return this.cell.read()}lastUpdatedMs(){return null}},Tw=class{kind=`document`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.clock=n,this.cell=X.observable.box(kw(t),{deep:!1}),this.lastChangedAt=t.kind===`pending`?null:n.now()}read(){return this.cell.get()}set(e){let t=kw(e);Ow(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}},Ew=class{kind=`document`;cell;constructor(e,t){this.name=e,this.cell=new xw(`Variable "${e}"`,()=>kw(t()),Ow)}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}};function Dw(e){return JSON.stringify(e)}function Ow(e,t){return Dw(e)===Dw(t)}function kw(e){return e.kind===`ok`?{kind:`ok`,value:fw(e.value)}:e}function Aw(e,t,n,r){let i=pw(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var jw=class{constructor(e,t=null){this.clock=e,this.parent=t}nodes=X.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new bw(e,t,n,this.clock))}defineDocument(e,t){this.declare(e,new Tw(e,t,this.clock))}defineDerivedDocument(e,t){this.declare(e,new Ew(e,t))}defineComputed(e,t,n){this.defineDerived(e,t,`computed`,n)}defineDerived(e,t,n,r){let i=e=>this.read(e),a=n===`computed`?Cw:ww;this.declare(e,new a(e,t,()=>r(i)))}derive(e,t,n){if(this.refuseDisposed(`Derived value "${e}"`),t===`projection`)return new Sw(n);let r=new xw(`Derived value "${e}"`,n);return this.kept.push(r),r}kept=[];read(e){return this.requireVar(e).read()}readDocument(e){let t=this.requireNode(e);if(t.kind!==`document`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a document`);return t.read()}stored(e){let t=this.requireNode(e);if(t.kind===`document`)return t.read();if(t.kind!==`box`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a written node`);return t.stored()}setDocument(e,t){let n=this.requireOwn(e);if(!(n instanceof Tw))throw TypeError(n.kind===`document`?`Variable "${e}" is a derived document: what it reads decides it, and nothing writes it`:`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,X.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireOwn(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,X.runInAction)(()=>n.set(t))}runInAction(e){(0,X.runInAction)(e)}has(e){return this.nodes.has(e)||(this.parent?.has(e)??!1)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`){let e=t.read();return e.kind===`pending`?e:F(Dw(e))}try{return F(String(t.read()))}catch(e){return vw(e)===void 0?F(` failed:${e instanceof Error?e.message:String(e)}`):So(`unread`)}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.parent?.names()??[],...this.nodes.keys()]}dispose(){if(this.disposed)return 0;this.disposed=!0;let e=0;return(0,X.runInAction)(()=>{for(let t of this.nodes.values())(t instanceof Cw||t instanceof Ew)&&(t.release(),e++);for(let e of this.kept)e.release()}),e+this.kept.length}disposed=!1;requireNode(e){let t=this.nodes.get(e)??this.parent?.requireNode(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireOwn(e){let t=this.nodes.get(e);if(t!==void 0)return t;throw this.parent?.has(e)?Error(`Variable "${e}" lives in the directory's store; a session's view cannot write it`):ReferenceError(`Unknown variable "${e}"`)}requireVar(e){let t=this.requireNode(e);if(t.kind===`document`)throw TypeError(`Variable "${e}" is a document; read its fields by path (.${e}.<field>)`);return t}refuseDisposed(e){if(this.disposed)throw Error(`${e}: cannot declare on a disposed store`)}declare(e,t){if(this.refuseDisposed(`Variable "${e}"`),this.has(e))throw Error(`Variable "${e}" is already declared`);(0,X.runInAction)(()=>this.nodes.set(e,t))}},Mw=class extends Error{name=`TemplateError`;kind=`EvalError`;pos;source;constructor(e,t,n={}){super(e,{cause:n.cause}),this.pos=t,this.source=n.source}get sourceSnippet(){return this.source?Vw(this.source,this.pos):``}toString(){let e=`${this.name}: ${this.message}\n at line ${this.pos.line}, column ${this.pos.column}`,t=this.sourceSnippet;return t?`${e}\n\n${t}`:e}},Nw=class extends Mw{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},Pw=class extends Mw{name=`EvalError`;kind=`EvalError`},Fw=class extends Pw{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=Hw(e,n.available??[]),i=r.length===0?``:` (did you mean: ${r.join(`, `)}?)`;super(`function ${JSON.stringify(e)} is not registered${i}`,t,n),this.funcName=e,this.suggestions=r}},Iw=class extends Pw{name=`ArgCountError`;kind=`ArgCountError`;funcName;accepted;got;constructor(e,t,n,r,i={}){let a=t.minimum===t.maximum?`${t.minimum}`:`at least ${t.minimum}`;super(`wrong number of args for ${e}: want ${a} got ${n}`,r,i),this.funcName=e,this.accepted=t,this.got=n}},Lw=class extends Pw{name=`TypeMismatchError`;kind=`TypeMismatchError`;funcName;argIndex;expected;receivedSummary;constructor(e,t,n,r,i,a={}){super(`function ${JSON.stringify(e)} arg ${t}: expected ${n}, but a ${r} flowed in. Pass it through \`unstyled\` (or your engine's flatten function) to convert.`,i,a),this.funcName=e,this.argIndex=t,this.expected=n,this.receivedSummary=r}},Rw=class extends Lw{constructor(e,t,n,r,i={}){super(e,t,`integer`,String(n),r,i),this.message=Number.isInteger(Number(n))?`integer out of range: ${String(n)}`:`expected integer; found ${String(n)}`}},zw=class extends Pw{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},Bw=class extends Pw{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function Vw(e,t){let n=e.split(`
59
59
  `),r=t.line-1,i=[];if(r-1>=0&&r-1<n.length&&i.push({num:r,text:n[r-1]??``}),r>=0&&r<n.length&&i.push({num:r+1,text:n[r]??``}),r+1<n.length&&i.push({num:r+2,text:n[r+1]??``}),i.length===0)return``;let a=String(i[i.length-1]?.num??1).length,o=[];for(let e of i)if(o.push(` ${String(e.num).padStart(a,` `)} | ${e.text}`),e.num===t.line){let e=` ${` `.repeat(a)} | `,n=` `.repeat(Math.max(0,t.column-1));o.push(`${e}${n}^`)}return o.join(`
60
- `)}function Uw(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:Ww(e,t)})).sort((e,t)=>e.dist-t.dist),r=Math.max(2,Math.floor(e.length/2));return n.filter(e=>e.dist<=r).slice(0,3).map(e=>e.name)}function Ww(e,t){if(e===t)return 0;let n=e.length,r=t.length;if(n===0)return r;if(r===0)return n;let i=Array(r+1),a=Array(r+1);for(let e=0;e<=r;e++)i[e]=e;for(let o=1;o<=n;o++){a[0]=o;for(let n=1;n<=r;n++){let r=e[o-1]===t[n-1]?0:1;a[n]=Math.min((a[n-1]??0)+1,(i[n]??0)+1,(i[n-1]??0)+r)}for(let e=0;e<=r;e++)i[e]=a[e]??0}return i[r]??0}function Gw(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const Kw=new Map([[`if`,`If`],[`else`,`Else`],[`end`,`End`],[`range`,`Range`],[`with`,`With`],[`break`,`Break`],[`continue`,`Continue`],[`define`,`Define`],[`template`,`Template`],[`block`,`Block`],[`true`,`Bool`],[`false`,`Bool`],[`nil`,`Nil`]]),qw={left:`{{`,right:`}}`};var Jw=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=qw){this.src=e,this.leftDelim=t.left,this.rightDelim=t.right}pos(){return{line:this.line,column:this.column,offset:this.offset}}err(e,t,n={}){return new Pw(e,t,{...n,source:this.src})}next(){if(this.pending){let e=this.pending;return this.pending=void 0,e}return this.read()}peek(){return this.pending||=this.read(),this.pending}read(){switch(this.mode){case`text`:return this.readText();case`action`:return this.readAction();case`done`:return this.makeToken(`EOF`,``,this.pos())}}readText(){if(this.offset>=this.src.length)return this.mode=`done`,this.makeToken(`EOF`,``,this.pos());let e=this.pos(),t=this.offset;for(;t<this.src.length&&!this.src.startsWith(this.leftDelim,t);)t+=1;let n=t<this.src.length&&this.src[t+this.leftDelim.length]===`-`,r=t;if(n)for(;r>this.offset&&Yw(this.src[r-1]??``);)--r;if(r>this.offset){let t=this.src.slice(this.offset,r);return this.advanceTo(r),this.makeToken(`Text`,t,e)}return this.advanceTo(t),this.emitLeftDelim(n)}emitLeftDelim(e){let t=this.pos();if(this.advanceBy(this.leftDelim.length),e)for(this.advanceBy(1);Yw(this.src[this.offset]??``);)this.advanceBy(1);return this.mode=`action`,this.src.startsWith(`/*`,this.offset)?this.readComment(t,e):this.makeToken(`LeftDelim`,e?`${this.leftDelim}-`:this.leftDelim,t,e?{trimLeft:!0}:{})}readComment(e,t){this.advanceBy(2);let n=this.offset,r=this.src.indexOf(`*/`,this.offset);if(r===-1)throw this.err(`unclosed comment`,e,{expected:`*/${this.rightDelim}`,found:`end of input`});this.advanceTo(r);let i=this.src.slice(n,r).trim();for(this.advanceBy(2);Yw(this.src[this.offset]??``);)this.advanceBy(1);let a=!1;if(this.src[this.offset]===`-`&&(a=!0,this.advanceBy(1)),!this.src.startsWith(this.rightDelim,this.offset))throw this.err(`expected \`${this.rightDelim}\` to close comment`,this.pos(),{expected:this.rightDelim,found:this.src[this.offset]??`end of input`});if(this.advanceBy(this.rightDelim.length),a)for(;Yw(this.src[this.offset]??``);)this.advanceBy(1);return this.mode=`text`,this.makeToken(`Comment`,i,e,{...t?{trimLeft:!0}:{},...a?{trimRight:!0}:{}})}readAction(){if(this.skipActionSpaces(),this.src.startsWith(`-${this.rightDelim}`,this.offset)){let e=this.pos();for(this.advanceBy(1+this.rightDelim.length),this.mode=`text`;Yw(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`RightDelim`,`-${this.rightDelim}`,e,{trimRight:!0})}if(this.src.startsWith(this.rightDelim,this.offset)){let e=this.pos();return this.advanceBy(this.rightDelim.length),this.mode=`text`,this.makeToken(`RightDelim`,this.rightDelim,e)}if(this.offset>=this.src.length)throw this.err(`unclosed action`,this.pos(),{expected:this.rightDelim,found:`end of input`});let e=this.src[this.offset],t=this.pos();switch(e){case`(`:return this.advanceBy(1),this.makeToken(`LeftParen`,`(`,t);case`)`:return this.advanceBy(1),this.makeToken(`RightParen`,`)`,t);case`|`:return this.advanceBy(1),this.makeToken(`Pipe`,`|`,t);case`,`:return this.advanceBy(1),this.makeToken(`Comma`,`,`,t);case`:`:if(this.src[this.offset+1]===`=`)return this.advanceBy(2),this.makeToken(`Declare`,`:=`,t);throw this.err("expected `:=`",t,{expected:`:=`,found:`:`});case`=`:return this.advanceBy(1),this.makeToken(`Assign`,`=`,t);case`"`:return this.readQuotedString(t);case"`":return this.readRawString(t);case`'`:return this.readChar(t)}if(e===`$`)return this.readVariable(t);if(e!==void 0&&(Zw(e)||Xw(e)&&Zw(this.src[this.offset+1]??``)||e===`.`&&Zw(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&nT(e))return this.readIdentifier(t);throw this.err(`unexpected character ${JSON.stringify(e)}`,t,{found:e??`end of input`})}readQuotedString(e){let t=this.offset;for(this.advanceBy(1);this.offset<this.src.length;){let n=this.src[this.offset];if(n===`\\`){this.advanceBy(1),this.offset<this.src.length&&this.advanceBy(1);continue}if(n===`
60
+ `)}function Hw(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:Uw(e,t)})).sort((e,t)=>e.dist-t.dist),r=Math.max(2,Math.floor(e.length/2));return n.filter(e=>e.dist<=r).slice(0,3).map(e=>e.name)}function Uw(e,t){if(e===t)return 0;let n=e.length,r=t.length;if(n===0)return r;if(r===0)return n;let i=Array(r+1),a=Array(r+1);for(let e=0;e<=r;e++)i[e]=e;for(let o=1;o<=n;o++){a[0]=o;for(let n=1;n<=r;n++){let r=e[o-1]===t[n-1]?0:1;a[n]=Math.min((a[n-1]??0)+1,(i[n]??0)+1,(i[n-1]??0)+r)}for(let e=0;e<=r;e++)i[e]=a[e]??0}return i[r]??0}function Ww(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const Gw=new Map([[`if`,`If`],[`else`,`Else`],[`end`,`End`],[`range`,`Range`],[`with`,`With`],[`break`,`Break`],[`continue`,`Continue`],[`define`,`Define`],[`template`,`Template`],[`block`,`Block`],[`true`,`Bool`],[`false`,`Bool`],[`nil`,`Nil`]]),Kw={left:`{{`,right:`}}`};var qw=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=Kw){this.src=e,this.leftDelim=t.left,this.rightDelim=t.right}pos(){return{line:this.line,column:this.column,offset:this.offset}}err(e,t,n={}){return new Nw(e,t,{...n,source:this.src})}next(){if(this.pending){let e=this.pending;return this.pending=void 0,e}return this.read()}peek(){return this.pending||=this.read(),this.pending}read(){switch(this.mode){case`text`:return this.readText();case`action`:return this.readAction();case`done`:return this.makeToken(`EOF`,``,this.pos())}}readText(){if(this.offset>=this.src.length)return this.mode=`done`,this.makeToken(`EOF`,``,this.pos());let e=this.pos(),t=this.offset;for(;t<this.src.length&&!this.src.startsWith(this.leftDelim,t);)t+=1;let n=t<this.src.length&&this.src[t+this.leftDelim.length]===`-`,r=t;if(n)for(;r>this.offset&&Jw(this.src[r-1]??``);)--r;if(r>this.offset){let t=this.src.slice(this.offset,r);return this.advanceTo(r),this.makeToken(`Text`,t,e)}return this.advanceTo(t),this.emitLeftDelim(n)}emitLeftDelim(e){let t=this.pos();if(this.advanceBy(this.leftDelim.length),e)for(this.advanceBy(1);Jw(this.src[this.offset]??``);)this.advanceBy(1);return this.mode=`action`,this.src.startsWith(`/*`,this.offset)?this.readComment(t,e):this.makeToken(`LeftDelim`,e?`${this.leftDelim}-`:this.leftDelim,t,e?{trimLeft:!0}:{})}readComment(e,t){this.advanceBy(2);let n=this.offset,r=this.src.indexOf(`*/`,this.offset);if(r===-1)throw this.err(`unclosed comment`,e,{expected:`*/${this.rightDelim}`,found:`end of input`});this.advanceTo(r);let i=this.src.slice(n,r).trim();for(this.advanceBy(2);Jw(this.src[this.offset]??``);)this.advanceBy(1);let a=!1;if(this.src[this.offset]===`-`&&(a=!0,this.advanceBy(1)),!this.src.startsWith(this.rightDelim,this.offset))throw this.err(`expected \`${this.rightDelim}\` to close comment`,this.pos(),{expected:this.rightDelim,found:this.src[this.offset]??`end of input`});if(this.advanceBy(this.rightDelim.length),a)for(;Jw(this.src[this.offset]??``);)this.advanceBy(1);return this.mode=`text`,this.makeToken(`Comment`,i,e,{...t?{trimLeft:!0}:{},...a?{trimRight:!0}:{}})}readAction(){if(this.skipActionSpaces(),this.src.startsWith(`-${this.rightDelim}`,this.offset)){let e=this.pos();for(this.advanceBy(1+this.rightDelim.length),this.mode=`text`;Jw(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`RightDelim`,`-${this.rightDelim}`,e,{trimRight:!0})}if(this.src.startsWith(this.rightDelim,this.offset)){let e=this.pos();return this.advanceBy(this.rightDelim.length),this.mode=`text`,this.makeToken(`RightDelim`,this.rightDelim,e)}if(this.offset>=this.src.length)throw this.err(`unclosed action`,this.pos(),{expected:this.rightDelim,found:`end of input`});let e=this.src[this.offset],t=this.pos();switch(e){case`(`:return this.advanceBy(1),this.makeToken(`LeftParen`,`(`,t);case`)`:return this.advanceBy(1),this.makeToken(`RightParen`,`)`,t);case`|`:return this.advanceBy(1),this.makeToken(`Pipe`,`|`,t);case`,`:return this.advanceBy(1),this.makeToken(`Comma`,`,`,t);case`:`:if(this.src[this.offset+1]===`=`)return this.advanceBy(2),this.makeToken(`Declare`,`:=`,t);throw this.err("expected `:=`",t,{expected:`:=`,found:`:`});case`=`:return this.advanceBy(1),this.makeToken(`Assign`,`=`,t);case`"`:return this.readQuotedString(t);case"`":return this.readRawString(t);case`'`:return this.readChar(t)}if(e===`$`)return this.readVariable(t);if(e!==void 0&&(Xw(e)||Yw(e)&&Xw(this.src[this.offset+1]??``)||e===`.`&&Xw(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&tT(e))return this.readIdentifier(t);throw this.err(`unexpected character ${JSON.stringify(e)}`,t,{found:e??`end of input`})}readQuotedString(e){let t=this.offset;for(this.advanceBy(1);this.offset<this.src.length;){let n=this.src[this.offset];if(n===`\\`){this.advanceBy(1),this.offset<this.src.length&&this.advanceBy(1);continue}if(n===`
61
61
  `)throw this.err(`newline in interpreted string`,e,{found:`\\n`});if(n===`"`)return this.advanceBy(1),this.makeToken(`String`,this.src.slice(t,this.offset),e);this.advanceBy(1)}throw this.err(`unterminated string literal`,e,{expected:`"`,found:`end of input`})}readRawString(e){let t=this.offset;for(this.advanceBy(1);this.offset<this.src.length;){if(this.src[this.offset]==="`")return this.advanceBy(1),this.makeToken(`String`,this.src.slice(t,this.offset),e);this.advanceBy(1)}throw this.err(`unterminated raw string literal`,e,{expected:"`",found:`end of input`})}readChar(e){let t=this.offset;for(this.advanceBy(1);this.offset<this.src.length;){let n=this.src[this.offset];if(n===`\\`){this.advanceBy(1),this.offset<this.src.length&&this.advanceBy(1);continue}if(n===`
62
- `)throw this.err(`newline in rune literal`,e,{found:`\\n`});if(n===`'`)return this.advanceBy(1),this.makeToken(`Char`,this.src.slice(t,this.offset),e);this.advanceBy(1)}throw this.err(`unterminated rune literal`,e,{expected:`'`,found:`end of input`})}readNumber(e){let t=this.offset;if(Xw(this.src[this.offset]??``)&&this.advanceBy(1),this.src[this.offset]===`0`&&this.offset+1<this.src.length){let n=this.src[this.offset+1];if(n===`x`||n===`X`){for(this.advanceBy(2);Qw(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`||this.src[this.offset]===`p`||this.src[this.offset]===`P`)for(;this.isHexFloatTail(this.src[this.offset]??``);)this.advanceBy(1);return this.finishNumber(t,e)}if(n===`o`||n===`O`){for(this.advanceBy(2);$w(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}if(n===`b`||n===`B`){for(this.advanceBy(2);eT(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;Zw(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);Zw(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`e`||this.src[this.offset]===`E`)for(this.advanceBy(1),Xw(this.src[this.offset]??``)&&this.advanceBy(1);Zw(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return Qw(e)||e===`.`||e===`p`||e===`P`||e===`+`||e===`-`||e===`_`}finishNumber(e,t){if(this.offset===e)throw this.err(`expected number`,t,{expected:`digit`});return this.makeToken(`Number`,this.src.slice(e,this.offset),t)}readVariable(e){let t=this.offset;for(this.advanceBy(1);rT(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&nT(this.src[this.offset+1]??``);)for(this.advanceBy(1);rT(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`Variable`,this.src.slice(t,this.offset),e)}readDotOrField(e){let t=this.offset;if(this.advanceBy(1),!nT(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;rT(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&nT(this.src[this.offset+1]??``);)for(this.advanceBy(1);rT(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`Field`,this.src.slice(t,this.offset),e)}readIdentifier(e){let t=this.offset;for(;rT(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=Kw.get(n);return r?this.makeToken(r,n,e):this.makeToken(`Identifier`,n,e)}skipActionSpaces(){for(;this.offset<this.src.length;){let e=this.src[this.offset];if(e===` `||e===` `||e===`\r`||e===`
62
+ `)throw this.err(`newline in rune literal`,e,{found:`\\n`});if(n===`'`)return this.advanceBy(1),this.makeToken(`Char`,this.src.slice(t,this.offset),e);this.advanceBy(1)}throw this.err(`unterminated rune literal`,e,{expected:`'`,found:`end of input`})}readNumber(e){let t=this.offset;if(Yw(this.src[this.offset]??``)&&this.advanceBy(1),this.src[this.offset]===`0`&&this.offset+1<this.src.length){let n=this.src[this.offset+1];if(n===`x`||n===`X`){for(this.advanceBy(2);Zw(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`||this.src[this.offset]===`p`||this.src[this.offset]===`P`)for(;this.isHexFloatTail(this.src[this.offset]??``);)this.advanceBy(1);return this.finishNumber(t,e)}if(n===`o`||n===`O`){for(this.advanceBy(2);Qw(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}if(n===`b`||n===`B`){for(this.advanceBy(2);$w(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;Xw(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);Xw(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`e`||this.src[this.offset]===`E`)for(this.advanceBy(1),Yw(this.src[this.offset]??``)&&this.advanceBy(1);Xw(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return Zw(e)||e===`.`||e===`p`||e===`P`||e===`+`||e===`-`||e===`_`}finishNumber(e,t){if(this.offset===e)throw this.err(`expected number`,t,{expected:`digit`});return this.makeToken(`Number`,this.src.slice(e,this.offset),t)}readVariable(e){let t=this.offset;for(this.advanceBy(1);nT(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&tT(this.src[this.offset+1]??``);)for(this.advanceBy(1);nT(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`Variable`,this.src.slice(t,this.offset),e)}readDotOrField(e){let t=this.offset;if(this.advanceBy(1),!tT(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;nT(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&tT(this.src[this.offset+1]??``);)for(this.advanceBy(1);nT(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`Field`,this.src.slice(t,this.offset),e)}readIdentifier(e){let t=this.offset;for(;nT(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=Gw.get(n);return r?this.makeToken(r,n,e):this.makeToken(`Identifier`,n,e)}skipActionSpaces(){for(;this.offset<this.src.length;){let e=this.src[this.offset];if(e===` `||e===` `||e===`\r`||e===`
63
63
  `)this.advanceBy(1);else return}}advanceBy(e){for(let t=0;t<e;t++){let e=this.src[this.offset];this.offset+=1,e===`
64
- `?(this.line+=1,this.column=1):this.column+=1}}advanceTo(e){for(;this.offset<e;)this.advanceBy(1)}makeToken(e,t,n,r={}){return Object.freeze({type:e,value:t,pos:n,...r.trimLeft===void 0?{}:{trimLeft:r.trimLeft},...r.trimRight===void 0?{}:{trimRight:r.trimRight}})}};function Yw(e){return e===` `||e===` `||e===`\r`||e===`
65
- `}function Xw(e){return e===`+`||e===`-`}function Zw(e){return e>=`0`&&e<=`9`}function Qw(e){return Zw(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function $w(e){return e>=`0`&&e<=`7`}function eT(e){return e===`0`||e===`1`}function tT(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function nT(e){return tT(e)||e===`_`}function rT(e){return nT(e)||Zw(e)}let iT,aT;function oT(e,t){return aT(e,t)}var sT=class e{static EMPTY=new e(new Map,void 0);#e;#t;constructor(e,t){this.#e=e,this.#t=t}static{iT=(t,n)=>new e(t,n),aT=(e,t)=>e.#e.get(t)??(e.#t&&aT(e.#t,t))}has(e){return aT(this,e)!==void 0}};function cT(e,t,n=sT.EMPTY){return new Mte(e,t,n).parseTemplate()}var Mte=class{lex;buf=[];defines=new Map;inherit;source;rangeDepth=0;constructor(e,t,n){this.source=e,this.inherit=n,this.lex=t?new Jw(e,t):new Jw(e)}peek(e=0){for(;this.buf.length<=e;)this.buf.push(this.lex.next());return this.buf[e]}next(){return this.buf.length>0?this.buf.shift():this.lex.next()}expect(e,t){let n=this.next();if(n.type!==e)throw this.errAt(n,`expected ${t}`,{expected:t,found:dT(n)});return n}errAt(e,t,n={}){return new Pw(t,e.pos,{...n,source:this.source})}parseTemplate(){let e=this.parseList();if(this.peek().type!==`EOF`){let e=this.peek(),t=this.peek(1);if(e.type===`LeftDelim`&&(t.type===`Else`||t.type===`End`)){let n=t.type===`Else`?`else`:`end`;throw this.errAt(e,`unexpected \`{{${n}}}\` outside of \`if\`, \`range\`, \`with\`, or \`block\``,{found:`{{${n}}}`})}throw this.errAt(e,`unexpected ${dT(e)}`,{found:dT(e)})}return{root:e,defines:iT(this.defines,this.inherit),ownDefines:this.defines,source:this.source}}parseList(){let e=this.peek().pos,t=[];for(;;){let n=this.peek();if(n.type===`EOF`)break;if(n.type===`Text`){this.next(),t.push({type:`Text`,pos:n.pos,text:n.value});continue}if(n.type===`Comment`){this.next();let e=uT(n);t.push({type:`Comment`,pos:n.pos,text:n.value,trim:e});continue}if(n.type===`LeftDelim`){let n=this.peek(1).type;if(n===`Else`||n===`End`)return lT(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${dT(n)} at top level`,{found:dT(n)})}return lT(e,t)}parseAction(){let e=this.expect(`LeftDelim`,"`{{`"),t=e.trimLeft===!0,n=this.peek();switch(n.type){case`If`:return this.next(),this.parseBranch(`If`,e.pos,t);case`Range`:return this.next(),this.parseBranch(`Range`,e.pos,t);case`With`:return this.next(),this.parseBranch(`With`,e.pos,t);case`Break`:return this.next(),this.parseBreakOrContinue(`Break`,e.pos,t);case`Continue`:return this.next(),this.parseBreakOrContinue(`Continue`,e.pos,t);case`Template`:return this.next(),this.parseTemplateInvocation(e.pos,t);case`Block`:return this.next(),this.parseBlock(e.pos,t);case`Define`:return this.next(),this.parseDefine(e.pos,t),null;case`RightDelim`:throw this.errAt(n,`empty action`,{expected:`pipeline`});default:{let n=this.parsePipeline(),r=this.expect(`RightDelim`,"`}}`");return{type:`Action`,pos:e.pos,pipe:n,trim:{trimLeft:t,trimRight:r.trimRight===!0}}}}}parseBranch(e,t,n){let r=this.parsePipeline();this.expect(`RightDelim`,"`}}`"),e===`Range`&&(this.rangeDepth+=1);let i=this.parseList();e===`Range`&&--this.rangeDepth;let a=this.parseElsePart(),o={trimLeft:n,trimRight:a.endConsumed?a.endRight:this.consumeEnd()},s=a.list?{pipe:r,list:i,elseList:a.list,trim:o}:{pipe:r,list:i,trim:o};switch(e){case`If`:return{type:`If`,pos:t,...s};case`Range`:return{type:`Range`,pos:t,...s};case`With`:return{type:`With`,pos:t,...s}}}parseBreakOrContinue(e,t,n){if(this.rangeDepth===0)throw new Pw(`{{${e===`Break`?`break`:`continue`}}} outside of {{range}}`,t,{source:this.source});let r={trimLeft:n,trimRight:this.expect(`RightDelim`,"`}}`").trimRight===!0};return e===`Break`?{type:`Break`,pos:t,trim:r}:{type:`Continue`,pos:t,trim:r}}parseElsePart(){if(this.peek().type!==`LeftDelim`||this.peek(1).type!==`Else`)return{list:void 0,endRight:!1,endConsumed:!1};let e=this.next();if(this.next(),this.peek().type===`If`){this.next();let t=this.parseBranch(`If`,e.pos,e.trimLeft===!0);return{list:{type:`List`,pos:e.pos,nodes:[t]},endRight:t.trim.trimRight,endConsumed:!0}}return this.expect(`RightDelim`,"`}}`"),{list:this.parseList(),endRight:!1,endConsumed:!1}}consumeEnd(){return this.expect(`LeftDelim`,"`{{end}}`"),this.expect(`End`,"`end`"),this.expect(`RightDelim`,"`}}`").trimRight===!0}parseTemplateInvocation(e,t){let n=this.parseQuotedName(),r=this.peek().type===`RightDelim`?void 0:this.parsePipeline(),i={trimLeft:t,trimRight:this.expect(`RightDelim`,"`}}`").trimRight===!0};return r?{type:`Template`,pos:e,name:n,pipe:r,trim:i}:{type:`Template`,pos:e,name:n,trim:i}}parseBlock(e,t){let n=this.parseQuotedName(),r=this.peek().type===`RightDelim`?void 0:this.parsePipeline();this.expect(`RightDelim`,"`}}`");let i=this.rangeDepth;this.rangeDepth=0;let a=this.parseList();this.rangeDepth=i;let o={trimLeft:t,trimRight:this.consumeEnd()};return!this.defines.has(n)&&!this.inherit.has(n)&&this.defines.set(n,{list:a,source:this.source}),r?{type:`Block`,pos:e,name:n,pipe:r,list:a,trim:o}:{type:`Block`,pos:e,name:n,list:a,trim:o}}parseDefine(e,t){let n=this.parseQuotedName();this.expect(`RightDelim`,"`}}`");let r=this.rangeDepth;this.rangeDepth=0;let i=this.parseList();if(this.rangeDepth=r,this.consumeEnd(),this.defines.has(n)||this.inherit.has(n))throw new Pw(`redefinition of template ${JSON.stringify(n)}`,i.pos,{source:this.source});this.defines.set(n,{list:i,source:this.source})}parseQuotedName(){let e=this.next();if(e.type!==`String`)throw this.errAt(e,`expected template name (quoted string)`,{expected:`string`,found:dT(e)});return yT(e.value,e.pos,this.source)}parsePipeline(){let e=this.peek().pos,t=this.tryParseDecls(),n=[this.parseCommand()];for(;this.peek().type===`Pipe`;){this.next();let e=this.peek();if(!fT(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:dT(e)});n.push(this.parseCommand())}return{type:`Pipe`,pos:e,decls:t?.vars??[],isAssign:t?.isAssign??!1,cmds:n}}tryParseDecls(){if(this.peek().type!==`Variable`)return;let e=1;for(;this.peek(e).type===`Comma`;){if(this.peek(e+1).type!==`Variable`)return;e+=2}let t=this.peek(e).type;if(t!==`Declare`&&t!==`Assign`)return;let n=[pT(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(pT(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;fT(this.peek().type);)t.push(this.parsePrimary());return{type:`Command`,pos:e,args:t}}parsePrimary(){let e=this.next();switch(e.type){case`Dot`:return{type:`Dot`,pos:e.pos};case`Field`:return{type:`Field`,pos:e.pos,idents:e.value.slice(1).split(`.`)};case`Variable`:return pT(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:yT(e.value,e.pos,this.source)};case`Number`:return hT(e);case`Char`:return gT(e,this.source);case`Bool`:return{type:`Bool`,pos:e.pos,value:e.value===`true`};case`Nil`:return{type:`Nil`,pos:e.pos};case`LeftParen`:return this.parseChainOrPipe(e.pos);default:throw this.errAt(e,`expected command argument, found ${dT(e)}`,{expected:`command argument`,found:dT(e)})}}parseChainOrPipe(e){let t=this.parsePipeline(),n=this.expect(`RightParen`,"`)`"),r=[],i=n.pos.offset+1,a=this.peek();return a.type===`Field`&&a.pos.offset===i&&(this.next(),r.push(...a.value.slice(1).split(`.`))),r.length===0?t:{type:`Chain`,pos:e,node:t,fields:r}}};function lT(e,t){return{type:`List`,pos:e,nodes:t}}function uT(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function dT(e){return e.type===`EOF`?`end of input`:e.value||e.type}function fT(e){switch(e){case`Dot`:case`Field`:case`Variable`:case`Identifier`:case`String`:case`Number`:case`Char`:case`Bool`:case`Nil`:case`LeftParen`:return!0;default:return!1}}function pT(e){return{type:`Variable`,pos:e.pos,idents:mT(e.value)}}function mT(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function hT(e){let t=e.value,n=t.replace(/_/g,``),r=n.toLowerCase().endsWith(`i`),i=r?n.slice(0,-1):n,a=!r&&(i.includes(`.`)||!i.startsWith(`0x`)&&!i.startsWith(`0X`)&&/[eE]/.test(i)||(i.startsWith(`0x`)||i.startsWith(`0X`))&&/[pP]/.test(i)),o=!r&&!a,s={type:`Number`,pos:e.pos,text:t,isInt:o,isUint:!1,isFloat:a,isComplex:r};if(o){let e=_T(i);return{...s,intValue:e}}if(a){let e=vT(i);return{...s,floatValue:e}}let c=vT(i);return{...s,complexValue:[0,c]}}function gT(e,t){let n=bT(e.value,e.pos,t);return{type:`Number`,pos:e.pos,text:e.value,isInt:!0,isUint:!1,isFloat:!1,isComplex:!1,intValue:BigInt(n)}}function _T(e){let t=1n,n=e;return n.startsWith(`+`)?n=n.slice(1):n.startsWith(`-`)&&(t=-1n,n=n.slice(1)),t*BigInt(n)}function vT(e){return Number(e)}function yT(e,t,n){if(e.startsWith("`"))return e.slice(1,-1);let r=``;for(let i=1;i<e.length-1;i++){let a=e[i];if(a!==`\\`){r+=a;continue}let o=e[++i];switch(o){case`n`:r+=`
66
- `;break;case`t`:r+=` `;break;case`r`:r+=`\r`;break;case`\\`:r+=`\\`;break;case`"`:r+=`"`;break;case`'`:r+=`'`;break;case`a`:r+=`\x07`;break;case`b`:r+=`\b`;break;case`f`:r+=`\f`;break;case`v`:r+=`\v`;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:{let t=o+(e[i+1]??``)+(e[i+2]??``);i+=2,r+=String.fromCodePoint(Number.parseInt(t,8));break}case`x`:{let t=(e[i+1]??``)+(e[i+2]??``);i+=2,r+=String.fromCodePoint(Number.parseInt(t,16));break}case`u`:{let t=e.slice(i+1,i+5);i+=4,r+=String.fromCodePoint(Number.parseInt(t,16));break}case`U`:{let t=e.slice(i+1,i+9);i+=8,r+=String.fromCodePoint(Number.parseInt(t,16));break}default:throw new Pw(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function bT(e,t,n){let r=yT(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new Pw(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function xT(e,t){if(t(e)!==!1)for(let n of ST(e))xT(n,t)}function ST(e){switch(e.type){case`Text`:case`Comment`:case`Dot`:case`Nil`:case`Bool`:case`Number`:case`String`:case`Identifier`:case`Field`:case`Variable`:case`Break`:case`Continue`:return[];case`List`:return e.nodes;case`Chain`:return[e.node];case`Command`:return e.args;case`Pipe`:return[...e.decls,...e.cmds];case`Action`:return[e.pipe];case`If`:case`Range`:case`With`:return e.elseList?[e.pipe,e.list,e.elseList]:[e.pipe,e.list];case`Template`:return e.pipe?[e.pipe]:[];case`Block`:return e.pipe?[e.pipe,e.list]:[e.list];default:return Gw(e)}}const CT=Symbol(`go-template-js.MISSING`);function wT(e,t){if(e==null)return CT;if(e instanceof Map)return e.has(t)?e.get(t):CT;if(Array.isArray(e))return CT;if(typeof e==`object`){let n=e;return t in n?n[t]:CT}return CT}function TT(e,t){let n=e;for(let e of t){if(n===CT)return CT;n=wT(n,e)}return n}function ET(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||e===void 0||t===void 0||typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length?e.every((e,n)=>ET(e,t[n])):!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!ET(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}if(typeof e==`object`&&typeof t==`object`){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length?n.every(n=>ET(e[n],t[n])):!1}return!1}const DT=new WeakSet;function OT(e){return DT.add(e),e}function kT(e){return DT.has(e)}function AT(e){return e==null||e===!1?!1:typeof e==`number`?e!==0&&!Number.isNaN(e):typeof e==`bigint`?e!==0n:typeof e==`string`||Array.isArray(e)?e.length>0:e instanceof Map||e instanceof Set?e.size>0:typeof e==`object`?Object.keys(e).length>0:!!e}function jT(e,t){return{eq:{fn:(e,...t)=>t.some(t=>PT(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!PT(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>FT(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>FT(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>FT(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>FT(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>IT(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=LT(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>zT(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>HT(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${HT(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>Bte(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>GT(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>GT(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>Pte(HT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>Lte(HT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>zte(HT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!AT(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function MT(){return{and:OT({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!AT(t))return t;return t}}),or:OT({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),AT(t))return t;return t}})}}function NT(e,t){return{...jT(e,t),...MT()}}function PT(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):ET(e,t)}function FT(e,t){if(typeof e==`bigint`&&typeof t==`bigint`)return e===t?0:e<t?-1:1;if(typeof e==`bigint`||typeof t==`bigint`){let n=typeof e==`bigint`?e:BigInt(Math.trunc(Number(e))),r=typeof t==`bigint`?t:BigInt(Math.trunc(Number(t)));return n===r?0:n<r?-1:1}let n=e,r=t;return n===r?0:n<r?-1:1}function IT(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function LT(e,t){if(Array.isArray(e)||typeof e==`string`){let n=RT(t,e.length);if(n===e.length)throw Error(`index out of range: ${n}`);return e[n]}if(e instanceof Map)return e.get(t);if(typeof e==`object`&&e){if(typeof t!=`string`)throw Error(`index: object index must be string, got ${BT(t)}`);return e[t]}throw Error(`index: cannot index ${BT(e)}`)}function RT(e,t){let n=typeof e==`bigint`?Number(e):e;if(typeof n!=`number`||!Number.isInteger(n))throw Error(`cannot index slice/array with type ${VT(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function zT(e,t){if(t.length>3)throw Error(`too many slice indexes: ${t.length}`);if(typeof e==`string`&&t.length>2)throw Error(`cannot 3-index slice a string`);let n=e.length,r=[0,n,n];t.forEach((e,t)=>{r[t]=RT(e,n)});let[i,a,o]=r;if(i>a)throw Error(`invalid slice index: ${i} > ${a}`);if(a>o)throw Error(`invalid slice index: ${a} > ${o}`);return e.slice(i,a)}function BT(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function VT(e){return e==null?`<nil>`:typeof e==`string`?`string`:typeof e==`boolean`?`bool`:typeof e==`bigint`?`int64`:typeof e==`number`?Number.isInteger(e)?`int`:`float64`:Array.isArray(e)?`[]interface {}`:e instanceof Map||typeof e==`object`?`map[string]interface {}`:typeof e}function HT(e,t){let n=``,r=!1;for(let i=0;i<e.length;i++){let a=e[i],o=typeof a==`string`;i>0&&!r&&!o&&(n+=` `),n+=UT(a,t),r=o}return n}function UT(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const Nte={"\0":`�`,'"':`&#34;`,"'":`&#39;`,"&":`&amp;`,"<":`&lt;`,">":`&gt;`};function Pte(e){return e.replace(/[\0"'&<>]/g,e=>Nte[e]??e)}const Fte={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},Ite=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function Lte(e){let t=``;for(let n of e){let e=Fte[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!Ite.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const Rte=new TextEncoder;function zte(e){let t=``,n=Rte.encode(e);for(let e of n)e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===45||e===46||e===95||e===126?t+=String.fromCharCode(e):e===32?t+=`+`:t+=`%${e.toString(16).toUpperCase().padStart(2,`0`)}`;return t}function Bte(e,t,n,r){let i=``,a=0,o=0;for(;o<e.length;){let s=e[o];if(s!==`%`){i+=s,o+=1;continue}if(e[o+1]===`%`){i+=`%`,o+=2;continue}let c=o+1;for(;c<e.length&&`+-# 0`.includes(e[c]??``);)c+=1;for(;c<e.length&&e[c]!==void 0&&/[0-9]/.test(e[c]);)c+=1;if(e[c]===`.`)for(c+=1;c<e.length&&e[c]!==void 0&&/[0-9]/.test(e[c]);)c+=1;let l=e[c],u=e.slice(o+1,c),d=t[a++];i+=Vte(l??``,u,d,n,r),o=c+1}return i}function Vte(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?WT(t,n):WT(t,UT(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${VT(n)}=${UT(n,r)})`:WT(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return WT(t,GT(n,r,i));case`q`:return WT(t,JSON.stringify(UT(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${VT(n)}=${UT(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return WT(t,Number(n).toFixed(i))}case`t`:return WT(t,AT(n)?`true`:`false`);case`x`:if(typeof n==`string`){let e=new TextEncoder().encode(n),r=``;for(let t of e)r+=t.toString(16).padStart(2,`0`);return WT(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${VT(n)}=${UT(n,r)})`:typeof n==`bigint`?WT(t,n.toString(16)):WT(t,Math.trunc(n).toString(16));default:return`%!${e}(${VT(n)}=${UT(n,r)})`}}function WT(e,t){let n=e.match(/^([+\-# 0]*)/)?.[1]??``,r=e.slice(n.length).match(/^(\d+)/);if(!r)return t;let i=Number(r[1]);if(t.length>=i)return t;let a=` `.repeat(i-t.length);return n.includes(`-`)?t+a:a+t}function GT(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>GT(e,t,n)).join(` `)}]`:e instanceof Map?KT([...e.entries()],t,n):qT(e)?KT(Object.entries(e),t,n):String(e)}function KT(e,t,n){let r=e=>GT(e,t,n),i=e=>typeof e==`number`||typeof e==`bigint`,a=([e],[t])=>{if(i(e)&&i(t))return e<t?-1:+(e>t);if(i(e)!==i(t))return i(e)?-1:1;let[n,a]=[r(e),r(t)];return n<a?-1:+(n>a)};return`map[${[...e].sort(a).map(([e,t])=>`${r(e)}:${r(t)}`).join(` `)}]`}function qT(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Map||e instanceof Set)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Hte(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function JT(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function Ute(e,t){let n=e;for(;n!==void 0;){if(n.vars.has(t))return{found:!0,value:n.vars.get(t)};n=n.parent}return{found:!1}}function YT(e,t,n){e.vars.set(t,n)}const XT=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],Wte=new Set([`default`,`zero`,`error`]);function Gte(e){if(e===void 0)return`default`;if(Wte.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${ZT(e)}`)}function ZT(e){return typeof e==`string`?JSON.stringify(e):e===null?`null`:e===void 0?`undefined`:typeof e==`bigint`?`${e}n`:typeof e==`number`||typeof e==`boolean`?String(e):typeof e==`symbol`?e.toString():typeof e==`function`?`[Function]`:`[${typeof e}]`}function Kte(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${ZT(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${ZT(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${ZT(e.right)}`);return{left:e.left,right:e.right}}}function qte(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function Jte(e){let t=new Set(XT);for(let[n,r]of Object.entries(e)){if(r.argTypes.forEach((e,r)=>{if(!t.has(e))throw Error(`EngineConfig.funcs.${n}: argTypes[${r}] is ${JSON.stringify(e)}, which is not an ArgType; declare one of ${XT.join(`, `)}`)}),qte(r.arity)&&r.argTypes.length===0)throw Error(`EngineConfig.funcs.${n}: arity ${JSON.stringify(r.arity.kind)} needs at least one declared argType (it reads its repeating slot from the end of argTypes); declare the slots the Go signature has, or use { kind: "exact" }`);if(r.arity.kind===`alternating`&&(!Number.isSafeInteger(r.arity.minimum)||r.arity.minimum<0))throw Error(`EngineConfig.funcs.${n}: arity "alternating" needs a non-negative integer minimum, got ${String(r.arity.minimum)}; the gate rejects every count below it, so a negative or non-finite minimum would disable the lower bound`)}return e}const QT=Object.freeze({kind:`break`}),$T=Object.freeze({kind:`continue`}),Yte={kind:`none`};let eE;(class e{source;_evaluate;_defines;_referencedFunctions;_referencedCalls;constructor(e,t,n,r,i){this.source=e,this._evaluate=t,this._defines=n,this._referencedFunctions=r,this._referencedCalls=i}static{eE=(t,n,r,i,a)=>new e(t,n,r,i,a)}defines(){return this._defines}evaluate(e){return this._evaluate(e)}referencedFunctions(){return this._referencedFunctions}referencedCalls(){return this._referencedCalls}});function Xte(e){let t=new Set,n=e=>{xT(e,e=>{e.type===`Identifier`&&t.add(e.ident)})};n(e.root);for(let t of e.ownDefines.values())n(t.list);return t}const tE={kind:`dynamic`};function nE(e){switch(e.type){case`String`:return{kind:`literal`,value:e.value};case`Bool`:return{kind:`literal`,value:e.value};case`Nil`:return{kind:`literal`,value:null};case`Number`:{let t=uE(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:tE}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return tE;let t=e.cmds[0];if(t===void 0)return tE;let n=t.args[0];return n===void 0||n.type!==`Identifier`?tE:{kind:`call`,name:n.ident,args:t.args.slice(1).map(nE)}}default:return tE}}function Zte(e){let t=[],n=e=>{xT(e,e=>{if(e.type!==`Command`)return;let n=e.args[0];if(n===void 0||n.type!==`Identifier`)return;let r=e.args.slice(1).map(nE);t.push({name:n.ident,args:r.map(e=>e.kind===`literal`&&typeof e.value==`string`?e.value:null),argExprs:r})})};n(e.root);for(let t of e.ownDefines.values())n(t.list);return t}var Qte=class{fromString;toString;isT;funcs;missingKey;delims;constructor(e){this.fromString=e.fromString;let t=Object.hasOwn(e,`toString`)?e.toString:void 0;this.toString=t??aE,this.isT=e.isT??rE,this.missingKey=Gte(e.missingKey),this.delims=Kte(e.delims),this.funcs=Jte({...NT(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=cT(e,this.delims,t);return eE(n.source,e=>this.evalParsed(n,e),n.defines,Xte(n),Zte(n))}compile(e){let t=this.parse(e);return e=>t.evaluate(e)}evaluate(e,t){return e.evaluate(t)}evalParsed(e,t){let n=[],r=Hte(t),i={out:n,defines:e.defines,source:e.source};return this.evalList(e.root,r,i),n}evalList(e,t,n){for(let r of e.nodes)this.evalNode(r,t,n)}evalNode(e,t,n){switch(e.type){case`Text`:n.out.push(this.fromString(e.text));return;case`Comment`:return;case`Action`:{let r=this.evalAction(e,t,n);e.pipe.decls.length===0&&this.emitFromValue(r,n);return}case`List`:this.evalList(e,t,n);return;case`If`:this.evalIf(e,t,n);return;case`Range`:this.evalRange(e,t,n);return;case`With`:this.evalWith(e,t,n);return;case`Break`:throw QT;case`Continue`:throw $T;case`Template`:this.evalTemplateInvoke(e,t,n);return;case`Block`:this.evalBlock(e,t,n);return;case`Pipe`:case`Command`:case`Identifier`:case`Field`:case`Variable`:case`Chain`:case`Dot`:case`Nil`:case`Bool`:case`Number`:case`String`:throw new Fw(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:Gw(e)}}evalIf(e,t,n){AT(this.evalPipe(e.pipe,t,n))?this.evalList(e.list,t,n):e.elseList&&this.evalList(e.elseList,t,n)}evalWith(e,t,n){let r=this.evalPipe(e.pipe,t,n);if(AT(r)){let i=JT(t,r);this.evalList(e.list,i,n)}else e.elseList&&this.evalList(e.elseList,t,n)}evalRange(e,t,n){let r=this.evalPipeWithoutDecls(e.pipe,t,n),i=e.pipe.decls,a=cne(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=JT(t,o);if(i.length===1)YT(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;YT(a,e,r),YT(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===$T)continue;throw e}}}catch(e){if(e===QT)return;throw e}}evalTemplateInvoke(e,t,n){let r=oT(n.defines,e.name);if(!r)throw new Fw(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=JT(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot);this.evalList(r.list,i,{out:n.out,defines:n.defines,source:r.source})}evalBlock(e,t,n){let r=JT(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=oT(n.defines,e.name)??{list:e.list,source:n.source};this.evalList(i.list,r,{out:n.out,defines:n.defines,source:i.source})}evalAction(e,t,n){return this.evalPipe(e.pipe,t,n)}evalPipe(e,t,n){if(e.cmds.length===0)throw new Fw(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,Yte);for(let i=1;i<e.cmds.length;i++){let a=e.cmds[i];r=this.evalCommand(a,t,n,{kind:`value`,value:r})}if(e.decls.length>0)for(let n of e.decls)YT(t,n.idents[0]??`$`,r);return r}evalPipeWithoutDecls(e,t,n){let r={type:`Pipe`,pos:e.pos,decls:[],isAssign:!1,cmds:e.cmds};return this.evalPipe(r,t,n)}evalCommand(e,t,n,r){if(e.args.length===0)throw new Fw(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new Fw(`cannot apply arguments to a ${i.type} primary; only functions take arguments`,e.pos,{source:n.source});return this.evalPrimary(i,t,n)}let a=this.funcs[i.ident];if(!a)throw new Iw(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=kT(a),c=o.map(e=>s?()=>this.evalPrimary(e,t,n):this.evalPrimary(e,t,n));if(r.kind===`value`){let e=r.value;c.push(s?()=>e:e)}return this.invoke(i.ident,a,c,e.pos,n)}invoke(e,t,n,r,i){$te(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof Rw?new Rw(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof Vw?new Vw(t.message,r,{source:i.source}):t instanceof Nw?t:new Fw(`error calling ${e}: ${sne(t)}`,r,{source:i.source,cause:t})}}evalPrimary(e,t,n){switch(e.type){case`Dot`:return t.dot;case`Nil`:return null;case`Bool`:return e.value;case`Number`:return uE(e);case`String`:return e.value;case`Field`:return this.resolveFieldChain(t.dot,e.idents,e.pos,n);case`Variable`:return this.resolveVariable(e.idents,t,e.pos,n);case`Identifier`:{let t=this.funcs[e.ident];if(!t)throw new Iw(e.ident,e.pos,{source:n.source,available:Object.keys(this.funcs)});return this.invoke(e.ident,t,[],e.pos,n)}case`Chain`:return this.resolveFieldChain(this.evalPrimary(e.node,t,n),e.fields,e.pos,n);case`Pipe`:return this.evalPipe(e,t,n);default:throw new Fw(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=TT(e,t);if(i!==CT)return i;if(this.missingKey===`error`)throw new Bw(t,n,{source:r.source})}resolveVariable(e,t,n,r){let i=e[0]??`$`;if(i===`$`){let i=e.slice(1);return i.length===0?t.root:this.resolveFieldChain(t.root,i,n,r)}let a=Ute(t,i);if(!a.found)throw new Fw(`undefined variable ${i}`,n,{source:r.source});let o=e.slice(1);return o.length===0?a.value:this.resolveFieldChain(a.value,o,n,r)}emitFromValue(e,t){if(e==null){t.out.push(this.fromString(`<no value>`));return}if(typeof e==`string`){t.out.push(this.fromString(e));return}if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`){t.out.push(this.fromString(String(e)));return}if(this.isT(e)){t.out.push(e);return}t.out.push(this.fromString(GT(e,this.toString,this.isT)))}};const rE=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function iE(e){return new Qte(e)}function $te(e,t,n,r,i,a=aE,o=rne,s=rE){let{argTypes:c,arity:l}=t,u=ene(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new Lw(e,u,n.length,r,{source:i});let d=tne(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!nne(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new zw(e,t+1,l,r,{source:i}):new Rw(e,t+1,sE(c),cE(l),r,{source:i});if(c===`liftable`&&typeof l==`string`&&(n[t]=o(l)),c===`truncating-int`?n[t]=Math.trunc(Number(l)):(c===`int`||c===`float`)&&(n[t]=Number(l)),c===`ordered`){if(f===-1)f=t;else if(!ane(n[f],l))throw new Rw(e,t+1,`${sE(`ordered`)} of the same kind as ${cE(n[f])}`,cE(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!one(n[p],l))throw new Rw(e,t+1,`${sE(`comparable`)} of the same kind as ${cE(n[p])}`,cE(l),r,{source:i})}}}function ene(e,t){switch(t.kind){case`exact`:return{minimum:e.length,maximum:e.length};case`variadic`:return{minimum:e.length-1,maximum:1/0};case`alternating`:return{minimum:t.minimum,maximum:1/0}}}function tne(e,t){let n=e.length;switch(t.kind){case`exact`:return t=>e[t];case`variadic`:return t=>e[Math.min(t,n-1)];case`alternating`:return t=>e[t%n]}}function nne(e,t,n,r){switch(e){case`truthy`:case`reflective`:case`value`:return!0;case`string`:return typeof t==`string`;case`int`:return typeof t==`number`&&Number.isSafeInteger(t)||typeof t==`bigint`&&Number.isSafeInteger(Number(t));case`truncating-int`:return typeof t==`number`&&Number.isFinite(t)||typeof t==`bigint`&&Number.isSafeInteger(Number(t));case`float`:return typeof t==`number`||typeof t==`bigint`&&Number.isFinite(Number(t));case`bool`:return typeof t==`boolean`;case`ordered`:return typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`;case`T`:return r(t);case`list`:return Array.isArray(t);case`dict`:return qT(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||qT(t);case`comparable`:return t==null||typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`||Array.isArray(t)||t instanceof Map||t instanceof Set||qT(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||qT(t);case`index-key`:return typeof t==`string`||typeof t==`number`||typeof t==`bigint`;case`sliceable`:return typeof t==`string`||Array.isArray(t);case`stringifiable`:if(typeof t==`string`)return!0;try{return n(t),!0}catch{return!1}case`liftable`:return typeof t==`string`||r(t);case`serializable`:return ine(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function rne(e){return e}function aE(e){if(typeof e==`string`)return e;if(e==null)return`<nil>`;if(typeof e==`number`||typeof e==`bigint`||typeof e==`boolean`)return String(e);throw new Rw(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,cE(e),{line:0,column:0,offset:0})}function ine(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function ane(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function one(e,t){let n=oE(e),r=oE(t);return n===`nil`||r===`nil`?!0:n===r}function oE(e){return e==null?`nil`:typeof e==`string`?`string`:typeof e==`number`||typeof e==`bigint`?`number`:typeof e==`boolean`?`boolean`:Array.isArray(e)?`array`:e instanceof Map?`map`:e instanceof Set?`set`:`object`}function sE(e){switch(e){case`int`:return`integer (safe-integer number or bigint)`;case`truncating-int`:return`integer (finite number, truncated toward zero, or safe-integer bigint)`;case`float`:return`float (number, including NaN/Infinity, or finite-convertible bigint)`;case`T`:return`T (consumer-defined fragment)`;case`ordered`:return`orderable primitive`;case`list`:return`list`;case`dict`:return`dict (plain object)`;case`sized`:return`sized value (string, list, map, set, or dict)`;case`comparable`:return`comparable value (orderable primitive, nil, list, dict, Map, or Set)`;case`stringifiable`:return`stringifiable value (string or convertible via the engine's toString)`;case`liftable`:return`liftable value (T or string, the latter lifted via the engine's fromString)`;case`callable`:return`callable (function value)`;case`collection`:return`collection (string, array, Map, or dict)`;case`index-key`:return`index key (number, bigint, or string)`;case`sliceable`:return`sliceable value (string or array)`;case`serializable`:return`JSON-serializable value`;case`truthy`:case`reflective`:case`value`:case`string`:case`bool`:return e;default:throw Error(`invalid ArgType: ${String(e)}`)}}function sne(e){return e instanceof Error?e.message:String(e)}function cE(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function cne(e){return e==null?[]:Array.isArray(e)?e.map((e,t)=>[t,e]):typeof e==`string`?[...e].map((e,t)=>[t,e]):e instanceof Map?lE([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?lE(Object.entries(e)):[]}function lE(e){return[...e].sort((e,t)=>lne(e[0],t[0]))}function lne(e,t){if((typeof e==`number`||typeof e==`bigint`)&&(typeof t==`number`||typeof t==`bigint`)){let n=typeof e==`bigint`?Number(e):e,r=typeof t==`bigint`?Number(t):t;return n===r?0:n<r?-1:1}let n=String(e),r=String(t);return n===r?0:n<r?-1:1}function uE(e){if(e.intValue!==void 0){let t=e.intValue;return t>=BigInt(-(2**53-1))&&t<=BigInt(2**53-1)?Number(t):t}if(e.floatValue!==void 0)return e.floatValue;if(e.complexValue!==void 0)return e.complexValue;throw Error(`internal: NumberNode has none of intValue/floatValue/complexValue — parser invariant violated`)}function une(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function dne(e){if(typeof e==`number`)return e;if(typeof e==`bigint`)return Number(e);if(typeof e==`string`){let t=Number.parseFloat(e);return Number.isNaN(t)?0:t}return typeof e==`boolean`?+!!e:0}function dE(e){if(e===``)return null;let t=1,n=e;return n[0]===`+`?n=n.slice(1):n[0]===`-`&&(t=-1,n=n.slice(1)),n===``?null:/^0x[0-9a-fA-F]+$/i.test(n)?{sign:t,digits:n.slice(2),base:16}:/^0b[01]+$/i.test(n)?{sign:t,digits:n.slice(2),base:2}:/^0o[0-7]+$/i.test(n)?{sign:t,digits:n.slice(2),base:8}:n===`0`?{sign:t,digits:`0`,base:10}:n[0]===`0`?/^0[0-7]+$/.test(n)?{sign:t,digits:n.slice(1),base:8}:null:/^[0-9]+$/.test(n)?{sign:t,digits:n,base:10}:null}function fne(e){if(typeof e==`number`){let t=Math.trunc(e);return Number.isSafeInteger(t)?t:0}if(typeof e==`bigint`){let t=Number(e);return Number.isSafeInteger(t)?t:0}if(typeof e==`string`){let t=dE(e);if(t===null)return 0;let n=t.sign*Number.parseInt(t.digits,t.base);return Number.isSafeInteger(n)?n:0}return typeof e==`boolean`?+!!e:0}function pne(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=dE(e);if(t===null)return 0n;let n=t.base===16?`0x`:t.base===2?`0b`:t.base===8?`0o`:``,r=BigInt(n+t.digits);return t.sign===-1?-r:r}return typeof e==`boolean`&&e?1n:0n}function mne(e){if(!/^[+-]?[0-7]+$/.test(e))return 0;let t=e[0]===`-`?-1:1,n=e[0]===`+`||e[0]===`-`?e.slice(1):e,r=t*Number.parseInt(n,8);return Number.isSafeInteger(r)?r:0}function hne(e){return JSON.stringify(e)??`null`}function fE(){return{atoi:{fn:e=>une(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>fne(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>pne(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>dne(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>mne(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>hne(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const pE={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function mE(e){if(e===`0`)return 0;let t=!1,n=e;if(n.startsWith(`-`)?(t=!0,n=n.slice(1)):n.startsWith(`+`)&&(n=n.slice(1)),!n)return NaN;let r=0,i=/^(\d+(?:\.\d+)?)(ns|µs|us|ms|[smh])/;for(;n.length>0;){let e=i.exec(n);if(!e)return NaN;let t=parseFloat(e[1]??`0`),a=e[2];r+=t*pE[a],n=n.slice(e[0].length)}return t?-r:r}function hE(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<pE.us?`${Math.floor(n)}ns`:n<pE.ms?gE(n,pE.us,3,`µs`):n<pE.s?gE(n,pE.ms,6,`ms`):_E(n),t?`-${r}`:r}function gE(e,t,n,r){let i=Math.floor(e/t),a=Math.round(e%t);return a===0?`${i}${r}`:`${i}.${String(a).padStart(n,`0`).replace(/0+$/,``)}${r}`}function _E(e){let t=Math.floor(e/pE.h);e-=t*pE.h;let n=Math.floor(e/pE.m);e-=n*pE.m;let r=Math.floor(e/pE.s),i=e-r*pE.s,a=i===0?`${r}s`:`${r}.${String(Math.round(i)).padStart(9,`0`).replace(/0+$/,``)}s`;return t>0?`${t}h${n}m${a}`:n>0?`${n}m${a}`:a}function vE(e){return e*pE.s}function yE(e){if(e instanceof Date)return e;if(typeof e==`bigint`)return new Date(Number(e)*1e3);if(typeof e==`number`)return new Date(e*1e3);if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t;throw Error(`sprig: cannot parse date value ${JSON.stringify(e)}`)}throw Error(`sprig: unsupported date type: ${typeof e}`)}function bE(e,t){let n=t().getTime()-yE(e).getTime();return hE(Math.round(n/1e3)*1e9)}const xE=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],SE=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],CE=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],wE=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function TE(e){return e<10?`0${e}`:String(e)}function EE(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function DE(e){return e<10?` ${e}`:String(e)}function OE(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${TE(Math.floor(n/60))}${TE(n%60)}`}function kE(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${TE(Math.floor(n/60))}:${TE(n%60)}`}function AE(e){return`${e>=0?`+`:`-`}${TE(Math.floor(Math.abs(e)/60))}`}function jE(e){return e===0?`Z`:OE(e)}function ME(e){return e===0?`Z`:kE(e)}function NE(e){return e===0?`Z`:AE(e)}function PE(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const FE=[[`.000000000`,e=>`.${PE(e.ms,9,!1)}`],[`.999999999`,e=>{let t=PE(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${PE(e.ms,6,!1)}`],[`.999999`,e=>{let t=PE(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${EE(e.ms)}`],[`.999`,e=>{let t=EE(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>xE[e.month-1]??`January`],[`Monday`,e=>CE[e.weekday]??`Monday`],[`Z07:00`,e=>ME(e.offsetMinutes)],[`-07:00`,e=>kE(e.offsetMinutes)],[`Z0700`,e=>jE(e.offsetMinutes)],[`-0700`,e=>OE(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>SE[e.month-1]??`Jan`],[`Mon`,e=>wE[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>AE(e.offsetMinutes)],[`Z07`,e=>NE(e.offsetMinutes)],[`15`,e=>TE(e.hour)],[`01`,e=>TE(e.month)],[`02`,e=>TE(e.day)],[`_2`,e=>DE(e.day)],[`03`,e=>TE(e.hour12)],[`04`,e=>TE(e.minute)],[`05`,e=>TE(e.second)],[`06`,e=>TE(e.year%100)],[`PM`,e=>e.hour>=12?`PM`:`AM`],[`pm`,e=>e.hour>=12?`pm`:`am`],[`1`,e=>String(e.month)],[`2`,e=>String(e.day)],[`3`,e=>String(e.hour12)],[`4`,e=>String(e.minute)],[`5`,e=>String(e.second)]];function IE(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of FE)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const LE={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function RE(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const zE=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function BE(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=RE(new Intl.DateTimeFormat(`en-US`,{...LE,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=RE(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=VE(RE(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=zE.indexOf(r.get(`weekday`)??`Sunday`);return{year:parseInt(r.get(`year`)??`2000`,10),month:parseInt(r.get(`month`)??`1`,10),day:parseInt(r.get(`day`)??`1`,10),weekday:s===-1?0:s,hour:i,hour12:i%12||12,minute:parseInt(r.get(`minute`)??`0`,10),second:parseInt(r.get(`second`)??`0`,10),ms:e.getUTCMilliseconds(),tzAbbr:a,offsetMinutes:o}}function VE(e){if(e===`GMT`||e===`UTC`)return 0;let t=e.match(/^GMT([+-])(\d{1,2})(?::(\d{2}))?$/);if(!t)return 0;let n=t[1]===`+`?1:-1,r=parseInt(t[2]??`0`,10),i=parseInt(t[3]??`0`,10);return n*(r*60+i)}function HE(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function UE(e,t){return IE(e,BE(yE(t),HE()))}function WE(e,t,n){return IE(e,BE(yE(t),n))}function GE(e,t){let n=yE(t),r=mE(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function KE(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:hE(vE(t))}return typeof e==`bigint`?hE(vE(Number(e))):typeof e==`number`?hE(vE(e)):`0s`}const qE=36e11*24*365,JE=36e11*24*30,YE=36e11*24,XE=36e11,ZE=6e10,QE=1e9;function $E(e){let t=mE(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>qE?`${Math.floor(n/qE)}y`:n>JE?`${Math.floor(n/JE)}mo`:n>YE?`${Math.floor(n/YE)}d`:n>XE?`${Math.floor(n/XE)}h`:n>ZE?`${Math.floor(n/ZE)}m`:n>QE?`${Math.floor(n/QE)}s`:`0s`}function eD(e){let t=BE(yE(e),HE());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function tD(e,t){let n=BE(yE(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function nD(e){return e()}const rD=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],iD=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function aD(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function oD(e,t,n){return[e.slice(t,t+n),t+n]}function sD(e,t,n,r){let i=t;for(;i<e.length&&i-t<r&&e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57;)i++;if(i-t<n)throw Error(`sprig toDate: expected ${n}-${r} digits at pos ${t}`);return[parseInt(e.slice(t,i),10),i]}function cD(e,t){for(let[n,r]of rD.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function lD(e,t){for(let[n,r]of iD.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function uD(e,t){for(let n of[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`])if(e.startsWith(n,t))return t+n.length;throw Error(`sprig toDate: expected weekday name at pos ${t}`)}function dD(e,t){for(let n of[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`])if(e.startsWith(n,t))return t+n.length;throw Error(`sprig toDate: expected short weekday name at pos ${t}`)}function fD(e,t){if(e[t]===` `){let[n,r]=sD(e,t+1,1,1);return[n,r]}return sD(e,t,1,2)}function pD(e,t,n){let r=e[t]===`+`?1:e[t]===`-`?-1:0;if(r===0)throw Error(`sprig toDate: expected +/- at pos ${t}`);let i=t+1,[a,o]=sD(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=sD(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=sD(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function mD(e,t,n,r){if(e[t]===`Z`)return[0,t+1];if(r){let n=e[t]===`+`?1:e[t]===`-`?-1:0;if(n===0)throw Error(`sprig toDate: expected Z or +/- at pos ${t}`);let[r,i]=sD(e,t+1,2,2);return[n*r*60,i]}return pD(e,t,n)}function hD(e,t){let n=t;for(;n<e.length&&e.charCodeAt(n)>=65&&e.charCodeAt(n)<=90;)n++;if(n===t)throw Error(`sprig toDate: expected timezone abbreviation at pos ${t}`);return n}function gD(e,t,n){let[r,i]=oD(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function _D(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=cD(t,n);return i.month=e,[r,i]}case`Monday`:return[uD(t,n),i];case`Jan`:{let[e,r]=lD(t,n);return i.month=e,[r,i]}case`Mon`:return[dD(t,n),i];case`2006`:{let[e,r]=sD(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=sD(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=sD(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=sD(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=fD(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=sD(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=sD(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=sD(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=sD(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=sD(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=sD(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=sD(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=sD(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=sD(t,n,1,2);return i.second=e,[r,i]}case`PM`:case`pm`:{let e=t.slice(n,n+2).toLowerCase();if(e!==`am`&&e!==`pm`)throw Error(`sprig toDate: expected AM/PM at pos ${n}, got ${JSON.stringify(t.slice(n,n+2))}`);return i.isPM=e===`pm`,i.hour12=!0,[n+2,i]}case`MST`:return[hD(t,n),i];case`-0700`:{let[e,r]=pD(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=pD(t,n,!0);return i.offsetMinutes=e,[r,i]}case`-07`:{let e=t[n]===`+`?1:t[n]===`-`?-1:0;if(e===0)throw Error(`sprig toDate: expected +/- at pos ${n}`);let[r,a]=sD(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=mD(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=mD(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=mD(t,n,!1,!0);return i.offsetMinutes=e,[r,i]}case`.000000000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=gD(t,n+1,9);return i.ms=e,[r,i]}case`.999999999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(9,`0`);return i.ms=Math.round(parseInt(a,10)/1e6),[r,i]}case`.000000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=gD(t,n+1,6);return i.ms=e,[r,i]}case`.999999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(9,`0`);return i.ms=Math.round(parseInt(a,10)/1e6),[r,i]}case`.000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=gD(t,n+1,3);return i.ms=e,[r,i]}case`.999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(3,`0`);return i.ms=parseInt(a,10),[r,i]}}throw Error(`sprig toDate: unhandled token ${e}`)}const vD=`.000000000,.999999999,.000000,.999999,.000,.999,January,Monday,Z07:00,-07:00,Z0700,-0700,2006,Jan,Mon,MST,-07,Z07,15,01,02,_2,03,04,05,06,PM,pm,1,2,3,4,5`.split(`,`);function yD(e,t){let n=0,r=0,i=aD();for(;n<e.length;){let a=!1;for(let o of vD)if(e.startsWith(o,n)){let[e,s]=_D(o,t,r,i);r=e,i=s,n+=o.length,a=!0;break}if(!a){let i=e.charAt(n);if(t[r]!==i)throw Error(`sprig toDate: expected ${JSON.stringify(i)} at pos ${r}, got ${JSON.stringify(t[r])}`);n++,r++}}if(r!==t.length)throw Error(`sprig toDate: extra characters at pos ${r}: ${JSON.stringify(t.slice(r))}`);if(i.hour12){let e=i.hour%12;i.hour=i.isPM?e+12:e}let a=Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second,i.ms)-i.offsetMinutes*60*1e3;return new Date(a)}function bD(e,t){return yD(e,t)}function xD(e){return String(Math.floor(yE(e).getTime()/1e3))}function SD(e=()=>new Date){return{now:{fn:()=>nD(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>UE(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>WE(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>GE(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>eD(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>tD(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>KE(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>$E(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>bD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>bE(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>xD(e),argTypes:[`value`],arity:{kind:`exact`}}}}function CD(e){return e==null||e===!1?!0:typeof e==`number`?e===0||Number.isNaN(e):typeof e==`bigint`?e===0n:typeof e==`string`||Array.isArray(e)?e.length===0:e instanceof Map||e instanceof Set?e.size===0:typeof e==`object`?Object.keys(e).length===0:!1}function wD(...e){for(let t of e)if(!CD(t))return t}function TD(e,t){return CD(t)?e:t}function ED(e){return JSON.parse(e)}function DD(e,t,n){return AT(n)?e:t}function OD(e){return JSON.stringify(e)??`null`}function kD(e){return JSON.stringify(e,null,2)??`null`}function AD(){return{default:{fn:(e,t)=>TD(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>CD(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>wD(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>DD(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>ED(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>OD(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>kD(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function jD(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function MD(e){if(e.kind!==`call`||e.name!==`dict`||e.args.length%2!=0)return null;let t=[];for(let[n,r]of e.args.entries()){if(r.kind!==`literal`||n%2==0&&typeof r.value!=`string`)return null;t.push(r.value)}return jD(...t)}function ND(e,t){return e[t]}function PD(e,t){return t in e}function FD(e){return Object.keys(e)}function ID(e,...t){let n={...e};for(let e of t)for(let[t,r]of Object.entries(e))t in n||(n[t]=r);return n}function LD(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function RD(e,...t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e))n.has(t)||(r[t]=i);return r}function zD(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function BD(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function VD(e,t,n){return e[t]=n,e}function HD(e,t){return delete e[t],e}function UD(e){return Object.values(e)}function WD(){return{dict:{fn:(...e)=>jD(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>ND(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>VD(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>HD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>FD(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>UD(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>BD(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>zD(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>RD(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>PD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>ID(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>LD(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function GD(e){throw new Vw(e)}function KD(){return{fail:{fn:e=>GD(e),argTypes:[`string`],arity:{kind:`exact`}}}}new TextEncoder,new Map(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`).map((e,t)=>[e,t])),new TextDecoder,new TextEncoder,new TextDecoder,new TextEncoder;function qD(...e){for(let t of e)if(CD(t))return!1;return!0}function JD(...e){for(let t of e)if(!CD(t))return!0;return!1}function YD(e,t){return[...e,t]}function XD(e,t){let n=Math.max(1,e),r=[];for(let e=0;e<t.length;e+=n)r.push(t.slice(e,e+n));return r}function ZD(e){return e.filter(e=>!CD(e))}function QD(...e){let t=[];for(let n of e)t.push(...n);return t}const $D={line:0,column:0,offset:0};function eO(e,t,n,r){return new Rw(e,t,n,r,$D)}function tO(...e){if(e.length<3)throw eO(`dig`,0,`at least 3 arguments (...keys, default, dict)`,`${e.length} argument${e.length===1?``:`s`}`);let t=e[e.length-1],n=e[e.length-2],r=e.slice(0,-2);if(!rO(t))throw eO(`dig`,e.length-1,`dict`,iO(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw eO(`dig`,e,`string`,iO(r[e]));return nO(t,n,r,e.length)}function nO(e,t,n,r){let i=n[0];if(!Object.hasOwn(e,i))return t;let a=e[i];if(n.length===1)return a;if(!rO(a))throw eO(`dig`,r-1,`dict at intermediate key`,iO(a));return nO(a,t,n.slice(1),r)}function rO(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function iO(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function aO(e){return e[0]}function oO(e,t){return t.some(t=>ET(t,e))}function sO(e){return e.slice(0,-1)}function cO(e){return e[e.length-1]}function lO(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function uO(...e){return e}function dO(e,t){return[t,...e]}function fO(e){return e.slice(1)}function pO(e){return[...e].reverse()}function mO(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function hO(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function gO(e){let t=[];for(let n of e)t.some(e=>ET(e,n))||t.push(n);return t}function _O(e,...t){return e.filter(e=>!t.some(t=>ET(t,e)))}function vO(){return{list:{fn:(...e)=>uO(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>aO(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>cO(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>fO(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>sO(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>lO(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>pO(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>gO(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>_O(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>oO(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>ZD(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>mO(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>QD(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>XD(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>dO(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>YD(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>hO(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>YD(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>uO(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>tO(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>qD(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>JD(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function yO(...e){return e.reduce((e,t)=>e+t,0)}function bO(e){return e+1}function xO(e){return e+1}function SO(...e){return e.reduce((e,t)=>e+t,0)}function CO(e){return Math.ceil(e)}function wO(e,t){return Math.trunc(e/t)}function TO(e,...t){return t.reduce((e,t)=>e/t,e)}function EO(e){return Math.floor(e)}function DO(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function OO(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function kO(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function AO(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function jO(e,t){return e%t}function MO(...e){return e.reduce((e,t)=>e*t,1)}function NO(...e){return e.reduce((e,t)=>e*t,1)}function PO(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function FO(e,t,n){let r=[];if(t<e){if(n>=0)return r;for(let i=e;i>t;i+=n)r.push(i);return r}if(n<=0)return r;for(let i=e;i<t;i+=n)r.push(i);return r}function IO(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),FO(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return FO(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:FO(n,i+t,r).join(` `)}default:return``}}function LO(e,t){return e-t}function RO(e,...t){return t.reduce((e,t)=>e-t,e)}function zO(e){return FO(0,e,e<0?-1:1)}function BO(){return{add:{fn:(...e)=>yO(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>LO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>MO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>wO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>jO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>kO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>DO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>EO(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>CO(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>PO(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>SO(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>RO(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>NO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>TO(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>bO(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>xO(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>OO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>AO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>DO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>IO(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>zO(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>FO(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function VO(e){return Array.from(e)}function HO(e,t){return e===``?VO(t):t.split(e)}function UO(e,t){let n=VO(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function WO(e,t,n){let r=VO(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const GO={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},KO=/^[-_\s]$/,qO=/^\p{P}$/u,JO=/^\p{L}$/u,YO=/^\p{Lu}$/u,XO=/^\p{N}$/u;function ZO(e){return e!==void 0&&KO.test(e)}function QO(e){return e!==void 0&&JO.test(e)}function $O(e){return e!==void 0&&YO.test(e)}function ek(e){return e!==void 0&&XO.test(e)}function tk(e){return e!==void 0&&qO.test(e)}function nk(e,t){if(t>=e.length)return{word:{wt:GO.Invalid,text:``},next:t};let n=e[t],r=t+1;if(ZO(n)){for(;r<e.length&&ZO(e[r]);)r++;return{word:{wt:GO.Connector,text:e.slice(t,r).join(``)},next:r}}if(tk(n)){for(;r<e.length&&tk(e[r]);)r++;return{word:{wt:GO.Punct,text:e.slice(t,r).join(``)},next:r}}if($O(n)){if(r>=e.length)return{word:{wt:GO.UpperCase,text:n},next:r};if($O(e[r])){let n=r;for(;n<e.length&&$O(e[n]);)n++;return n<e.length&&QO(e[n])?{word:{wt:GO.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:GO.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(QO(e[r])){let n=r+1;for(;n<e.length&&QO(e[n])&&!$O(e[n]);)n++;return{word:{wt:GO.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:GO.UpperCase,text:n},next:r}}if(QO(n)){for(;r<e.length&&QO(e[r])&&!$O(e[r]);)r++;return{word:{wt:GO.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(ek(n)){for(;r<e.length&&ek(e[r]);)r++;return{word:{wt:GO.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!ZO(e[r])&&!QO(e[r])&&!ek(e[r])&&!tk(e[r]);)r++;return{word:{wt:GO.Other,text:e.slice(t,r).join(``)},next:r}}function rk(e,t,n){if(t.wt!==GO.UpperCase&&t.wt!==GO.Connector){e.push(t.text);return}for(let r of t.text)ZO(r)?e.push(n):$O(r)?e.push(r.toLowerCase()):e.push(r)}function ik(e,t){if(e.length===0)return``;let n=VO(e),r=[],{word:i,next:a}=nk(n,0);for(;a<n.length;){i.wt!==GO.Connector&&rk(r,i,t);let e=i,o=i;if({word:i,next:a}=nk(n,a),e.wt===GO.Number){for(;i.wt===GO.Alphabet||i.wt===GO.Number;)rk(r,i,t),{word:i,next:a}=nk(n,a);i.wt!==GO.Invalid&&i.wt!==GO.Punct&&i.wt!==GO.Connector&&r.push(t);continue}if(e.wt===GO.Connector){rk(r,o,t);continue}if(e.wt===GO.Punct)continue;if(i.wt!==GO.Number){i.wt!==GO.Connector&&i.wt!==GO.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=nk(n,a),i.wt!==GO.Alphabet){rk(r,s,t),i.wt!==GO.Connector&&i.wt!==GO.Punct&&r.push(t);continue}for(r.push(t),rk(r,s,t);i.wt===GO.Alphabet||i.wt===GO.Number;)rk(r,i,t),{word:i,next:a}=nk(n,a);i.wt!==GO.Invalid&&i.wt!==GO.Connector&&i.wt!==GO.Punct&&r.push(t)}return rk(r,i,t),r.join(``).toLowerCase()}function ak(e){if(e.length===0)return``;let t=VO(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!ZO(i)){i=i.toUpperCase();break}n.push(i)}if(r>=t.length)return t.length>0&&n.push(i),n.join(``);for(;r<t.length;){let e=i;if(i=t[r],r++,ZO(i)&&ZO(e)){n.push(e);continue}ZO(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function ok(e){return ak(e)}function sk(...e){return e.join(` `)}function ck(e,t){return t.includes(e)}function lk(e,t){return t.startsWith(e)}function uk(e,t){return t.endsWith(e)}function dk(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
64
+ `?(this.line+=1,this.column=1):this.column+=1}}advanceTo(e){for(;this.offset<e;)this.advanceBy(1)}makeToken(e,t,n,r={}){return Object.freeze({type:e,value:t,pos:n,...r.trimLeft===void 0?{}:{trimLeft:r.trimLeft},...r.trimRight===void 0?{}:{trimRight:r.trimRight}})}};function Jw(e){return e===` `||e===` `||e===`\r`||e===`
65
+ `}function Yw(e){return e===`+`||e===`-`}function Xw(e){return e>=`0`&&e<=`9`}function Zw(e){return Xw(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function Qw(e){return e>=`0`&&e<=`7`}function $w(e){return e===`0`||e===`1`}function eT(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function tT(e){return eT(e)||e===`_`}function nT(e){return tT(e)||Xw(e)}let rT,iT;function aT(e,t){return iT(e,t)}var oT=class e{static EMPTY=new e(new Map,void 0);#e;#t;constructor(e,t){this.#e=e,this.#t=t}static{rT=(t,n)=>new e(t,n),iT=(e,t)=>e.#e.get(t)??(e.#t&&iT(e.#t,t))}has(e){return iT(this,e)!==void 0}};function sT(e,t,n=oT.EMPTY){return new cT(e,t,n).parseTemplate()}var cT=class{lex;buf=[];defines=new Map;inherit;source;rangeDepth=0;constructor(e,t,n){this.source=e,this.inherit=n,this.lex=t?new qw(e,t):new qw(e)}peek(e=0){for(;this.buf.length<=e;)this.buf.push(this.lex.next());return this.buf[e]}next(){return this.buf.length>0?this.buf.shift():this.lex.next()}expect(e,t){let n=this.next();if(n.type!==e)throw this.errAt(n,`expected ${t}`,{expected:t,found:dT(n)});return n}errAt(e,t,n={}){return new Nw(t,e.pos,{...n,source:this.source})}parseTemplate(){let e=this.parseList();if(this.peek().type!==`EOF`){let e=this.peek(),t=this.peek(1);if(e.type===`LeftDelim`&&(t.type===`Else`||t.type===`End`)){let n=t.type===`Else`?`else`:`end`;throw this.errAt(e,`unexpected \`{{${n}}}\` outside of \`if\`, \`range\`, \`with\`, or \`block\``,{found:`{{${n}}}`})}throw this.errAt(e,`unexpected ${dT(e)}`,{found:dT(e)})}return{root:e,defines:rT(this.defines,this.inherit),ownDefines:this.defines,source:this.source}}parseList(){let e=this.peek().pos,t=[];for(;;){let n=this.peek();if(n.type===`EOF`)break;if(n.type===`Text`){this.next(),t.push({type:`Text`,pos:n.pos,text:n.value});continue}if(n.type===`Comment`){this.next();let e=uT(n);t.push({type:`Comment`,pos:n.pos,text:n.value,trim:e});continue}if(n.type===`LeftDelim`){let n=this.peek(1).type;if(n===`Else`||n===`End`)return lT(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${dT(n)} at top level`,{found:dT(n)})}return lT(e,t)}parseAction(){let e=this.expect(`LeftDelim`,"`{{`"),t=e.trimLeft===!0,n=this.peek();switch(n.type){case`If`:return this.next(),this.parseBranch(`If`,e.pos,t);case`Range`:return this.next(),this.parseBranch(`Range`,e.pos,t);case`With`:return this.next(),this.parseBranch(`With`,e.pos,t);case`Break`:return this.next(),this.parseBreakOrContinue(`Break`,e.pos,t);case`Continue`:return this.next(),this.parseBreakOrContinue(`Continue`,e.pos,t);case`Template`:return this.next(),this.parseTemplateInvocation(e.pos,t);case`Block`:return this.next(),this.parseBlock(e.pos,t);case`Define`:return this.next(),this.parseDefine(e.pos,t),null;case`RightDelim`:throw this.errAt(n,`empty action`,{expected:`pipeline`});default:{let n=this.parsePipeline(),r=this.expect(`RightDelim`,"`}}`");return{type:`Action`,pos:e.pos,pipe:n,trim:{trimLeft:t,trimRight:r.trimRight===!0}}}}}parseBranch(e,t,n){let r=this.parsePipeline();this.expect(`RightDelim`,"`}}`"),e===`Range`&&(this.rangeDepth+=1);let i=this.parseList();e===`Range`&&--this.rangeDepth;let a=this.parseElsePart(),o={trimLeft:n,trimRight:a.endConsumed?a.endRight:this.consumeEnd()},s=a.list?{pipe:r,list:i,elseList:a.list,trim:o}:{pipe:r,list:i,trim:o};switch(e){case`If`:return{type:`If`,pos:t,...s};case`Range`:return{type:`Range`,pos:t,...s};case`With`:return{type:`With`,pos:t,...s}}}parseBreakOrContinue(e,t,n){if(this.rangeDepth===0)throw new Nw(`{{${e===`Break`?`break`:`continue`}}} outside of {{range}}`,t,{source:this.source});let r={trimLeft:n,trimRight:this.expect(`RightDelim`,"`}}`").trimRight===!0};return e===`Break`?{type:`Break`,pos:t,trim:r}:{type:`Continue`,pos:t,trim:r}}parseElsePart(){if(this.peek().type!==`LeftDelim`||this.peek(1).type!==`Else`)return{list:void 0,endRight:!1,endConsumed:!1};let e=this.next();if(this.next(),this.peek().type===`If`){this.next();let t=this.parseBranch(`If`,e.pos,e.trimLeft===!0);return{list:{type:`List`,pos:e.pos,nodes:[t]},endRight:t.trim.trimRight,endConsumed:!0}}return this.expect(`RightDelim`,"`}}`"),{list:this.parseList(),endRight:!1,endConsumed:!1}}consumeEnd(){return this.expect(`LeftDelim`,"`{{end}}`"),this.expect(`End`,"`end`"),this.expect(`RightDelim`,"`}}`").trimRight===!0}parseTemplateInvocation(e,t){let n=this.parseQuotedName(),r=this.peek().type===`RightDelim`?void 0:this.parsePipeline(),i={trimLeft:t,trimRight:this.expect(`RightDelim`,"`}}`").trimRight===!0};return r?{type:`Template`,pos:e,name:n,pipe:r,trim:i}:{type:`Template`,pos:e,name:n,trim:i}}parseBlock(e,t){let n=this.parseQuotedName(),r=this.peek().type===`RightDelim`?void 0:this.parsePipeline();this.expect(`RightDelim`,"`}}`");let i=this.rangeDepth;this.rangeDepth=0;let a=this.parseList();this.rangeDepth=i;let o={trimLeft:t,trimRight:this.consumeEnd()};return!this.defines.has(n)&&!this.inherit.has(n)&&this.defines.set(n,{list:a,source:this.source}),r?{type:`Block`,pos:e,name:n,pipe:r,list:a,trim:o}:{type:`Block`,pos:e,name:n,list:a,trim:o}}parseDefine(e,t){let n=this.parseQuotedName();this.expect(`RightDelim`,"`}}`");let r=this.rangeDepth;this.rangeDepth=0;let i=this.parseList();if(this.rangeDepth=r,this.consumeEnd(),this.defines.has(n)||this.inherit.has(n))throw new Nw(`redefinition of template ${JSON.stringify(n)}`,i.pos,{source:this.source});this.defines.set(n,{list:i,source:this.source})}parseQuotedName(){let e=this.next();if(e.type!==`String`)throw this.errAt(e,`expected template name (quoted string)`,{expected:`string`,found:dT(e)});return yT(e.value,e.pos,this.source)}parsePipeline(){let e=this.peek().pos,t=this.tryParseDecls(),n=[this.parseCommand()];for(;this.peek().type===`Pipe`;){this.next();let e=this.peek();if(!fT(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:dT(e)});n.push(this.parseCommand())}return{type:`Pipe`,pos:e,decls:t?.vars??[],isAssign:t?.isAssign??!1,cmds:n}}tryParseDecls(){if(this.peek().type!==`Variable`)return;let e=1;for(;this.peek(e).type===`Comma`;){if(this.peek(e+1).type!==`Variable`)return;e+=2}let t=this.peek(e).type;if(t!==`Declare`&&t!==`Assign`)return;let n=[pT(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(pT(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;fT(this.peek().type);)t.push(this.parsePrimary());return{type:`Command`,pos:e,args:t}}parsePrimary(){let e=this.next();switch(e.type){case`Dot`:return{type:`Dot`,pos:e.pos};case`Field`:return{type:`Field`,pos:e.pos,idents:e.value.slice(1).split(`.`)};case`Variable`:return pT(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:yT(e.value,e.pos,this.source)};case`Number`:return hT(e);case`Char`:return gT(e,this.source);case`Bool`:return{type:`Bool`,pos:e.pos,value:e.value===`true`};case`Nil`:return{type:`Nil`,pos:e.pos};case`LeftParen`:return this.parseChainOrPipe(e.pos);default:throw this.errAt(e,`expected command argument, found ${dT(e)}`,{expected:`command argument`,found:dT(e)})}}parseChainOrPipe(e){let t=this.parsePipeline(),n=this.expect(`RightParen`,"`)`"),r=[],i=n.pos.offset+1,a=this.peek();return a.type===`Field`&&a.pos.offset===i&&(this.next(),r.push(...a.value.slice(1).split(`.`))),r.length===0?t:{type:`Chain`,pos:e,node:t,fields:r}}};function lT(e,t){return{type:`List`,pos:e,nodes:t}}function uT(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function dT(e){return e.type===`EOF`?`end of input`:e.value||e.type}function fT(e){switch(e){case`Dot`:case`Field`:case`Variable`:case`Identifier`:case`String`:case`Number`:case`Char`:case`Bool`:case`Nil`:case`LeftParen`:return!0;default:return!1}}function pT(e){return{type:`Variable`,pos:e.pos,idents:mT(e.value)}}function mT(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function hT(e){let t=e.value,n=t.replace(/_/g,``),r=n.toLowerCase().endsWith(`i`),i=r?n.slice(0,-1):n,a=!r&&(i.includes(`.`)||!i.startsWith(`0x`)&&!i.startsWith(`0X`)&&/[eE]/.test(i)||(i.startsWith(`0x`)||i.startsWith(`0X`))&&/[pP]/.test(i)),o=!r&&!a,s={type:`Number`,pos:e.pos,text:t,isInt:o,isUint:!1,isFloat:a,isComplex:r};if(o){let e=_T(i);return{...s,intValue:e}}if(a){let e=vT(i);return{...s,floatValue:e}}let c=vT(i);return{...s,complexValue:[0,c]}}function gT(e,t){let n=bT(e.value,e.pos,t);return{type:`Number`,pos:e.pos,text:e.value,isInt:!0,isUint:!1,isFloat:!1,isComplex:!1,intValue:BigInt(n)}}function _T(e){let t=1n,n=e;return n.startsWith(`+`)?n=n.slice(1):n.startsWith(`-`)&&(t=-1n,n=n.slice(1)),t*BigInt(n)}function vT(e){return Number(e)}function yT(e,t,n){if(e.startsWith("`"))return e.slice(1,-1);let r=``;for(let i=1;i<e.length-1;i++){let a=e[i];if(a!==`\\`){r+=a;continue}let o=e[++i];switch(o){case`n`:r+=`
66
+ `;break;case`t`:r+=` `;break;case`r`:r+=`\r`;break;case`\\`:r+=`\\`;break;case`"`:r+=`"`;break;case`'`:r+=`'`;break;case`a`:r+=`\x07`;break;case`b`:r+=`\b`;break;case`f`:r+=`\f`;break;case`v`:r+=`\v`;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:{let t=o+(e[i+1]??``)+(e[i+2]??``);i+=2,r+=String.fromCodePoint(Number.parseInt(t,8));break}case`x`:{let t=(e[i+1]??``)+(e[i+2]??``);i+=2,r+=String.fromCodePoint(Number.parseInt(t,16));break}case`u`:{let t=e.slice(i+1,i+5);i+=4,r+=String.fromCodePoint(Number.parseInt(t,16));break}case`U`:{let t=e.slice(i+1,i+9);i+=8,r+=String.fromCodePoint(Number.parseInt(t,16));break}default:throw new Nw(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function bT(e,t,n){let r=yT(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new Nw(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function xT(e,t){if(t(e)!==!1)for(let n of ST(e))xT(n,t)}function ST(e){switch(e.type){case`Text`:case`Comment`:case`Dot`:case`Nil`:case`Bool`:case`Number`:case`String`:case`Identifier`:case`Field`:case`Variable`:case`Break`:case`Continue`:return[];case`List`:return e.nodes;case`Chain`:return[e.node];case`Command`:return e.args;case`Pipe`:return[...e.decls,...e.cmds];case`Action`:return[e.pipe];case`If`:case`Range`:case`With`:return e.elseList?[e.pipe,e.list,e.elseList]:[e.pipe,e.list];case`Template`:return e.pipe?[e.pipe]:[];case`Block`:return e.pipe?[e.pipe,e.list]:[e.list];default:return Ww(e)}}const CT=Symbol(`go-template-js.MISSING`);function wT(e,t){if(e==null)return CT;if(e instanceof Map)return e.has(t)?e.get(t):CT;if(Array.isArray(e))return CT;if(typeof e==`object`){let n=e;return t in n?n[t]:CT}return CT}function TT(e,t){let n=e;for(let e of t){if(n===CT)return CT;n=wT(n,e)}return n}function ET(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||e===void 0||t===void 0||typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length?e.every((e,n)=>ET(e,t[n])):!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!ET(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}if(typeof e==`object`&&typeof t==`object`){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length?n.every(n=>ET(e[n],t[n])):!1}return!1}const DT=new WeakSet;function OT(e){return DT.add(e),e}function kT(e){return DT.has(e)}function AT(e){return e==null||e===!1?!1:typeof e==`number`?e!==0&&!Number.isNaN(e):typeof e==`bigint`?e!==0n:typeof e==`string`||Array.isArray(e)?e.length>0:e instanceof Map||e instanceof Set?e.size>0:typeof e==`object`?Object.keys(e).length>0:!!e}function jT(e,t){return{eq:{fn:(e,...t)=>t.some(t=>PT(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!PT(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>FT(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>FT(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>FT(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>FT(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>IT(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=LT(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>Nte(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>VT(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${VT(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>Vte(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>WT(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>WT(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>Fte(VT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>Rte(VT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>Bte(VT(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!AT(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function MT(){return{and:OT({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!AT(t))return t;return t}}),or:OT({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),AT(t))return t;return t}})}}function NT(e,t){return{...jT(e,t),...MT()}}function PT(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):ET(e,t)}function FT(e,t){if(typeof e==`bigint`&&typeof t==`bigint`)return e===t?0:e<t?-1:1;if(typeof e==`bigint`||typeof t==`bigint`){let n=typeof e==`bigint`?e:BigInt(Math.trunc(Number(e))),r=typeof t==`bigint`?t:BigInt(Math.trunc(Number(t)));return n===r?0:n<r?-1:1}let n=e,r=t;return n===r?0:n<r?-1:1}function IT(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function LT(e,t){if(Array.isArray(e)||typeof e==`string`){let n=RT(t,e.length);if(n===e.length)throw Error(`index out of range: ${n}`);return e[n]}if(e instanceof Map)return e.get(t);if(typeof e==`object`&&e){if(typeof t!=`string`)throw Error(`index: object index must be string, got ${zT(t)}`);return e[t]}throw Error(`index: cannot index ${zT(e)}`)}function RT(e,t){let n=typeof e==`bigint`?Number(e):e;if(typeof n!=`number`||!Number.isInteger(n))throw Error(`cannot index slice/array with type ${BT(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function Nte(e,t){if(t.length>3)throw Error(`too many slice indexes: ${t.length}`);if(typeof e==`string`&&t.length>2)throw Error(`cannot 3-index slice a string`);let n=e.length,r=[0,n,n];t.forEach((e,t)=>{r[t]=RT(e,n)});let[i,a,o]=r;if(i>a)throw Error(`invalid slice index: ${i} > ${a}`);if(a>o)throw Error(`invalid slice index: ${a} > ${o}`);return e.slice(i,a)}function zT(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function BT(e){return e==null?`<nil>`:typeof e==`string`?`string`:typeof e==`boolean`?`bool`:typeof e==`bigint`?`int64`:typeof e==`number`?Number.isInteger(e)?`int`:`float64`:Array.isArray(e)?`[]interface {}`:e instanceof Map||typeof e==`object`?`map[string]interface {}`:typeof e}function VT(e,t){let n=``,r=!1;for(let i=0;i<e.length;i++){let a=e[i],o=typeof a==`string`;i>0&&!r&&!o&&(n+=` `),n+=HT(a,t),r=o}return n}function HT(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const Pte={"\0":`�`,'"':`&#34;`,"'":`&#39;`,"&":`&amp;`,"<":`&lt;`,">":`&gt;`};function Fte(e){return e.replace(/[\0"'&<>]/g,e=>Pte[e]??e)}const Ite={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},Lte=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function Rte(e){let t=``;for(let n of e){let e=Ite[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!Lte.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const zte=new TextEncoder;function Bte(e){let t=``,n=zte.encode(e);for(let e of n)e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===45||e===46||e===95||e===126?t+=String.fromCharCode(e):e===32?t+=`+`:t+=`%${e.toString(16).toUpperCase().padStart(2,`0`)}`;return t}function Vte(e,t,n,r){let i=``,a=0,o=0;for(;o<e.length;){let s=e[o];if(s!==`%`){i+=s,o+=1;continue}if(e[o+1]===`%`){i+=`%`,o+=2;continue}let c=o+1;for(;c<e.length&&`+-# 0`.includes(e[c]??``);)c+=1;for(;c<e.length&&e[c]!==void 0&&/[0-9]/.test(e[c]);)c+=1;if(e[c]===`.`)for(c+=1;c<e.length&&e[c]!==void 0&&/[0-9]/.test(e[c]);)c+=1;let l=e[c],u=e.slice(o+1,c),d=t[a++];i+=Hte(l??``,u,d,n,r),o=c+1}return i}function Hte(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?UT(t,n):UT(t,HT(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${BT(n)}=${HT(n,r)})`:UT(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return UT(t,WT(n,r,i));case`q`:return UT(t,JSON.stringify(HT(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${BT(n)}=${HT(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return UT(t,Number(n).toFixed(i))}case`t`:return UT(t,AT(n)?`true`:`false`);case`x`:if(typeof n==`string`){let e=new TextEncoder().encode(n),r=``;for(let t of e)r+=t.toString(16).padStart(2,`0`);return UT(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${BT(n)}=${HT(n,r)})`:typeof n==`bigint`?UT(t,n.toString(16)):UT(t,Math.trunc(n).toString(16));default:return`%!${e}(${BT(n)}=${HT(n,r)})`}}function UT(e,t){let n=e.match(/^([+\-# 0]*)/)?.[1]??``,r=e.slice(n.length).match(/^(\d+)/);if(!r)return t;let i=Number(r[1]);if(t.length>=i)return t;let a=` `.repeat(i-t.length);return n.includes(`-`)?t+a:a+t}function WT(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>WT(e,t,n)).join(` `)}]`:e instanceof Map?GT([...e.entries()],t,n):KT(e)?GT(Object.entries(e),t,n):String(e)}function GT(e,t,n){let r=e=>WT(e,t,n),i=e=>typeof e==`number`||typeof e==`bigint`,a=([e],[t])=>{if(i(e)&&i(t))return e<t?-1:+(e>t);if(i(e)!==i(t))return i(e)?-1:1;let[n,a]=[r(e),r(t)];return n<a?-1:+(n>a)};return`map[${[...e].sort(a).map(([e,t])=>`${r(e)}:${r(t)}`).join(` `)}]`}function KT(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Map||e instanceof Set)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Ute(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function qT(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function Wte(e,t){let n=e;for(;n!==void 0;){if(n.vars.has(t))return{found:!0,value:n.vars.get(t)};n=n.parent}return{found:!1}}function JT(e,t,n){e.vars.set(t,n)}const YT=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],Gte=new Set([`default`,`zero`,`error`]);function Kte(e){if(e===void 0)return`default`;if(Gte.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${XT(e)}`)}function XT(e){return typeof e==`string`?JSON.stringify(e):e===null?`null`:e===void 0?`undefined`:typeof e==`bigint`?`${e}n`:typeof e==`number`||typeof e==`boolean`?String(e):typeof e==`symbol`?e.toString():typeof e==`function`?`[Function]`:`[${typeof e}]`}function qte(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${XT(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${XT(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${XT(e.right)}`);return{left:e.left,right:e.right}}}function Jte(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function Yte(e){let t=new Set(YT);for(let[n,r]of Object.entries(e)){if(r.argTypes.forEach((e,r)=>{if(!t.has(e))throw Error(`EngineConfig.funcs.${n}: argTypes[${r}] is ${JSON.stringify(e)}, which is not an ArgType; declare one of ${YT.join(`, `)}`)}),Jte(r.arity)&&r.argTypes.length===0)throw Error(`EngineConfig.funcs.${n}: arity ${JSON.stringify(r.arity.kind)} needs at least one declared argType (it reads its repeating slot from the end of argTypes); declare the slots the Go signature has, or use { kind: "exact" }`);if(r.arity.kind===`alternating`&&(!Number.isSafeInteger(r.arity.minimum)||r.arity.minimum<0))throw Error(`EngineConfig.funcs.${n}: arity "alternating" needs a non-negative integer minimum, got ${String(r.arity.minimum)}; the gate rejects every count below it, so a negative or non-finite minimum would disable the lower bound`)}return e}const ZT=Object.freeze({kind:`break`}),QT=Object.freeze({kind:`continue`}),Xte={kind:`none`};let $T;(class e{source;_evaluate;_defines;_referencedFunctions;_referencedCalls;constructor(e,t,n,r,i){this.source=e,this._evaluate=t,this._defines=n,this._referencedFunctions=r,this._referencedCalls=i}static{$T=(t,n,r,i,a)=>new e(t,n,r,i,a)}defines(){return this._defines}evaluate(e){return this._evaluate(e)}referencedFunctions(){return this._referencedFunctions}referencedCalls(){return this._referencedCalls}});function Zte(e){let t=new Set,n=e=>{xT(e,e=>{e.type===`Identifier`&&t.add(e.ident)})};n(e.root);for(let t of e.ownDefines.values())n(t.list);return t}const eE={kind:`dynamic`};function tE(e){switch(e.type){case`String`:return{kind:`literal`,value:e.value};case`Bool`:return{kind:`literal`,value:e.value};case`Nil`:return{kind:`literal`,value:null};case`Number`:{let t=lE(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:eE}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return eE;let t=e.cmds[0];if(t===void 0)return eE;let n=t.args[0];return n===void 0||n.type!==`Identifier`?eE:{kind:`call`,name:n.ident,args:t.args.slice(1).map(tE)}}default:return eE}}function Qte(e){let t=[],n=e=>{xT(e,e=>{if(e.type!==`Command`)return;let n=e.args[0];if(n===void 0||n.type!==`Identifier`)return;let r=e.args.slice(1).map(tE);t.push({name:n.ident,args:r.map(e=>e.kind===`literal`&&typeof e.value==`string`?e.value:null),argExprs:r})})};n(e.root);for(let t of e.ownDefines.values())n(t.list);return t}var $te=class{fromString;toString;isT;funcs;missingKey;delims;constructor(e){this.fromString=e.fromString;let t=Object.hasOwn(e,`toString`)?e.toString:void 0;this.toString=t??iE,this.isT=e.isT??nE,this.missingKey=Kte(e.missingKey),this.delims=qte(e.delims),this.funcs=Yte({...NT(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=sT(e,this.delims,t);return $T(n.source,e=>this.evalParsed(n,e),n.defines,Zte(n),Qte(n))}compile(e){let t=this.parse(e);return e=>t.evaluate(e)}evaluate(e,t){return e.evaluate(t)}evalParsed(e,t){let n=[],r=Ute(t),i={out:n,defines:e.defines,source:e.source};return this.evalList(e.root,r,i),n}evalList(e,t,n){for(let r of e.nodes)this.evalNode(r,t,n)}evalNode(e,t,n){switch(e.type){case`Text`:n.out.push(this.fromString(e.text));return;case`Comment`:return;case`Action`:{let r=this.evalAction(e,t,n);e.pipe.decls.length===0&&this.emitFromValue(r,n);return}case`List`:this.evalList(e,t,n);return;case`If`:this.evalIf(e,t,n);return;case`Range`:this.evalRange(e,t,n);return;case`With`:this.evalWith(e,t,n);return;case`Break`:throw ZT;case`Continue`:throw QT;case`Template`:this.evalTemplateInvoke(e,t,n);return;case`Block`:this.evalBlock(e,t,n);return;case`Pipe`:case`Command`:case`Identifier`:case`Field`:case`Variable`:case`Chain`:case`Dot`:case`Nil`:case`Bool`:case`Number`:case`String`:throw new Pw(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:Ww(e)}}evalIf(e,t,n){AT(this.evalPipe(e.pipe,t,n))?this.evalList(e.list,t,n):e.elseList&&this.evalList(e.elseList,t,n)}evalWith(e,t,n){let r=this.evalPipe(e.pipe,t,n);if(AT(r)){let i=qT(t,r);this.evalList(e.list,i,n)}else e.elseList&&this.evalList(e.elseList,t,n)}evalRange(e,t,n){let r=this.evalPipeWithoutDecls(e.pipe,t,n),i=e.pipe.decls,a=lne(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=qT(t,o);if(i.length===1)JT(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;JT(a,e,r),JT(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===QT)continue;throw e}}}catch(e){if(e===ZT)return;throw e}}evalTemplateInvoke(e,t,n){let r=aT(n.defines,e.name);if(!r)throw new Pw(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=qT(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot);this.evalList(r.list,i,{out:n.out,defines:n.defines,source:r.source})}evalBlock(e,t,n){let r=qT(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=aT(n.defines,e.name)??{list:e.list,source:n.source};this.evalList(i.list,r,{out:n.out,defines:n.defines,source:i.source})}evalAction(e,t,n){return this.evalPipe(e.pipe,t,n)}evalPipe(e,t,n){if(e.cmds.length===0)throw new Pw(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,Xte);for(let i=1;i<e.cmds.length;i++){let a=e.cmds[i];r=this.evalCommand(a,t,n,{kind:`value`,value:r})}if(e.decls.length>0)for(let n of e.decls)JT(t,n.idents[0]??`$`,r);return r}evalPipeWithoutDecls(e,t,n){let r={type:`Pipe`,pos:e.pos,decls:[],isAssign:!1,cmds:e.cmds};return this.evalPipe(r,t,n)}evalCommand(e,t,n,r){if(e.args.length===0)throw new Pw(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new Pw(`cannot apply arguments to a ${i.type} primary; only functions take arguments`,e.pos,{source:n.source});return this.evalPrimary(i,t,n)}let a=this.funcs[i.ident];if(!a)throw new Fw(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=kT(a),c=o.map(e=>s?()=>this.evalPrimary(e,t,n):this.evalPrimary(e,t,n));if(r.kind===`value`){let e=r.value;c.push(s?()=>e:e)}return this.invoke(i.ident,a,c,e.pos,n)}invoke(e,t,n,r,i){ene(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof Lw?new Lw(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof Bw?new Bw(t.message,r,{source:i.source}):t instanceof Mw?t:new Pw(`error calling ${e}: ${cne(t)}`,r,{source:i.source,cause:t})}}evalPrimary(e,t,n){switch(e.type){case`Dot`:return t.dot;case`Nil`:return null;case`Bool`:return e.value;case`Number`:return lE(e);case`String`:return e.value;case`Field`:return this.resolveFieldChain(t.dot,e.idents,e.pos,n);case`Variable`:return this.resolveVariable(e.idents,t,e.pos,n);case`Identifier`:{let t=this.funcs[e.ident];if(!t)throw new Fw(e.ident,e.pos,{source:n.source,available:Object.keys(this.funcs)});return this.invoke(e.ident,t,[],e.pos,n)}case`Chain`:return this.resolveFieldChain(this.evalPrimary(e.node,t,n),e.fields,e.pos,n);case`Pipe`:return this.evalPipe(e,t,n);default:throw new Pw(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=TT(e,t);if(i!==CT)return i;if(this.missingKey===`error`)throw new zw(t,n,{source:r.source})}resolveVariable(e,t,n,r){let i=e[0]??`$`;if(i===`$`){let i=e.slice(1);return i.length===0?t.root:this.resolveFieldChain(t.root,i,n,r)}let a=Wte(t,i);if(!a.found)throw new Pw(`undefined variable ${i}`,n,{source:r.source});let o=e.slice(1);return o.length===0?a.value:this.resolveFieldChain(a.value,o,n,r)}emitFromValue(e,t){if(e==null){t.out.push(this.fromString(`<no value>`));return}if(typeof e==`string`){t.out.push(this.fromString(e));return}if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`){t.out.push(this.fromString(String(e)));return}if(this.isT(e)){t.out.push(e);return}t.out.push(this.fromString(WT(e,this.toString,this.isT)))}};const nE=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function rE(e){return new $te(e)}function ene(e,t,n,r,i,a=iE,o=ine,s=nE){let{argTypes:c,arity:l}=t,u=tne(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new Iw(e,u,n.length,r,{source:i});let d=nne(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!rne(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new Rw(e,t+1,l,r,{source:i}):new Lw(e,t+1,oE(c),sE(l),r,{source:i});if(c===`liftable`&&typeof l==`string`&&(n[t]=o(l)),c===`truncating-int`?n[t]=Math.trunc(Number(l)):(c===`int`||c===`float`)&&(n[t]=Number(l)),c===`ordered`){if(f===-1)f=t;else if(!one(n[f],l))throw new Lw(e,t+1,`${oE(`ordered`)} of the same kind as ${sE(n[f])}`,sE(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!sne(n[p],l))throw new Lw(e,t+1,`${oE(`comparable`)} of the same kind as ${sE(n[p])}`,sE(l),r,{source:i})}}}function tne(e,t){switch(t.kind){case`exact`:return{minimum:e.length,maximum:e.length};case`variadic`:return{minimum:e.length-1,maximum:1/0};case`alternating`:return{minimum:t.minimum,maximum:1/0}}}function nne(e,t){let n=e.length;switch(t.kind){case`exact`:return t=>e[t];case`variadic`:return t=>e[Math.min(t,n-1)];case`alternating`:return t=>e[t%n]}}function rne(e,t,n,r){switch(e){case`truthy`:case`reflective`:case`value`:return!0;case`string`:return typeof t==`string`;case`int`:return typeof t==`number`&&Number.isSafeInteger(t)||typeof t==`bigint`&&Number.isSafeInteger(Number(t));case`truncating-int`:return typeof t==`number`&&Number.isFinite(t)||typeof t==`bigint`&&Number.isSafeInteger(Number(t));case`float`:return typeof t==`number`||typeof t==`bigint`&&Number.isFinite(Number(t));case`bool`:return typeof t==`boolean`;case`ordered`:return typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`;case`T`:return r(t);case`list`:return Array.isArray(t);case`dict`:return KT(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||KT(t);case`comparable`:return t==null||typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`||Array.isArray(t)||t instanceof Map||t instanceof Set||KT(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||KT(t);case`index-key`:return typeof t==`string`||typeof t==`number`||typeof t==`bigint`;case`sliceable`:return typeof t==`string`||Array.isArray(t);case`stringifiable`:if(typeof t==`string`)return!0;try{return n(t),!0}catch{return!1}case`liftable`:return typeof t==`string`||r(t);case`serializable`:return ane(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function ine(e){return e}function iE(e){if(typeof e==`string`)return e;if(e==null)return`<nil>`;if(typeof e==`number`||typeof e==`bigint`||typeof e==`boolean`)return String(e);throw new Lw(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,sE(e),{line:0,column:0,offset:0})}function ane(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function one(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function sne(e,t){let n=aE(e),r=aE(t);return n===`nil`||r===`nil`?!0:n===r}function aE(e){return e==null?`nil`:typeof e==`string`?`string`:typeof e==`number`||typeof e==`bigint`?`number`:typeof e==`boolean`?`boolean`:Array.isArray(e)?`array`:e instanceof Map?`map`:e instanceof Set?`set`:`object`}function oE(e){switch(e){case`int`:return`integer (safe-integer number or bigint)`;case`truncating-int`:return`integer (finite number, truncated toward zero, or safe-integer bigint)`;case`float`:return`float (number, including NaN/Infinity, or finite-convertible bigint)`;case`T`:return`T (consumer-defined fragment)`;case`ordered`:return`orderable primitive`;case`list`:return`list`;case`dict`:return`dict (plain object)`;case`sized`:return`sized value (string, list, map, set, or dict)`;case`comparable`:return`comparable value (orderable primitive, nil, list, dict, Map, or Set)`;case`stringifiable`:return`stringifiable value (string or convertible via the engine's toString)`;case`liftable`:return`liftable value (T or string, the latter lifted via the engine's fromString)`;case`callable`:return`callable (function value)`;case`collection`:return`collection (string, array, Map, or dict)`;case`index-key`:return`index key (number, bigint, or string)`;case`sliceable`:return`sliceable value (string or array)`;case`serializable`:return`JSON-serializable value`;case`truthy`:case`reflective`:case`value`:case`string`:case`bool`:return e;default:throw Error(`invalid ArgType: ${String(e)}`)}}function cne(e){return e instanceof Error?e.message:String(e)}function sE(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function lne(e){return e==null?[]:Array.isArray(e)?e.map((e,t)=>[t,e]):typeof e==`string`?[...e].map((e,t)=>[t,e]):e instanceof Map?cE([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?cE(Object.entries(e)):[]}function cE(e){return[...e].sort((e,t)=>une(e[0],t[0]))}function une(e,t){if((typeof e==`number`||typeof e==`bigint`)&&(typeof t==`number`||typeof t==`bigint`)){let n=typeof e==`bigint`?Number(e):e,r=typeof t==`bigint`?Number(t):t;return n===r?0:n<r?-1:1}let n=String(e),r=String(t);return n===r?0:n<r?-1:1}function lE(e){if(e.intValue!==void 0){let t=e.intValue;return t>=BigInt(-(2**53-1))&&t<=BigInt(2**53-1)?Number(t):t}if(e.floatValue!==void 0)return e.floatValue;if(e.complexValue!==void 0)return e.complexValue;throw Error(`internal: NumberNode has none of intValue/floatValue/complexValue — parser invariant violated`)}function dne(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function fne(e){if(typeof e==`number`)return e;if(typeof e==`bigint`)return Number(e);if(typeof e==`string`){let t=Number.parseFloat(e);return Number.isNaN(t)?0:t}return typeof e==`boolean`?+!!e:0}function uE(e){if(e===``)return null;let t=1,n=e;return n[0]===`+`?n=n.slice(1):n[0]===`-`&&(t=-1,n=n.slice(1)),n===``?null:/^0x[0-9a-fA-F]+$/i.test(n)?{sign:t,digits:n.slice(2),base:16}:/^0b[01]+$/i.test(n)?{sign:t,digits:n.slice(2),base:2}:/^0o[0-7]+$/i.test(n)?{sign:t,digits:n.slice(2),base:8}:n===`0`?{sign:t,digits:`0`,base:10}:n[0]===`0`?/^0[0-7]+$/.test(n)?{sign:t,digits:n.slice(1),base:8}:null:/^[0-9]+$/.test(n)?{sign:t,digits:n,base:10}:null}function pne(e){if(typeof e==`number`){let t=Math.trunc(e);return Number.isSafeInteger(t)?t:0}if(typeof e==`bigint`){let t=Number(e);return Number.isSafeInteger(t)?t:0}if(typeof e==`string`){let t=uE(e);if(t===null)return 0;let n=t.sign*Number.parseInt(t.digits,t.base);return Number.isSafeInteger(n)?n:0}return typeof e==`boolean`?+!!e:0}function mne(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=uE(e);if(t===null)return 0n;let n=t.base===16?`0x`:t.base===2?`0b`:t.base===8?`0o`:``,r=BigInt(n+t.digits);return t.sign===-1?-r:r}return typeof e==`boolean`&&e?1n:0n}function hne(e){if(!/^[+-]?[0-7]+$/.test(e))return 0;let t=e[0]===`-`?-1:1,n=e[0]===`+`||e[0]===`-`?e.slice(1):e,r=t*Number.parseInt(n,8);return Number.isSafeInteger(r)?r:0}function dE(e){return JSON.stringify(e)??`null`}function fE(){return{atoi:{fn:e=>dne(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>pne(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>mne(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>fne(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>hne(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>dE(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const pE={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function mE(e){if(e===`0`)return 0;let t=!1,n=e;if(n.startsWith(`-`)?(t=!0,n=n.slice(1)):n.startsWith(`+`)&&(n=n.slice(1)),!n)return NaN;let r=0,i=/^(\d+(?:\.\d+)?)(ns|µs|us|ms|[smh])/;for(;n.length>0;){let e=i.exec(n);if(!e)return NaN;let t=parseFloat(e[1]??`0`),a=e[2];r+=t*pE[a],n=n.slice(e[0].length)}return t?-r:r}function hE(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<pE.us?`${Math.floor(n)}ns`:n<pE.ms?gE(n,pE.us,3,`µs`):n<pE.s?gE(n,pE.ms,6,`ms`):_E(n),t?`-${r}`:r}function gE(e,t,n,r){let i=Math.floor(e/t),a=Math.round(e%t);return a===0?`${i}${r}`:`${i}.${String(a).padStart(n,`0`).replace(/0+$/,``)}${r}`}function _E(e){let t=Math.floor(e/pE.h);e-=t*pE.h;let n=Math.floor(e/pE.m);e-=n*pE.m;let r=Math.floor(e/pE.s),i=e-r*pE.s,a=i===0?`${r}s`:`${r}.${String(Math.round(i)).padStart(9,`0`).replace(/0+$/,``)}s`;return t>0?`${t}h${n}m${a}`:n>0?`${n}m${a}`:a}function vE(e){return e*pE.s}function yE(e){if(e instanceof Date)return e;if(typeof e==`bigint`)return new Date(Number(e)*1e3);if(typeof e==`number`)return new Date(e*1e3);if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t;throw Error(`sprig: cannot parse date value ${JSON.stringify(e)}`)}throw Error(`sprig: unsupported date type: ${typeof e}`)}function bE(e,t){let n=t().getTime()-yE(e).getTime();return hE(Math.round(n/1e3)*1e9)}const xE=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],SE=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],CE=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],wE=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function TE(e){return e<10?`0${e}`:String(e)}function EE(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function DE(e){return e<10?` ${e}`:String(e)}function OE(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${TE(Math.floor(n/60))}${TE(n%60)}`}function kE(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${TE(Math.floor(n/60))}:${TE(n%60)}`}function AE(e){return`${e>=0?`+`:`-`}${TE(Math.floor(Math.abs(e)/60))}`}function jE(e){return e===0?`Z`:OE(e)}function ME(e){return e===0?`Z`:kE(e)}function NE(e){return e===0?`Z`:AE(e)}function PE(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const FE=[[`.000000000`,e=>`.${PE(e.ms,9,!1)}`],[`.999999999`,e=>{let t=PE(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${PE(e.ms,6,!1)}`],[`.999999`,e=>{let t=PE(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${EE(e.ms)}`],[`.999`,e=>{let t=EE(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>xE[e.month-1]??`January`],[`Monday`,e=>CE[e.weekday]??`Monday`],[`Z07:00`,e=>ME(e.offsetMinutes)],[`-07:00`,e=>kE(e.offsetMinutes)],[`Z0700`,e=>jE(e.offsetMinutes)],[`-0700`,e=>OE(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>SE[e.month-1]??`Jan`],[`Mon`,e=>wE[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>AE(e.offsetMinutes)],[`Z07`,e=>NE(e.offsetMinutes)],[`15`,e=>TE(e.hour)],[`01`,e=>TE(e.month)],[`02`,e=>TE(e.day)],[`_2`,e=>DE(e.day)],[`03`,e=>TE(e.hour12)],[`04`,e=>TE(e.minute)],[`05`,e=>TE(e.second)],[`06`,e=>TE(e.year%100)],[`PM`,e=>e.hour>=12?`PM`:`AM`],[`pm`,e=>e.hour>=12?`pm`:`am`],[`1`,e=>String(e.month)],[`2`,e=>String(e.day)],[`3`,e=>String(e.hour12)],[`4`,e=>String(e.minute)],[`5`,e=>String(e.second)]];function IE(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of FE)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const LE={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function RE(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const zE=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function BE(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=RE(new Intl.DateTimeFormat(`en-US`,{...LE,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=RE(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=VE(RE(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=zE.indexOf(r.get(`weekday`)??`Sunday`);return{year:parseInt(r.get(`year`)??`2000`,10),month:parseInt(r.get(`month`)??`1`,10),day:parseInt(r.get(`day`)??`1`,10),weekday:s===-1?0:s,hour:i,hour12:i%12||12,minute:parseInt(r.get(`minute`)??`0`,10),second:parseInt(r.get(`second`)??`0`,10),ms:e.getUTCMilliseconds(),tzAbbr:a,offsetMinutes:o}}function VE(e){if(e===`GMT`||e===`UTC`)return 0;let t=e.match(/^GMT([+-])(\d{1,2})(?::(\d{2}))?$/);if(!t)return 0;let n=t[1]===`+`?1:-1,r=parseInt(t[2]??`0`,10),i=parseInt(t[3]??`0`,10);return n*(r*60+i)}function HE(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function UE(e,t){return IE(e,BE(yE(t),HE()))}function WE(e,t,n){return IE(e,BE(yE(t),n))}function GE(e,t){let n=yE(t),r=mE(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function KE(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:hE(vE(t))}return typeof e==`bigint`?hE(vE(Number(e))):typeof e==`number`?hE(vE(e)):`0s`}const qE=36e11*24*365,JE=36e11*24*30,YE=36e11*24,XE=36e11,ZE=6e10,QE=1e9;function $E(e){let t=mE(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>qE?`${Math.floor(n/qE)}y`:n>JE?`${Math.floor(n/JE)}mo`:n>YE?`${Math.floor(n/YE)}d`:n>XE?`${Math.floor(n/XE)}h`:n>ZE?`${Math.floor(n/ZE)}m`:n>QE?`${Math.floor(n/QE)}s`:`0s`}function eD(e){let t=BE(yE(e),HE());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function tD(e,t){let n=BE(yE(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function nD(e){return e()}const rD=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],iD=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function aD(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function oD(e,t,n){return[e.slice(t,t+n),t+n]}function sD(e,t,n,r){let i=t;for(;i<e.length&&i-t<r&&e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57;)i++;if(i-t<n)throw Error(`sprig toDate: expected ${n}-${r} digits at pos ${t}`);return[parseInt(e.slice(t,i),10),i]}function cD(e,t){for(let[n,r]of rD.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function lD(e,t){for(let[n,r]of iD.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function uD(e,t){for(let n of[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`])if(e.startsWith(n,t))return t+n.length;throw Error(`sprig toDate: expected weekday name at pos ${t}`)}function dD(e,t){for(let n of[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`])if(e.startsWith(n,t))return t+n.length;throw Error(`sprig toDate: expected short weekday name at pos ${t}`)}function fD(e,t){if(e[t]===` `){let[n,r]=sD(e,t+1,1,1);return[n,r]}return sD(e,t,1,2)}function pD(e,t,n){let r=e[t]===`+`?1:e[t]===`-`?-1:0;if(r===0)throw Error(`sprig toDate: expected +/- at pos ${t}`);let i=t+1,[a,o]=sD(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=sD(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=sD(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function mD(e,t,n,r){if(e[t]===`Z`)return[0,t+1];if(r){let n=e[t]===`+`?1:e[t]===`-`?-1:0;if(n===0)throw Error(`sprig toDate: expected Z or +/- at pos ${t}`);let[r,i]=sD(e,t+1,2,2);return[n*r*60,i]}return pD(e,t,n)}function hD(e,t){let n=t;for(;n<e.length&&e.charCodeAt(n)>=65&&e.charCodeAt(n)<=90;)n++;if(n===t)throw Error(`sprig toDate: expected timezone abbreviation at pos ${t}`);return n}function gD(e,t,n){let[r,i]=oD(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function _D(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=cD(t,n);return i.month=e,[r,i]}case`Monday`:return[uD(t,n),i];case`Jan`:{let[e,r]=lD(t,n);return i.month=e,[r,i]}case`Mon`:return[dD(t,n),i];case`2006`:{let[e,r]=sD(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=sD(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=sD(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=sD(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=fD(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=sD(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=sD(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=sD(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=sD(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=sD(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=sD(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=sD(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=sD(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=sD(t,n,1,2);return i.second=e,[r,i]}case`PM`:case`pm`:{let e=t.slice(n,n+2).toLowerCase();if(e!==`am`&&e!==`pm`)throw Error(`sprig toDate: expected AM/PM at pos ${n}, got ${JSON.stringify(t.slice(n,n+2))}`);return i.isPM=e===`pm`,i.hour12=!0,[n+2,i]}case`MST`:return[hD(t,n),i];case`-0700`:{let[e,r]=pD(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=pD(t,n,!0);return i.offsetMinutes=e,[r,i]}case`-07`:{let e=t[n]===`+`?1:t[n]===`-`?-1:0;if(e===0)throw Error(`sprig toDate: expected +/- at pos ${n}`);let[r,a]=sD(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=mD(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=mD(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=mD(t,n,!1,!0);return i.offsetMinutes=e,[r,i]}case`.000000000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=gD(t,n+1,9);return i.ms=e,[r,i]}case`.999999999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(9,`0`);return i.ms=Math.round(parseInt(a,10)/1e6),[r,i]}case`.000000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=gD(t,n+1,6);return i.ms=e,[r,i]}case`.999999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(9,`0`);return i.ms=Math.round(parseInt(a,10)/1e6),[r,i]}case`.000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=gD(t,n+1,3);return i.ms=e,[r,i]}case`.999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(3,`0`);return i.ms=parseInt(a,10),[r,i]}}throw Error(`sprig toDate: unhandled token ${e}`)}const vD=`.000000000,.999999999,.000000,.999999,.000,.999,January,Monday,Z07:00,-07:00,Z0700,-0700,2006,Jan,Mon,MST,-07,Z07,15,01,02,_2,03,04,05,06,PM,pm,1,2,3,4,5`.split(`,`);function yD(e,t){let n=0,r=0,i=aD();for(;n<e.length;){let a=!1;for(let o of vD)if(e.startsWith(o,n)){let[e,s]=_D(o,t,r,i);r=e,i=s,n+=o.length,a=!0;break}if(!a){let i=e.charAt(n);if(t[r]!==i)throw Error(`sprig toDate: expected ${JSON.stringify(i)} at pos ${r}, got ${JSON.stringify(t[r])}`);n++,r++}}if(r!==t.length)throw Error(`sprig toDate: extra characters at pos ${r}: ${JSON.stringify(t.slice(r))}`);if(i.hour12){let e=i.hour%12;i.hour=i.isPM?e+12:e}let a=Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second,i.ms)-i.offsetMinutes*60*1e3;return new Date(a)}function bD(e,t){return yD(e,t)}function xD(e){return String(Math.floor(yE(e).getTime()/1e3))}function SD(e=()=>new Date){return{now:{fn:()=>nD(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>UE(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>WE(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>GE(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>eD(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>tD(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>KE(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>$E(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>bD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>bE(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>xD(e),argTypes:[`value`],arity:{kind:`exact`}}}}function CD(e){return e==null||e===!1?!0:typeof e==`number`?e===0||Number.isNaN(e):typeof e==`bigint`?e===0n:typeof e==`string`||Array.isArray(e)?e.length===0:e instanceof Map||e instanceof Set?e.size===0:typeof e==`object`?Object.keys(e).length===0:!1}function wD(...e){for(let t of e)if(!CD(t))return t}function TD(e,t){return CD(t)?e:t}function ED(e){return JSON.parse(e)}function DD(e,t,n){return AT(n)?e:t}function OD(e){return JSON.stringify(e)??`null`}function kD(e){return JSON.stringify(e,null,2)??`null`}function AD(){return{default:{fn:(e,t)=>TD(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>CD(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>wD(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>DD(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>ED(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>OD(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>kD(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function jD(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function MD(e){if(e.kind!==`call`||e.name!==`dict`||e.args.length%2!=0)return null;let t=[];for(let[n,r]of e.args.entries()){if(r.kind!==`literal`||n%2==0&&typeof r.value!=`string`)return null;t.push(r.value)}return jD(...t)}function ND(e,t){return e[t]}function PD(e,t){return t in e}function FD(e){return Object.keys(e)}function ID(e,...t){let n={...e};for(let e of t)for(let[t,r]of Object.entries(e))t in n||(n[t]=r);return n}function LD(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function RD(e,...t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e))n.has(t)||(r[t]=i);return r}function zD(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function BD(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function VD(e,t,n){return e[t]=n,e}function HD(e,t){return delete e[t],e}function UD(e){return Object.values(e)}function WD(){return{dict:{fn:(...e)=>jD(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>ND(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>VD(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>HD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>FD(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>UD(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>BD(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>zD(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>RD(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>PD(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>ID(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>LD(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function GD(e){throw new Bw(e)}function KD(){return{fail:{fn:e=>GD(e),argTypes:[`string`],arity:{kind:`exact`}}}}new TextEncoder,new Map(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`).map((e,t)=>[e,t])),new TextDecoder,new TextEncoder,new TextDecoder,new TextEncoder;function qD(...e){for(let t of e)if(CD(t))return!1;return!0}function JD(...e){for(let t of e)if(!CD(t))return!0;return!1}function YD(e,t){return[...e,t]}function XD(e,t){let n=Math.max(1,e),r=[];for(let e=0;e<t.length;e+=n)r.push(t.slice(e,e+n));return r}function ZD(e){return e.filter(e=>!CD(e))}function QD(...e){let t=[];for(let n of e)t.push(...n);return t}const $D={line:0,column:0,offset:0};function eO(e,t,n,r){return new Lw(e,t,n,r,$D)}function tO(...e){if(e.length<3)throw eO(`dig`,0,`at least 3 arguments (...keys, default, dict)`,`${e.length} argument${e.length===1?``:`s`}`);let t=e[e.length-1],n=e[e.length-2],r=e.slice(0,-2);if(!rO(t))throw eO(`dig`,e.length-1,`dict`,iO(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw eO(`dig`,e,`string`,iO(r[e]));return nO(t,n,r,e.length)}function nO(e,t,n,r){let i=n[0];if(!Object.hasOwn(e,i))return t;let a=e[i];if(n.length===1)return a;if(!rO(a))throw eO(`dig`,r-1,`dict at intermediate key`,iO(a));return nO(a,t,n.slice(1),r)}function rO(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function iO(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function aO(e){return e[0]}function oO(e,t){return t.some(t=>ET(t,e))}function sO(e){return e.slice(0,-1)}function cO(e){return e[e.length-1]}function lO(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function uO(...e){return e}function dO(e,t){return[t,...e]}function fO(e){return e.slice(1)}function pO(e){return[...e].reverse()}function mO(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function hO(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function gO(e){let t=[];for(let n of e)t.some(e=>ET(e,n))||t.push(n);return t}function _O(e,...t){return e.filter(e=>!t.some(t=>ET(t,e)))}function vO(){return{list:{fn:(...e)=>uO(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>aO(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>cO(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>fO(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>sO(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>lO(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>pO(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>gO(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>_O(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>oO(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>ZD(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>mO(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>QD(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>XD(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>dO(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>YD(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>hO(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>YD(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>uO(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>tO(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>qD(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>JD(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function yO(...e){return e.reduce((e,t)=>e+t,0)}function bO(e){return e+1}function xO(e){return e+1}function SO(...e){return e.reduce((e,t)=>e+t,0)}function CO(e){return Math.ceil(e)}function wO(e,t){return Math.trunc(e/t)}function TO(e,...t){return t.reduce((e,t)=>e/t,e)}function EO(e){return Math.floor(e)}function DO(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function OO(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function kO(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function AO(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function jO(e,t){return e%t}function MO(...e){return e.reduce((e,t)=>e*t,1)}function NO(...e){return e.reduce((e,t)=>e*t,1)}function PO(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function FO(e,t,n){let r=[];if(t<e){if(n>=0)return r;for(let i=e;i>t;i+=n)r.push(i);return r}if(n<=0)return r;for(let i=e;i<t;i+=n)r.push(i);return r}function IO(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),FO(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return FO(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:FO(n,i+t,r).join(` `)}default:return``}}function LO(e,t){return e-t}function RO(e,...t){return t.reduce((e,t)=>e-t,e)}function zO(e){return FO(0,e,e<0?-1:1)}function BO(){return{add:{fn:(...e)=>yO(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>LO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>MO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>wO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>jO(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>kO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>DO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>EO(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>CO(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>PO(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>SO(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>RO(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>NO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>TO(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>bO(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>xO(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>OO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>AO(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>DO(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>IO(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>zO(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>FO(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function VO(e){return Array.from(e)}function HO(e,t){return e===``?VO(t):t.split(e)}function UO(e,t){let n=VO(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function WO(e,t,n){let r=VO(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const GO={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},KO=/^[-_\s]$/,qO=/^\p{P}$/u,JO=/^\p{L}$/u,YO=/^\p{Lu}$/u,XO=/^\p{N}$/u;function ZO(e){return e!==void 0&&KO.test(e)}function QO(e){return e!==void 0&&JO.test(e)}function $O(e){return e!==void 0&&YO.test(e)}function ek(e){return e!==void 0&&XO.test(e)}function tk(e){return e!==void 0&&qO.test(e)}function nk(e,t){if(t>=e.length)return{word:{wt:GO.Invalid,text:``},next:t};let n=e[t],r=t+1;if(ZO(n)){for(;r<e.length&&ZO(e[r]);)r++;return{word:{wt:GO.Connector,text:e.slice(t,r).join(``)},next:r}}if(tk(n)){for(;r<e.length&&tk(e[r]);)r++;return{word:{wt:GO.Punct,text:e.slice(t,r).join(``)},next:r}}if($O(n)){if(r>=e.length)return{word:{wt:GO.UpperCase,text:n},next:r};if($O(e[r])){let n=r;for(;n<e.length&&$O(e[n]);)n++;return n<e.length&&QO(e[n])?{word:{wt:GO.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:GO.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(QO(e[r])){let n=r+1;for(;n<e.length&&QO(e[n])&&!$O(e[n]);)n++;return{word:{wt:GO.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:GO.UpperCase,text:n},next:r}}if(QO(n)){for(;r<e.length&&QO(e[r])&&!$O(e[r]);)r++;return{word:{wt:GO.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(ek(n)){for(;r<e.length&&ek(e[r]);)r++;return{word:{wt:GO.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!ZO(e[r])&&!QO(e[r])&&!ek(e[r])&&!tk(e[r]);)r++;return{word:{wt:GO.Other,text:e.slice(t,r).join(``)},next:r}}function rk(e,t,n){if(t.wt!==GO.UpperCase&&t.wt!==GO.Connector){e.push(t.text);return}for(let r of t.text)ZO(r)?e.push(n):$O(r)?e.push(r.toLowerCase()):e.push(r)}function ik(e,t){if(e.length===0)return``;let n=VO(e),r=[],{word:i,next:a}=nk(n,0);for(;a<n.length;){i.wt!==GO.Connector&&rk(r,i,t);let e=i,o=i;if({word:i,next:a}=nk(n,a),e.wt===GO.Number){for(;i.wt===GO.Alphabet||i.wt===GO.Number;)rk(r,i,t),{word:i,next:a}=nk(n,a);i.wt!==GO.Invalid&&i.wt!==GO.Punct&&i.wt!==GO.Connector&&r.push(t);continue}if(e.wt===GO.Connector){rk(r,o,t);continue}if(e.wt===GO.Punct)continue;if(i.wt!==GO.Number){i.wt!==GO.Connector&&i.wt!==GO.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=nk(n,a),i.wt!==GO.Alphabet){rk(r,s,t),i.wt!==GO.Connector&&i.wt!==GO.Punct&&r.push(t);continue}for(r.push(t),rk(r,s,t);i.wt===GO.Alphabet||i.wt===GO.Number;)rk(r,i,t),{word:i,next:a}=nk(n,a);i.wt!==GO.Invalid&&i.wt!==GO.Connector&&i.wt!==GO.Punct&&r.push(t)}return rk(r,i,t),r.join(``).toLowerCase()}function ak(e){if(e.length===0)return``;let t=VO(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!ZO(i)){i=i.toUpperCase();break}n.push(i)}if(r>=t.length)return t.length>0&&n.push(i),n.join(``);for(;r<t.length;){let e=i;if(i=t[r],r++,ZO(i)&&ZO(e)){n.push(e);continue}ZO(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function ok(e){return ak(e)}function sk(...e){return e.join(` `)}function ck(e,t){return t.includes(e)}function lk(e,t){return t.startsWith(e)}function uk(e,t){return t.endsWith(e)}function dk(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
67
67
  `).map(e=>n+e).join(`
68
68
  `)}function fk(e){let t=new TextEncoder;return e.split(/\s+/).filter(e=>e.length>0).map(e=>String.fromCharCode(...t.encode(e).slice(0,1))).join(``)}function pk(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw eO(`join`,2,`list of strings/primitives`,`list element of type ${mk(e)}`);n.push(String(e))}return n.join(e)}function mk(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function hk(e){return ik(e,`-`)}function gk(e){return e.toLowerCase()}function _k(e,t){return`\n${dk(e,t)}`}function vk(e){return e.replace(/\s+/g,``)}function yk(e,t,n){return n===1?e:t}function bk(...e){return e.map(e=>`"${e}"`).join(` `)}function xk(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function Sk(e,t){return t.repeat(Math.max(0,e))}function Ck(e,t,n){return HO(e,n).join(t)}function wk(e){return ik(e,`_`)}function Tk(e,t){let n=HO(e,t),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function Ek(e,t){return HO(e,t)}function Dk(e,t,n){let r=Ok(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function Ok(e,t,n){if(n===0)return[];let r=HO(t,e);if(n<0||r.length<=n)return r;let i=r.slice(0,n-1),a=r.slice(n-1).join(t);return[...i,a]}function kk(...e){return e.map(e=>`'${e}'`).join(` `)}function Ak(e,t,n){let r=VO(n),i=t<0||t>r.length?r.length:t,a=Math.min(Math.max(0,e),i);return r.slice(a,i).join(``)}function jk(e){let t=``;for(let n of e)Mk(n)?t+=n.toLowerCase():Nk(n)?t+=n.toUpperCase():t+=n;return t}function Mk(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function Nk(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function Pk(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function Fk(e){return e.trim()}function Ik(e,t){if(e.length===0)return t;let n=new Set(VO(e)),r=VO(t),i=0;for(;i<r.length&&n.has(r[i]);)i+=1;let a=r.length;for(;a>i&&n.has(r[a-1]);)--a;return r.slice(i,a).join(``)}function Lk(e,t){return t.startsWith(e)?t.slice(e.length):t}function Rk(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function zk(e,t){let n=VO(t);if(e<0){let r=-e;return r>=n.length?t:n.slice(n.length-r).join(``)}return e>=n.length?t:n.slice(0,e).join(``)}function Bk(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function Vk(e){return e.toUpperCase()}function Hk(e,t){return Uk(e,`
69
69
  `,t)}function Uk(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
70
- `)){let n=``;for(let i of t.split(/\s+/))i.length!==0&&(n.length===0?n=i:n.length+1+i.length<=e?n+=` ${i}`:(r.push(n),n=i));n.length>0&&r.push(n)}return r.join(t)}function Wk(e,t,n){return Uk(e,t,n)}function Gk(){return{abbrev:{fn:(e,t)=>UO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>WO(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>ok(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>sk(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>ck(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>lk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>uk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>dk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>fk(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>pk(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>hk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>gk(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>_k(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>vk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>yk(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>bk(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>xk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>Sk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>Ck(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>wk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>Tk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>Ek(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>Dk(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>kk(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>Ak(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>jk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>Pk(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>Fk(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>Ik(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>Lk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>Rk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>zk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>Bk(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>Vk(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>Hk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>Wk(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function Kk(e,t){let n=qk(e),r=n.copy();return r.style=Yf(n.style,t),r}function qk(e){if(!(e instanceof q))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function Jk(e){return{fn:(t=>Kk(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function Yk(e){return{fn:((t,n)=>Kk(n,new W({[e]:U.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function Xk(e,t){return new W({[e]:t})}function Zk(){let e={};for(let t of Vf)e[t]=Jk(Xk(t,!0)),e[`not_${t}`]=Jk(Xk(t,!1));for(let[t,n]of Object.entries(Uf))e[t]=Jk(Xk(n,!0));return e}const Qk={fn:((e,t)=>Kk(t,W.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},$k={fn:((e,t)=>Kk(t,new W({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function eA(){return{fg:Yk(`color`),bg:Yk(`bgcolor`),...Zk(),link:$k,style:Qk}}function tA(e,t){let n;try{n=Cu(e.trim())}catch(n){throw n instanceof au?TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`,{cause:n}):n}return nA(n,t,JSON.stringify(e))}function nA(e,t,n){if(e.alpha===0)throw RangeError(`${t} got ${n}, which is fully transparent: it draws no colour of its own, so there is nothing to compute with — use the colour of the surface it sits on, e.g. (color "background")`);return e}function rA(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function iA(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`)}return e}const aA=rA([`string`,`int`],((e,t)=>od(tA(e,`darken`),t).hex)),oA=rA([`string`,`int`],((e,t)=>od(tA(e,`lighten`),-t).hex)),sA={min:0,max:100,note:`0 = from, 100 = toward`},cA=rA([`string`,`string`,`float`],((e,t,n)=>wu(tA(e,`mix`),tA(t,`mix`),iA(n,`mix`,`percentage`,sA)/100).hex)),lA={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},uA=rA([`string`],(e=>ud(tA(e,`contrastOn`)).hex)),dA={depth:H.TRUECOLOR},fA=e=>rA([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return dd(tA(t,`readableOn`),tA(n,`readableOn`),iA(r,`readableOn`,`ratio`,lA),i,void 0,a).hex})),pA={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function mA(){let e={};for(let[t,n]of Object.entries(pA)){let r=t;e[n]=rA([`string`,`float`],((e,t)=>{let i={...Ru,[r]:iA(t,n,`amount`)};return Xu.fromRgba(tA(e,n)).applyKey(i).toRgba().hex}))}return e}function hA(e=()=>dA){return{darken:aA,lighten:oA,mix:cA,contrastOn:uA,readableOn:fA(e),...mA()}}function gA(e,t){if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:nA(ed(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function _A(e){return{color:{fn:(t=>ed(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new Ip(Tf(n),gA(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}const vA=Up.play(0);function yA(e,t,n){if(t.length%2!=0)throw RangeError(`last hold (${String(t[t.length-1])} s) has no ${e} — the arguments are <seconds> <${e}> pairs`);let r=[];for(let e=0;e<t.length;e+=2){let i=t[e];if(!Number.isFinite(i)||i<=0)throw RangeError(`hold ${e/2} must be a positive number of seconds, got ${i}`);r.push({seconds:i,value:n(t[e+1])})}return r}const bA={...j_.loops,typewriter:e=>j_.transitions.typewriter(e).effect,scramble:e=>j_.transitions.scramble(e).effect,backspace:e=>j_.transitions.backspace(e).effect,scrambleOut:e=>j_.transitions.scrambleOut(e).effect};function xA(e){if(!Object.hasOwn(bA,e))throw RangeError(`unknown glyph effect ${JSON.stringify(e)}; expected one of ${Object.keys(bA).map(e=>JSON.stringify(e)).join(`, `)}`);return bA[e]}function SA(e,t={}){let n=t.timeline??(()=>vA),r=(e,t,r)=>[Up.run(n(),t),kf(e,r.time)],i=(t,n)=>{let i=e(),[a,o]=r(t,n,i),s=Tp(a,o,i);return i.onHold?.(Ep(s,o)),s.value},a=(e,t)=>Up.run(Up.play(e),t);return{frames:{fn:((...t)=>{let n=yA(`frame`,t,qk).map(({seconds:e,value:t})=>({seconds:e,text:t})),i=e();return N_(...r(`frames`,new M_(n),i),i)}),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...e)=>{let t=yA(`color`,e,e=>tA(e,`stepped`));return t[i(`stepped`,If(t.map(e=>e.seconds)))].value.hex}),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:2},returnType:`string`},tween:{fn:((e,t,n,r,o)=>i(`tween`,a(n,Fp(r,o,{seconds:e,ease:Tf(t)})))),argTypes:[`float`,`string`,`float`,`float`,`float`],arity:{kind:`exact`},returnType:`float`},loop:{fn:((e,t)=>i(`loop`,a(t,K.continuous(Lf.loop(e))))),argTypes:[`float`,`float`],arity:{kind:`exact`},returnType:`float`},glyphs:{fn:((t,n,i)=>{let o=xA(t),s=qk(i),c=s.plain,l=e();return N_(...r(`glyphs`,a(n,l_(s,o({z:Mh(c,0,0)}),{key:c,asciiOnly:l.asciiOnly===!0})),l),l)}),argTypes:[`string`,`float`,`liftable`],arity:{kind:`exact`},returnType:`T`}}}function CA(e){return{...eA(),...hA(e)}}new W({color:`red`,dim:!0});const wA=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i,TA=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function EA(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(wA);if(n?.groups){let{family:e,newMajor:t,newMinor:r,oldMajor:i,oldMinor:a,oldFamily:o}=n.groups,s=e||o,c=t||i,l=r||a;if(s&&c)return`${s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()} ${l?`${c}.${l}`:c}`}let r=t.match(TA);if(r?.groups){let e=r.groups.family,t=r.groups.major,n=r.groups.minor;return`${e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()} ${n?`${t}.${n}`:t}`}return t||e}function DA(e){let t=e.match(TA);if(!t?.groups)return e;let n=t.groups.family,r=t.groups.major,i=t.groups.minor;return`${n.charAt(0).toUpperCase()}${i?`${r}.${i}`:r}`}function OA(e){let t=e.split(`/`),n=t.length-1;return t.map((e,t)=>{if(t===n)return e;let r=e.match(/^\.*./);return r?r[0]:e}).join(`/`)}function kA(e){return e.toLocaleString()}function AA(e){if(e.length===0)throw Error(`a cascade needs at least one stop, e.g. "0:calm"`);let t=[];for(let[n,r]of e.entries()){let e=r.indexOf(`:`),i=e<0?NaN:Number(r.slice(0,e));if(!Number.isFinite(i))throw Error(`cascade stop ${n} ("${r}") must be "<position>:<result>", e.g. "80:hot" — the position must be a number`);let a=t[n-1];if(a!==void 0&&i<a.at)throw Error(`cascade stops must be in ascending position order; stop ${n} at ${i} follows stop ${n-1} at ${a.at}`);t.push({at:i,text:r.slice(e+1)})}return t}function jA(e,t){if(!Number.isFinite(e))throw Error(`a cascade needs a finite value, got ${e}`);let n=-1;for(;n+1<t.length&&t[n+1].at<=e;)n++;return(n<0?t[0]:t[n]).text}const MA=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],NA=MA.length;function PA(e,t){let n=t===void 0?e:t<=0?[]:e.slice(-t);if(n.length===0)return``;let r=n[0],i=n[0];for(let e of n)e<r&&(r=e),e>i&&(i=e);let a=i-r,o=``;for(let e of n){let t=a===0?0:Math.round((e-r)/a*(NA-1));o+=MA[t]}return o}function FA(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(e===``)continue;let r=Number(e);if(!Number.isFinite(r))throw TypeError(`sparkline: non-numeric series element ${JSON.stringify(n)}`);t.push(r)}return t}function IA(e,t,n){if(n.length!==0)throw Error(`${e}: takes at most ${t.length} optional argument${t.length===1?``:`s`} (${t.join(`, `)}), got ${t.length+n.length}`)}const LA=gy(),RA=[...Ry];function zA(){return{basename:{fn:e=>c(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>l(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>OA(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(gw(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>hw(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>_w(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>LA,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>RA,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(IA(`sparkline`,[`width`],n),PA(FA(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>jA(e,AA(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function BA(e,t,n,r){let i=n*6e4-(t*1e3-r);if(i<3e5||e<=0)return-1;let a=e/i;return Math.max(0,Math.round((100-e)/a/6e4))}const VA=e=>({minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e.now().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},etaMinutes:{fn:(t,n,r)=>BA(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function HA(){return{formatInteger:{fn:e=>kA(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>EA(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>DA(e),argTypes:[`string`],arity:{kind:`exact`}}}}let UA=null;function WA(e,t){if(UA!==null)throw Error(`a draw is already in progress: draws do not nest`);let n={at:e,timeline:t,frame:{time:e,onHold:({nextChange:e})=>{n.soonest=Math.min(n.soonest,e)}},soonest:1/0};return UA=n,{heard:()=>n.soonest,[Symbol.dispose]:()=>{UA=null}}}function GA(e){if((0,X._isComputingDerivation)())throw Error(`the clock was read by a value that keeps its answer (${e}): a template reaching a time variable or a clock function by a name it does not spell (index, get) is not known to read the instant — name it: {{ .clock }}`);if(UA===null)throw Error(`the clock was read outside a draw (${e})`);return UA}const KA={now:()=>ot(GA(`now`).at),frame:()=>GA(`frame`).frame,timeline:()=>GA(`timeline`).timeline};function qA(e,t){let{frames:n,stepped:r}=SA(e,t===void 0?{}:{timeline:t});if(n===void 0||r===void 0)throw Error(`rich-js's animationFuncs no longer registers frames and stepped`);return{frames:n,stepped:r}}const JA=new Set([`now`,`ago`]);function YA(e,t){return Object.fromEntries(Object.entries(SD(e)).filter(([e])=>JA.has(e)===t))}const XA=YA(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),ZA=[e=>YA(e.now,!0),e=>qA(e.frame,e.timeline),e=>Object.fromEntries(Object.entries(qA(e.frame)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),VA];function QA(e){return Object.assign({},...e.map(e=>e(KA)))}const $A=new Set(Object.keys(QA(ZA)));function ej(e){return new Set([...$A,...Object.keys(QA(e))])}function tj(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return iE({fromString:e=>new q(e),toString:e=>e.plain,isT:e=>e instanceof q,missingKey:`error`,funcs:{...AD(),...Gk(),...vO(),...BO(),...fE(),...KD(),...WD(),...XA,...CA(r),readableOn:fA(r),...QA([...ZA,...e.clockFuncs??[]]),...zA(),...HA(),...n??{}}})}function nj(e){return rj(e,new Set(e.names()),``)}function rj(e,t,n){return new Proxy(Object.create(null),{has(r,i){if(typeof i!=`string`)return!1;let a=n?`${n}.${i}`:i;if(t.has(a))return!aj(e,a);let o=`${a}.`;for(let e of t)if(e.startsWith(o))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a)){if(e.getKind(a)!==`document`)return e.read(a);let t=e.readDocument(a);return t.kind===`absent`?void 0:oj(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return rj(e,t,a)}})}function ij(e,t){return new Proxy(e,{has:(e,t)=>t===`settings`||Reflect.has(e,t),get:(e,n)=>n===`settings`?t:Reflect.get(e,n)})}function aj(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function oj(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new vw(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}var sj=class{held=new Map;declaring=null;closed=!1;take(e,t){if(this.closed)throw Error(`hold taken after close: ${e}`);this.declaring?.taken.add(e),!this.held.has(e)&&(this.held.set(e,t()),this.declaring!==null&&this.declaring.acquired++)}declare(e){if(this.declaring!==null)throw Error(`declaration within one`);let t={taken:new Set,acquired:0};this.declaring=t;let n;try{n=e()}finally{this.declaring=null}let r=0;for(let[e,n]of this.held)t.taken.has(e)||(this.held.delete(e),n(),r++);return{result:n,acquired:t.acquired,released:r}}close(){this.closed=!0;let e=this.held.size;for(let e of this.held.values())e();return this.held.clear(),e}get size(){return this.held.size}};function cj(e,t){let{dir:n,rest:r}=Gn(e,s.dirname(t));return{dir:n,name:r[0]??s.basename(t),leaf:r.length===0}}const lj=(e,t)=>Pe(t);function uj(e,t){let n=[],r=!0,i=new Map;for(let a of t.named){let{hops:t,stopped:o}=br(e,a);o!==null&&n.push({path:a,reason:o.message});for(let n of t){let{dir:t,name:a,leaf:o}=cj(e,n);r&&=o;let s=i.has(t)?i.get(t):new Set;s?.add(a),i.set(t,s)}}for(let n of t.whole.map(t=>Wn(e,t)))n!==null&&i.set(n,null);let a={dirs:[...i.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})},o=new Map(a.dirs.map(t=>{let n=Lc(e,t.path);return[t.path,zc(n)?Rc(n):null]}));return{key:JSON.stringify([a,[...o]]),targets:a,unbound:[...o.values()].includes(null),bound:o,reached:r,unresolved:n}}function dj(e,t,n){let r=[...t.derived.unresolved.map(e=>`cannot follow a link chain — ${e.reason}`),...t.held.handle.deaf.map(fj),...n===null?[]:[n]];return r.length===0?null:`${e}: ${r.join(`; `)}`}const fj=e=>e.kind===`refused`?`cannot watch ${e.path} — ${e.reason}`:`watching ${e.path} failed — ${e.reason}`;function pj(e,t){if(t.kind===`failed`)return t;if(e.kind!==`changed`)return e;if(t.kind===`unknown`)return t;for(let n of t.paths)e.paths.add(n);return e}const mj=(e,t)=>t===null?{kind:`unknown`}:{kind:`changed`,paths:new Set([s.join(e,t)])},hj=e=>({kind:`failed`,reason:`${e.path}: ${e.reason}`}),gj=(e,t)=>e.kind===`listening`&&e.handle===t,_j=(e,t)=>e?.kind===`deaf`&&e.deafness.kind===t.kind&&e.deafness.reason===t.reason,vj=(e,t)=>`${t?`names`:e.recursive===!0?`tree`:`dir`}:${e.path}`;function yj(e,t,n){try{let r=e.lstatSync(s.join(t,n)),i=r.kind===`directory`?``:`${r.size}:${r.mtimeMs}`;return`${r.kind}:${r.dev}:${r.ino}:${r.mode}:${i}`}catch(e){return`error:${e.code}`}}const bj=e=>new Set([...e.listeners].flatMap(({filter:e})=>[...e??[]]));var xj=class{slots=new Map;dirs=new Map;counters;logger;clock;filesystem;sweep=null;closed=!1;constructor(e){this.clock=e.clock,this.filesystem=e.filesystem,this.counters=e.counters,this.logger=e.logger??lj}get namesPolled(){return this.filesystem.watchReach===`tree`}acquire(e,t,n){if(this.closed)return{release:()=>{},ridesStream:!1,deaf:t.dirs.map(e=>({kind:`refused`,path:e.path,reason:`the watcher registry is closed`}))};let r=this.slots.get(e);for(let{dir:e}of r?.listeners??[])this.judged(e,`acquire`);let i=r??this.opened(e,t),a={onInvalidate:n};return i.holders.add(a),this.makeHandle(i,a)}follow(e,t,n){if(e!==null&&(e.key===t.key||t.unbound))return{watch:e,move:`kept`};let r={key:t.key,handle:this.acquire(t.key,t.targets,n)};return e?.handle.release(),{watch:r,move:`rebound`}}opened(e,t){let n={key:e,listeners:[],holders:new Set,debounce:null};for(let e of t.dirs){let t=this.dirFor(e),r={slot:n,dir:t,filter:e.filenames?new Set(e.filenames):null};t.listeners.add(r),n.listeners.push(r),this.baseline(t)}return this.slots.set(e,n),this.counters&&(n.listeners.every(e=>e.dir.state.kind!==`deaf`)?this.counters.watchersOpened++:this.counters.watchRefusals++),n}dirFor(e){let t=this.namesPolled&&e.filenames!==void 0,n=vj(e,t),r=this.dirs.get(n);if(r!==void 0)return this.judged(r,`acquire`),r;let i={path:e.path,recursive:e.recursive===!0,polled:t},a={id:n,...i,listeners:new Set,state:this.open(i,()=>a,`acquire`,null)};return this.dirs.set(n,a),a}judged(e,t){if(e.state.kind===`deaf`){this.reopen(e,t);return}if(e.state.kind===`polling`)return;let n=Lc(this.filesystem,e.path);zc(n)&&Rc(n)!==e.state.bound&&this.reopen(e,`another folder is at its path`)}judge(){for(let e of this.dirs.values())this.judged(e,`period`)}reopen(e,t){let n=e.state;n.kind===`listening`&&this.closeHandle(e.path,n.handle,t),e.state=this.open(e,()=>e,t,n),this.baseline(e),e.state.kind===`deaf`?_j(n,e.state.deafness)||this.tell(e,hj(e.state.deafness)):this.tell(e,{kind:`unknown`})}open(e,t,n,r){let i=e.path,a=Rc(Lc(this.filesystem,i));try{if(this.filesystem.opendirSync(i),e.polled)return this.logger(`info`,`dir names polled path=${z(i)} cause=${z(n)}`),this.armSweep(),{kind:`polling`,bound:a,seen:new Map};let r=this.filesystem.watch(i,{recursive:e.recursive},(e,n)=>this.heard(t(),r,n));return r.onError(e=>{this.logger(`warn`,`watcher error ${i}: ${e.message}`),this.counters&&this.counters.watchErrors++;let n=t();if(!gj(n.state,r))return;this.closeHandle(i,r,`error`);let a={kind:`failed`,path:i,reason:e.message};n.state={kind:`deaf`,deafness:a},this.tell(n,hj(a))}),this.counters&&this.counters.dirWatchesOpened++,this.logger(`info`,`dir watch opened path=${z(i)} cause=${z(n)}`),{kind:`listening`,handle:r,bound:a}}catch(e){let t={kind:`refused`,path:i,reason:e.message};return _j(r,t)||this.logger(`warn`,`watch failed ${i}: ${t.reason}`),{kind:`deaf`,deafness:t}}}heard(e,t,n){let{state:r}=e;if(!gj(r,t))return;let i=n===s.basename(e.path)&&Rc(Lc(this.filesystem,e.path))!==r.bound;for(let{slot:t,filter:r}of e.listeners)(r===null||n===null||r.has(n)||i)&&this.fire(t,mj(e.path,n));i&&this.judged(e,`moved`)}tell(e,t){for(let{slot:n}of e.listeners)this.fire(n,t)}fire(e,t){if(e.debounce!==null){e.debounce.window=pj(e.debounce.window,t);return}let n={window:t,cancel:this.clock.after(50,()=>{e.debounce=null;for(let t of e.holders)try{t.onInvalidate(n.window)}catch(t){this.logger(`warn`,`watcher invalidate threw key=${z(e.key)}: ${t.message}`)}},{unref:!0})};e.debounce=n}makeHandle(e,t){return{ridesStream:e.listeners.some(({dir:e})=>!e.polled),get deaf(){return e.listeners.flatMap(({dir:e})=>e.state.kind===`deaf`?[e.state.deafness]:[])},release:()=>{!e.holders.delete(t)||e.holders.size>0||this.slots.get(e.key)===e&&(this.closeSlot(e,`last release`),this.slots.delete(e.key))}}}closeHandle(e,t,n){try{t.close()}catch{}this.counters&&this.counters.dirWatchesClosed++,this.logger(`info`,`dir watch closed path=${z(e)} cause=${z(n)}`)}closeSlot(e,t){e.debounce!==null&&(e.debounce.cancel(),e.debounce=null);for(let n of e.listeners){let{dir:e}=n;if(e.listeners.delete(n),e.state.kind===`polling`){let t=bj(e);for(let n of e.state.seen.keys())t.has(n)||e.state.seen.delete(n)}e.listeners.size>0||(e.state.kind===`listening`&&this.closeHandle(e.path,e.state.handle,t),e.state.kind===`polling`&&this.logger(`info`,`dir names unpolled path=${z(e.path)} cause=${z(t)}`),this.dirs.delete(e.id))}this.sweep!==null&&!this.polling()&&(this.sweep(),this.sweep=null),this.counters&&this.counters.watchersClosed++}polling(){return[...this.dirs.values()].some(e=>e.state.kind===`polling`)}baseline(e){let{state:t}=e;if(t.kind===`polling`)for(let n of bj(e))t.seen.has(n)||t.seen.set(n,yj(this.filesystem,e.path,n))}armSweep(){this.sweep!==null||this.closed||(this.sweep=this.clock.after(1e3,()=>{this.sweep=null,this.armSweep(),this.pollNames()},{unref:!0}))}pollNames(){for(let e of this.dirs.values()){let{state:t}=e;if(t.kind!==`polling`)continue;let n=Rc(Lc(this.filesystem,e.path)),r=bj(e);if(n!==t.bound){t.bound=n;for(let n of r)t.seen.set(n,yj(this.filesystem,e.path,n));this.tell(e,{kind:`unknown`});continue}for(let n of r){let r=yj(this.filesystem,e.path,n);if(t.seen.get(n)!==r){t.seen.set(n,r);for(let{slot:t,filter:r}of e.listeners)r?.has(n)&&this.fire(t,mj(e.path,n))}}}}size(){return this.slots.size}dirWatches(){return[...this.dirs.values()].filter(e=>e.state.kind===`listening`).length}polledDirs(){return[...this.dirs.values()].filter(e=>e.state.kind===`polling`).length}watchedDirs(){return[...this.dirs.values()].map(e=>e.path)}closeAll(){this.closed=!0,this.sweep?.(),this.sweep=null;for(let e of this.slots.values())this.closeSlot(e,`close`);this.slots.clear()}};function Sj(e,t){return t.kind===`failed`?e.failedMs:e.okMs}function Cj(e,t,n){return t===0?e.okMs:Math.min(e.failedMs*2**(t-1),n)}var wj=class{stop=null;state=`released`;last=null;constructor(e,t){this.tick=e,this.clock=t}landed(e,t=this.clock.monotonic()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.clock.monotonic());this.stop=this.clock.after(e,()=>{this.stop=null,this.tick()},{unref:!0})}cancel(){this.stop?.(),this.stop=null}};function Tj(){return X.observable.box(Ej(`unread`),{deep:!1})}function Ej(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function Dj(e,t){let n=e.reading.get();n.kind!==`pending`&&(0,X.compareStructural)(n,t)||((0,X.runInAction)(()=>e.reading.set(t)),n.kind===`pending`&&n.land())}function Oj(e,t){let n=e.reading.get();n.kind===`pending`?n.why!==t&&t===`unread`&&(0,X.runInAction)(()=>e.reading.set({...n,why:t})):(0,X.runInAction)(()=>e.reading.set(Ej(t)))}function kj(e,t){e.reading.get().kind===`pending`&&Dj(e,t)}function Aj(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function jj(e){return e.reading.get()}async function Mj(e){for(;;){let t=e();if(!Aj(t))return t;await t.landed}}function Nj(e,t,n,r){let i=new AbortController,a=()=>i.abort(),o=t>0?r(t,a):Pj(a);return new Promise((t,r)=>{i.signal.addEventListener(`abort`,()=>t(`deadline`)),e(i.signal).then(()=>t(`answered`),e=>i.signal.aborted?n(e):r(e))}).finally(()=>{o(),i.abort()})}function Pj(e){return Promise.resolve().then(()=>process.nextTick(e)),()=>{}}function Fj(e){return{current:()=>e}}const Ij=()=>()=>{};var Lj=class{entries=new Map;refreshes;closed=!1;constructor(e){this.spec=e,this.refreshes=e.ledger.declare({name:e.name,scope:e.scope,refresh:[`first`,`period`,`change`,`supersede`]})}declare(e,t){if(this.closed)return Fj(L(`${this.spec.name} closed`,`read`));let n=this.spec.keyOf(t),r=this.touched(n)??this.firstRead(this.created(n,t));return e.take(`${this.spec.name}:${n}`,()=>this.hold(r)),{current:()=>jj(r)}}supersede(e){if(this.closed)return()=>{};let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,Oj(n,`superseded`),this.abandon(n),n.changed=!1,this.evict();let r=!1;return()=>{r||(r=!0,n.superseding--,this.entries.get(n.key)===n&&this.refresh(n,`supersede`))}}changed(e){for(let t of this.entries.values())e(t.input)&&this.heard(t)}heard(e){e.holders>0&&this.refresh(e,`change`)}isHeld(e){for(let t of this.entries.values())if(t.holders>0&&e(t.input))return!0;return!1}stats(){let e=0;for(let t of this.entries.values())t.holders>0&&e++;let{refreshes:t,failures:n,abandoned:r,lastMs:i}=this.refreshes.record();return{entries:this.entries.size,held:e,refreshes:t,failures:n,abandoned:r,lastMs:i}}close(){this.closed=!0;for(let e of[...this.entries.values()])this.drop(e)}touched(e){let t=this.entries.get(e);if(t!==void 0)return this.entries.delete(e),this.entries.set(e,t),t}created(e,t){let n={key:e,input:t,reading:Tj(),holders:0,flight:null,changed:!1,superseding:0,revisit:Rj(this.spec.every(t),this.spec.clock,{period:()=>this.refresh(n,`period`),holdReturned:()=>this.refresh(n,`change`)}),unwatch:()=>{}};return this.entries.set(e,n),n.unwatch=this.spec.watch(t,()=>this.heard(n)),n}firstRead(e){return this.refresh(e,`first`),e}refresh(e,t){if(e.superseding>0)return;if(e.flight!==null){e.changed||=t===`change`;return}let n=new AbortController;e.flight=n;let r=this.spec.clock.monotonic();Bj(()=>this.spec.read(e.input,n.signal)).then(i=>{let a=this.spec.fields(e.input,e.holders),o=Qe(this.spec.clock,r);if(n.signal.aborted){this.refreshes.abandoned(a,t,o);return}try{this.refreshes.recorded(a,t,i,o)}finally{this.store(e,i)}}).catch(t=>{this.spec.logger(`error`,`${this.spec.name} refresh threw (${this.spec.fields(e.input,e.holders)}): ${String(t)}`)})}store(e,t){e.flight=null;try{Dj(e,t)}finally{e.revisit.landed(t),e.changed&&(e.changed=!1,this.refresh(e,`change`))}}hold(e){return e.holders++,e.revisit.hold(!0),this.evict(),()=>{e.holders--,e.revisit.hold(e.holders>0),this.evict()}}evict(){for(let e of[...this.entries.values()]){if(this.entries.size<=this.spec.maxEntries)return;e.holders===0&&e.superseding===0&&this.drop(e)}}drop(e){this.entries.delete(e.key),this.abandon(e),e.unwatch(),e.revisit.dispose(),kj(e,L(`${this.spec.name} entry dropped`,`read`))}abandon(e){let t=e.flight;e.flight=null,t?.abort(Error(`${this.spec.name} read abandoned`))}};function Rj(e,t,n){if(e===null)return new zj(n.holdReturned);let r=new wj(n.period,t);return{landed:t=>r.landed(Sj(e,t)),hold:e=>r.hold(e),dispose:()=>r.dispose()}}var zj=class{state=`released`;answered=!1;constructor(e){this.reread=e}landed(){this.answered=!0}hold(e){if(this.state===`disposed`)return;let t=e&&this.state===`released`&&this.answered;this.state=e?`held`:`released`,t&&this.reread()}dispose(){this.state=`disposed`}};function Bj(e){let t=e=>L(`read threw: ${String(e)}`,`read`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}const Vj=[`first`,`period`,`change`,`request`,`supersede`];var Hj=class{tallies=new Map;constructor(e=Ie){this.logger=e}declare(e){let t=`${e.scope}/${e.name}`,n=this.tallies.get(t)??{name:e.name,scope:e.scope,refreshes:{},failures:0,abandoned:0,lastMs:null};for(let t of e.refresh)n.refreshes[t]??=0;return this.tallies.set(t,n),new Wj(n,this.logger)}snapshot(){return[...this.tallies.entries()].sort(([e],[t])=>e<t?-1:+(e>t)).map(([,e])=>({...e,refreshes:{...e.refreshes}}))}totals(){let e=Object.fromEntries(Vj.map(e=>[e,0]));for(let t of this.tallies.values())for(let n of Vj)e[n]+=t.refreshes[n]??0;return e}};const Uj={first:!0,period:!0,change:!0,request:!1,supersede:!0};var Wj=class{constructor(e,t){this.tally=e,this.logger=t}record(){return{...this.tally,refreshes:{...this.tally.refreshes}}}recorded(e,t,n,r){this.tally.refreshes[t]=(this.tally.refreshes[t]??0)+1,this.tally.lastMs=r,n.kind===`failed`&&this.tally.failures++;let i=n.kind===`failed`;if(!i&&!Uj[t])return;let a=i?` reason=${JSON.stringify(n.reason)}`:``;this.logger(i?`warn`:`info`,`${this.tally.name} refresh ${e} by=${t} outcome=${n.kind}${a} took=${r}ms`)}abandoned(e,t,n){this.tally.abandoned++,this.logger(`info`,`${this.tally.name} refresh ${e} by=${t} abandoned took=${n}ms`)}};const Gj=/\r\n|\r|\n/g,Kj=e=>F(e.replace(Gj,` `).trim());function qj(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?L(`regex no-match`,`parse`):F(n.replace(Gj,` `))}}const Jj=e=>{try{return F(JSON.parse(e))}catch(e){return L(`JSON parse failed: ${e.message}`,`parse`)}},Yj=e=>$y(e);function Xj(e){return ie.createHash(`sha256`).update(e).digest(`hex`)}const Zj=e=>e.kind===`shell`?`output of "${e.command}" in ${e.cwd}`:`"${e.path}"`;function Qj(e,t,n,r){return{where:Zj({kind:`shell`,command:t,cwd:n}),read:async()=>{let i=await e.launch({bin:`/bin/sh`,args:[`-c`,t],cwd:n,category:`user-shell`,timeoutMs:1e4,signal:r});return i.ok?F(i.stdout):L(`shell "${t}" ${gt(i,` in ${n}`)}`,`read`)}}}function $j(e,t,n){return{where:Zj({kind:`file`,path:e,readMode:t}),read:async()=>{try{let r=await he(e,{encoding:`utf8`,signal:n});return F(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch(t){let r=t.code??String(t);return L(n.aborted?`file read aborted: ${String(n.reason)}`:`file unreadable (${r}): ${e}`,`read`)}}}}function eM(e,t,n){switch(t.kind){case`shell`:return Qj(e,t.command,t.cwd,n);case`file`:return $j(t.path,t.readMode,n)}}function tM(e){switch(e.kind){case`text`:return Kj;case`regex`:return qj(new RegExp(e.source,e.flags));case`json`:return e=>e.trim()===``?I:Jj(e)}}function nM(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?L(`${r.reason} in ${n}`,r.failedAt):r}var rM=class{entries=new Map;releaseDelivery;constructor(e,t){this.watchers=e,this.fileEvents=t,this.releaseDelivery=t.subscribe(e=>this.noticed(e))}subscribe(e,t,n){let r=this.entries.get(e)??this.arm(e);return r.subscribers.set(t,n),n(this.faultOf(e,r)),()=>this.unsubscribe(e,t)}arm(e){let t=iM(this.watchers.filesystem,e),n={bound:{derived:t,held:this.watchers.follow(null,t,t=>this.heard(e,n,t)).watch},subscribers:new Map};return this.entries.set(e,n),n}rederive(e,t){let n=iM(this.watchers.filesystem,e),{watch:r}=this.watchers.follow(t.bound.held,n,n=>this.heard(e,t,n));t.bound={derived:n,held:r},this.report(e,t)}heard(e,t,n){let r=t.bound.derived.reached;if(this.rederive(e,t),!(n.kind!==`failed`&&!r&&!t.bound.derived.reached))for(let e of t.subscribers.keys())e()}report(e,t){let n=this.faultOf(e,t);for(let e of t.subscribers.values())e(n)}faultOf(e,t){return dj(`watch_file ${e}`,t.bound,Gc(this.fileEvents.delivery(),t.bound.held.handle))}noticed(e){switch(e.kind){case`period`:return;case`moved`:case`caught-up`:(0,X.runInAction)(()=>{for(let[e,t]of this.entries){this.rederive(e,t);for(let e of t.subscribers.keys())e()}});return}}unsubscribe(e,t){let n=this.entries.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.bound.held.handle.release(),this.entries.delete(e)))}dispose(){this.releaseDelivery();for(let e of this.entries.values())e.bound.held.handle.release();this.entries.clear()}size(){return this.entries.size}};const iM=(e,t)=>uj(e,{named:[t],whole:[t]}),aM={declare:(e,t)=>({digest:Yj(t),current:()=>So(`unread`),fault:()=>null})},oM={declare:(e,t)=>{throw Error(`a directory declares no shell or file source, and ${Zj(t.read)} was declared in one: each is a session view's`)}};var sM=class{byKind;watchMgr;faults=X.observable.map(void 0,{deep:!1});constructor(e){let t=e.logger??Ie,n=e.ledger??new Hj(t);this.watchMgr=new rM(e.watchers??new xj({filesystem:mn,clock:e.clock}),e.fileEvents??Bc);let r=r=>new Lj({name:`source.${r}`,scope:`daemon`,keyOf:Yj,fields:(e,t)=>`digest=${Ln(Yj(e))} where=${z(Zj(e.read))} sharedBy=${t}`,read:async(t,n)=>{let r=eM(e.launcher,t.read,n);return nM(await r.read(),tM(t.parse),r.where)},every:({refresh:e})=>e.kind===`ttl`?{okMs:e.durationMs,failedMs:e.durationMs}:null,watch:(e,t)=>{if(e.refresh.kind!==`watch_file`)return Ij();let n=Yj(e),r=this.watchMgr.subscribe(e.refresh.path,t,e=>(0,X.runInAction)(()=>{e===null?this.faults.delete(n):this.faults.set(n,e)}));return()=>{r(),(0,X.runInAction)(()=>this.faults.delete(n))}},maxEntries:0,logger:t,ledger:n,clock:e.clock});this.byKind={shell:r(`shell`),file:r(`file`)}}declare(e,t){let n=Yj(t),r=this.byKind[t.read.kind].declare(e,t);return{digest:n,current:()=>r.current(),fault:()=>this.faults.get(n)??null}}stats(){return{shell:this.byKind.shell.stats(),file:this.byKind.file.stats(),watches:this.watchMgr.size()}}close(){this.byKind.shell.close(),this.byKind.file.close(),this.watchMgr.dispose()}};function cM(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(Pe(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function lM(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const uM=`session.id`;function dM(e){switch(e.kind){case`text`:return{kind:`text`};case`regex`:return{kind:`regex`,source:e.regex.source,flags:e.regex.flags};case`json`:return{kind:`json`}}}const fM={read:()=>So(`unread`),drawnAt:()=>{throw new vw(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}},pM=e=>({kind:`found`,value:e});function mM(e,t){let n=e,r=!1;for(let e of t.split(`.`)){if(!r&&To(n))return n;if(typeof n!=`object`||!n)return pM(void 0);r||=e===`value`&&n.kind===`ok`,n=n[e]}return!r&&To(n)?n:pM(n)}const hM=(e,t)=>`variable "${e}" reads ${t}, which the declaration its facts were gathered under does not name`;var gM=class extends Error{constructor(e,t){super(hM(e,t)),this.name=`UndeclaredReadError`}};function _M(e,t){if(t.kind===`pending`)return t;if(t.kind===`undeclared`)return L(hM(e,t.fact),`read`);let n=t.value;if(n===void 0)return L(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the preset reads`,`read`);switch(typeof n==`object`&&n?n.kind:void 0){case`ok`:case`absent`:case`failed`:return n;default:return L(`variable "${e}": the view's payload holds no source reading at "${e}"`,`read`)}}function vM(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?hw(e):t===`number`?gw(e):_w(e)}function yM(e){return e===`number`?0:e===`boolean`?!1:``}var bM=class e{lastErrors=new Map;policyFaults=X.observable.map(void 0,{deep:!1});cleanups=[];holds=new sj;identities=new Map;lanes=X.observable.map(void 0,{deep:!1});inputs=X.observable.box(fM,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=tj({drawnAt:this.drawnAt});sourceNames=X.observable.array([],{deep:!1});publishedNow=(0,X.computed)(()=>({values:this.sourceNames.map(e=>this.store.stored(e)),faults:[...this.policyFaults.values()]}));published(){return this.publishedNow.get()}sessionState;constructor(e,t,n=``,r,i=null){this.runs=e,this.store=t,this.defaultEmptyValue=n,this.parent=i,this.sessionState=r}view(t){return new e(t,new Mw(this.store.clock,this.store),this.defaultEmptyValue,this.sessionState,this)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,mw(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,L(t,`parse`))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>_M(e,this.inputs.get().read(e)))}own(e){this.cleanups.push(e)}declareInput(e,t,n,r,i){this.store.defineDerived(e,n,i,()=>this.inputAt(e,t,n,r))}inputAt(e,t,n,r){let i=this.inputs.get().read(t);if(i.kind===`pending`)throw this.lastErrors.delete(e),new vw(e,`variable "${e}" has no value yet: its source has not answered`);if(i.kind===`undeclared`){let t=new gM(e,i.fact);throw this.recordError(e,t.message),t}let a=i.value;if(a===void 0)return this.fallbackOf(e,n,r,`input path "${t}" not found in payload`);try{let t=vM(a,n);return this.lastErrors.delete(e),t}catch(t){return this.fallbackOf(e,n,r,t instanceof Error?t.message:String(t))}}declareShell(e,t,n){this.declareSource(e,{kind:`shell`,command:t,cwd:n.cwd},cM(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,{kind:`file`,path:t,readMode:n.readMode??`whole`},n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r);(0,X.runInAction)(()=>this.sourceNames.push(e)),this.cleanups.push((0,X.reaction)(()=>this.lanes.get(e)?.current(),e=>{e===void 0||e.kind===`pending`||i(e)},{fireImmediately:!0})),this.registerCachePolicy(e,n,n=>this.hold(e,{read:t,parse:dM(r),refresh:n}))}hold(e,t){(0,X.runInAction)(()=>{this.identities.set(e,t);let{result:n}=this.holds.declare(()=>[...this.identities].map(([e,t])=>{let n=this.runs.declare(this.holds,t),r=this.lanes.get(e);return[e,r?.digest===n.digest?r:n]}));for(let[e,t]of n)this.lanes.set(e,t)})}publisherFor(e,t){switch(t.kind){case`text`:case`regex`:return this.scalarPublisher(e,t.default);case`json`:return this.documentPublisher(e,t.default)}}scalarPublisher(e,t){let n=this.stringInitial(t);return this.store.defineBox(e,`string`,n),t=>{this.noteOutcome(e,t),this.store.setBox(e,bo(t,n))}}documentPublisher(e,t){let n=t===void 0?So(`unread`):F(t);this.store.defineDocument(e,n);let r,i=!1;return this.cleanups.push(()=>r?.()),a=>{r?.();let o=a;this.noteOutcome(e,o);let s=o.kind===`ok`||o.kind===`failed`&&o.failedAt===`parse`,c=s||t===void 0?o:n,l=i&&s&&o.kind!==`ok`,u=()=>{i=o.kind===`ok`,this.store.setDocument(e,c)};l?r=this.store.clock.after(250,u):u()}}async inFlight(e){for(;!e.aborted&&this.awaited().length>0;)try{await(0,X.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}return this.awaited()}awaited(){return[...[...this.lanes].filter(([,e])=>e.current().kind===`pending`).map(([e])=>e),...this.parent?.awaited()??[]]}settled(e){return this.inFlight(tt(this.store.clock,e))}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(nj(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){let n=this.engine.parse(`{{ date .layout now }}`),r={layout:t.format};this.declareDerived(e,`string`,`projection`,()=>n.evaluate(r).map(e=>e.plain).join(``),t.varDefault)}declareDerived(e,t,n,r,i){this.store.defineDerived(e,t,n,()=>{try{let n=vM(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=yw(t);if(n!==void 0)throw this.lastErrors.delete(e),n;let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),i===void 0)throw Error(`variable "${e}": ${r}`);return i}})}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(uM);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}stateRevision(){let e=this.store.has(`session.id`)?this.store.read(uM):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}bindInputs(e){(0,X.runInAction)(()=>this.inputs.set(e))}getLastError(e){if(!this.declaredHere(e))return this.parent?.getLastError(e);let t=this.lastErrors.get(e),n=this.policyFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){return new Map([...this.parent?.cachePolicyFaults()??[],...this.policyFaults])}declaredHere(e){return this.store.has(e)&&!(this.parent?.store.has(e)??!1)}dispose(){for(let e of this.cleanups)e();return this.cleanups.length=0,this.holds.close(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:n({kind:`never`});break;case`ttl`:n({kind:`ttl`,durationMs:t.durationMs});break;case`watch_file`:n({kind:`watch_file`,path:t.path}),this.cleanups.push((0,X.reaction)(()=>this.lanes.get(e)?.fault()??null,t=>this.notePolicy(e,t===null?F(void 0):L(t,`read`)),{fireImmediately:!0}));break;case`key`:{let r=this.engine.parse(t.template);this.onReads(e,()=>{try{return F(r.evaluate(nj(this.store)).map(e=>e.plain).join(``))}catch(e){return yw(e)===void 0?L(`cache key: ${e instanceof Error?e.message:String(e)}`,`read`):So(`unread`)}},e=>n({kind:`key`,hash:Xj(e)}));break}case`depends_on`:this.onReads(e,()=>{let e=t.varNames.map(e=>this.store.changeKey(e));return e.every(e=>e.kind===`ok`)?F(e.map(e=>e.value).join(`,`)):So(`unread`)},e=>n({kind:`key`,hash:Xj(e)}));break}}onReads(e,t,n){let r,i=(0,X.reaction)(t,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===r)&&(r=t.value,n(t.value))},{fireImmediately:!0});this.cleanups.push(i)}fallbackOf(e,t,n,r){if(this.recordError(e,r),n!==void 0)return n;try{return vM(this.defaultEmptyValue,t)}catch{return yM(t)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:this.store.clock.now(),message:t})}notePolicy(e,t){(0,X.runInAction)(()=>{t.kind===`failed`?this.policyFaults.get(e)?.message!==t.reason&&this.policyFaults.set(e,{timestamp:this.store.clock.now(),message:t.reason}):this.policyFaults.delete(e)})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function xM(e,t){let n=dx[e],r=vx(e),i=n.kind===`session`||n.kind===`config`?n.floor:``;return r===`string`?{kind:`input`,path:t,default:``}:{kind:`input`,path:t,type:r,default:i}}const SM=Object.fromEntries([...Ex].map(([e,t])=>[t,xM(e,t)])),CM={subscribers:`number`,fps:`number`,shown:`boolean`},wM=Object.keys(CM),TM={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[uM]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`,default:``},config_path:{kind:`input`,path:`configPath`,default:``},...SM,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(Qc.flatMap(e=>wM.map(t=>[rl(e,t),{kind:`input`,path:rl(e,t),type:CM[t],default:nl[t]}]))),[tl(`by`)]:{kind:`input`,path:tl(`by`),default:el.by},[tl(`fps`)]:{kind:`input`,path:tl(`fps`),type:`number`,default:0},...Object.fromEntries([`label`,`fg`,`bg`,`open`].map(e=>[`diagnostics.${e}`,{kind:`input`,path:`diagnostics.${e}`,default:``}])),"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"tmux.pane":{kind:`input`,path:`tmux.pane`,default:``},"autocompact.window":{kind:`input`,path:`autocompact.window`,type:`number`,default:-1},...Object.fromEntries([`applied`,`lower`,`higher`].map(e=>[`autocompact.${e}`,{kind:`input`,path:`autocompact.${e}`,type:`number`,default:0}])),"autocompact.error":{kind:`input`,path:`autocompact.error`,default:``},"location.main":{kind:`input`,path:`location.main`,default:``},"location.worktree":{kind:`input`,path:`location.worktree`,default:``},"location.subpath":{kind:`input`,path:`location.subpath`,default:``},"location.noRepo":{kind:`input`,path:`location.noRepo`,type:`boolean`,default:!1},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},EM={today:`the day the draw is at`,feeds:`the frames a lane was sent up to the draw's instant`,drawing:`who the draw is for`,diagnostics:`the errors and warnings the draw owes its reader`};function DM(e){let t=e.split(`.`,1)[0];return Object.hasOwn(EM,t)?t:void 0}const OM=Object.fromEntries(xy.map(e=>[e,Ex.get(e)]));function kM(e){return xy.find(t=>OM[t]===e)}function AM(e,t,n){let r=new Set,i=(e,t=n)=>{for(let n of UC(e??``,t).keys())r.add(n)};for(let t of Object.values(e.segments)){let e=t.partials===void 0?n:{...n,...t.partials};i(t.template,e),i(t.bg,e),i(t.fg,e),i(t.when,e);for(let n of Object.values(t.partials??{}))i(n,e)}for(let e of t)for(let t of sb(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(uM);for(let t of Object.values(e.actions)){r.add(uM);for(let[,e]of yS(t))i(e);let e=`set`in t?Dx.get(t.set):void 0,n=`persist`in t?Ex.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function jM(e,t,n){let r=cw({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of AM(e,t,n.helpers)){if(sw(a,r))continue;let e=TM[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function MM(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function NM(e){return e}function PM(e,t,n){return n===void 0?CS+MM(e)+`.`+MM(t):FM(n)}function FM(e){return CS+MM(e)}function IM(e,t){return e+`.`+t}function LM(e){return wS+e}const RM=[`closeOnPick`,`paged`,`key`,`distribution`],zM=e=>RM.includes(e),BM=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${wv.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function VM(e){for(let t of Object.keys(e))if(!zM(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${BM}`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);let r=e.distribution;if(r!==void 0&&!Tv(r))throw Error(`{{ menu }} option "distribution" must be one of: ${wv.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Dv(r)}}const HM=e=>`from`in e?e.from:e.themes;function UM(e,t,n){return e===`bool`?Xy(t)!==null:`min`in e?Zy(t,e)!==null:mS(HM(e),n).members.includes(t)}function WM(e,t){let n=e.map(e=>JSON.stringify(e));if(e.length<=8)return`one of ${n.join(`, `)}`;let r=t===void 0?``:` "${t}"`;return`one of the ${e.length}${r} names, such as ${n.slice(0,3).join(`, `)}`}function GM(e,t){if(e===`bool`)return Jy.join(` or `);if(!(`min`in e)){let n=HM(e),{members:r}=mS(n,t);return WM(r,typeof n==`string`?n:void 0)}return`an integer from ${e.min} to ${e.max}`}function KM(e){return{label:e.label,domain:qM(e.domain)}}function qM(e){return e===`theme`?{themes:fS}:e===`bool`||`min`in e?e:{from:e}}function JM(e,t,n,r,i){let a=ya(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...Jy]}},variables:{}};if(`from`in o)return YM(t,r,i,o.from,e=>({template:`{{ carousel "${e.apply}" "${e.open}" "${a}" }}`,rows:[`{{ picker "${e.apply}" "${e.page}" false true true }}`]}));if(`themes`in o)return YM(t,r,i,o.themes,e=>({template:`{{ action "${e.open}" "${a}" .${n} }} {{ action "${e.open}" (swatch "${e.apply}") }}`,rows:[`{{ swatches "${e.apply}" "${e.page}" }}`,`{{ themePreview "${e.apply}" }}`]}));let s=e=>({set:t,min:o.min,max:o.max,by:e});return{kind:`inline`,template:`{{ action "${r}.down" "◀" }} {{ "${a}" }} {{ .${n} }} {{ action "${r}.up" "▶" }}`,actions:{[`${r}.down`]:s(-o.step),[`${r}.up`]:s(o.step)},variables:{}}}function YM(e,t,n,r,i){let a={variable:n,key:n,member:t},o=IM(n,t),s=`${t}.open`,c=LM(n),l=`${c}.current`,{template:u,rows:d}=i({apply:t,open:s,page:c});return{kind:`picker`,template:u,actions:{[t]:{set:e,from:r},[o]:Da(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:Ea(n,ma),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const XM=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],ZM=Object.fromEntries(XM.map(e=>[e.member,e.label])),QM={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},$M=Object.keys(QM),eN=Ox(e=>xx[e].place),tN=e=>Object.hasOwn(QM,e),nN=(e,t)=>e===t||tN(e)&&nN(eN[QM[e].beside],t),rN=e=>tN(e)?`${rN(eN[QM[e].beside])} › ${QM[e].trigger}`:e===`door`?`first line`:ZM[e],iN=e=>rN(eN[e]),aN=()=>[`door`,...XM.map(e=>e.member)].flatMap(e=>[e,...$M.filter(t=>nN(t,e))]).map(e=>({path:rN(e),names:Sx.filter(t=>eN[t]===e)})).filter(({names:e})=>e.length>0),oN=e=>{let{setting:t,on:n,inTmux:r}=Zc[e].switch;return`${Zc[e].label} is off — turn it on in the settings menu's ${iN(t)}, or set globals.${t}: ${JSON.stringify(n)}${r?`; it runs only for a session inside a tmux pane`:``}`},sN=Object.fromEntries(Object.entries(dx).map(([e,t])=>[e,t.spec]));function cN(e){return lN(dx[e])}function lN(e){return`optionDomain`in e&&e.optionDomain!==void 0?{from:e.optionDomain.name}:e.domain}function uN(e,t){return{required:!1,json:{not:{},description:`not allowed here — ${e}`},parse:(e,n,r,i)=>{i[r]!==void 0&&e.issues.push({path:`${n}.${r}`,message:t(`${n}.${r}`),line:J(e.source,[...n.split(`.`),r])})}}}function dN(e){return uN(`${e} cannot select a preset`,t=>`${t}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`)}function fN(e){return uN(`${e} cannot change the settings menu glyph`,t=>`${t}: ${e} cannot change the settings menu glyph — one menu is shared by every preset. Set it in the top-level globals.menuGlyph instead.`)}function pN(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Sy(s)){r.issues.push({path:`${i}.${a}`,message:`${i}.${a}: a rule is not allowed here — ${t} ${n}, so it names a value. Write the rule in globals.${a} (or a preset's globals.${a}) instead.`,line:J(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const mN={default_bg:"nothing reads it — a segment with no `bg:` wears the decoration tint of its place in the bar. Delete the key, and author `bg:` on the segments that need a fixed colour.",default_fg:"nothing reads it — a segment with no `fg:` wears text chosen for contrast against its background. Delete the key, and author `fg:` on the segments that need a fixed colour.",default_truncate_marker:'nothing reads it — a segment clipped to its `width:` always ends in "…". Delete the key.',look:`it was renamed "style" — write the same name as style: "<name>"`,progression:`it was renamed "variation", and its values with it: accent (was secondary-accent), duo (was primary-secondary), mono (was primary)`,experimentalTmuxStatus:`it became the renderer setting — write renderer: "tmux" (or pick tmux in ${iN(`renderer`)} › renderer, from a session inside tmux)`,charset:"the bar always draws Nerd Font glyphs. Delete the key; `cc-candybar doctor` names what your terminal's font is missing."},hN={noun:`globals key`,fields:sN,removed:mN},gN={preset:dN(`a preset`),menuGlyph:fN(`a preset`)},_N={noun:`preset globals key`,fields:{...sN,...gN},removed:mN};function vN(e){return ON(e)&&!(e in gN)}const yN=`is decided later than any rule could be settled`,bN={noun:`editGlobals key`,removed:mN,fields:{...sN,preset:dN(`the editGlobals fragment`),menuGlyph:fN(`the editGlobals fragment`),palette:pN(sN.palette,`the editGlobals fragment`,yN),style:pN(sN.style,`the editGlobals fragment`,yN),effect:pN(sN.effect,`the editGlobals fragment`,yN)}},xN={noun:`theme default key`,fields:{...Object.fromEntries(mx.map(e=>[e,sN[e]])),style:pN(sN.style,`a theme's default`,`is the look that theme wears by name`)}};function SN(e,t){if(!Qy(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${Lb(t)}`,line:J(e.source,[`themeDefaults`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=`themeDefaults.${r}`;if(!e.allowedPalettes.has(r)){e.issues.push({path:t,message:`${t}: "${r}" is not an installed theme${py(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[`themeDefaults`,r])});continue}let a=Rb(e,xN,t,i);a!==null&&(n[r]=a)}return n}function CN(e,t,n){return n===void 0?{}:Rb(e,hN,t,n)??{}}function wN(e,t,n){return Rb(e,_N,t,n)??{}}function TN(){return ate(_N)}function EN(e,t,n){return Rb(e,bN,t,n)??{}}const DN=new Set(Object.keys(sN));function ON(e){return DN.has(e)}function kN(e){return Object.hasOwn(mN,e)?mN[e]:void 0}function AN(){return[...DN]}const jN=new Map(Object.entries(dx).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function MN(e){let t=new Map;for(let[n,r]of jN){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const NN=/^segments\.([^.]+)\.palette$/,PN=/^presets\.(.+)\.root$/,FN=/^presets\.(.+)\.globals\.([^.]+)$/,IN=/^themeDefaults\.(.+)\.([^.]+)$/;function LN(e){return`presets.${e}.root`}function RN(e,t){return`themeDefaults.${e}.${t}`}const zN=e=>mx.includes(e);function BN(e,t){return`presets.${e}.globals.${t}`}function VN(e){if(ON(e))return{scope:`globals`,field:e};let t=NN.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=FN.exec(e);if(n&&vN(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=IN.exec(e);if(r&&zN(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=PN.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function HN(e){switch(e.scope){case`globals`:return[`globals`,e.field];case`preset-globals`:return[`presets`,e.preset,`globals`,e.field];case`segment-palette`:return[`segments`,e.segment,`palette`];case`theme-default`:return[`themeDefaults`,e.theme,e.field]}}const UN=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],WN=[...UN,`other`],GN={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},KN=iE({fromString:e=>e});function qN(e){let t=MM(e);return DS.find(e=>t.startsWith(MM(e)))}function JN(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:J(e.source,[`root`])})}function YN(e,t,n){for(let r of[`variables`,`actions`,`helpers`,`segments`])for(let i of Object.keys(t[r]??{})){let t=EC(i);t!==void 0&&(r!==`variables`&&i===t||r===`segments`&&n.has(i)||e.issues.push({path:`${r}.${i}`,message:`"${i}" is in "${t}", the namespace plugins own (each declares its names there from its own definition) — rename it`,line:J(e.source,[r,i])}))}for(let[r,i]of Object.entries(t.segments??{}))for(let t of Object.keys(i.vars??{})){let i=`${r}.${t}`,a=EC(i);a===void 0||n.has(r)||e.issues.push({path:`segments.${r}.vars.${t}`,message:`segment "${r}"'s var "${t}" is named "${i}", in "${a}", the namespace plugins own — rename the var or the segment`,line:J(e.source,[`segments`,r,`vars`,t])})}}const XN=`edit.mode`,ZN=`edit.configure`,QN=`edit.toggle`,$N=`arrange`,eP=`${TS}draft.`;function tP(e,t){return`${e}:${t}`}const nP={variable:XN,key:XN,member:$N},rP=xa(nP);function iP(e){try{return KN.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function aP(e){if(Object.values(e.actions??{}).some(e=>`do`in e&&e.do.includes(`edit.toggle`)))return!0;for(let t of Object.values(e.segments??{})){let e=[t.template,t.bg,t.fg,...Object.values(t.partials??{})];for(let t of e)if(typeof t==`string`&&iP(t))return!0}return!1}function oP(e,t){if(JN(e,t,TS,`edit mode`),!aP(t))return;let{variables:n,actions:r}=sP();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function sP(){return{variables:{[XN]:{...Ea(XN,ma),within:[jS]},[ZN]:{...Ea(ZN,ma),within:[nP]}},actions:{[QN]:Da(XN,$N),"edit.unconfigure":{set:ZN,to:ma}}}}function cP(e,t,n,r){let i={variable:e,key:e,member:ha};return r.variables[e]={...Ea(e,ma),...n.length>0&&{within:n}},r.actions[e]=Da(e,ha),r.segments[e]={template:Ca(e,`(?)`,`✕`),...lP(n)},ba(e,i,{kind:`container`,direction:`horizontal`,children:t.map((t,n)=>{let i=`${e}.${n}`;return r.segments[i]={template:t},{kind:`segment`,name:i}})},`drop`)}function lP(e){let[t,...n]=e;return t===void 0?{}:{when:xa(t,...n)}}const uP=`none`;function dP(e){return ed(e,`background`)}var fP=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function pP(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=mP(n,i),l=c!==uP,u=l?c===void 0?o:hP(a,c,`bg`):dP(a);e.bg=u;let d=mP(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:Uv(a,e,t))(u):void 0:hP(a,d,`fg`);return new W({...l&&{bgcolor:U.fromRgba(u)},...f!==void 0&&{color:U.fromRgba(f)}})}function mP(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function hP(e,t,n){try{return ed(e,t)}catch(e){throw e instanceof $u?new fP(t,n,e.message):e}}const gP=`🔧`,_P={help:[`-h`,`--help`],version:[`-V`,`--version`]},vP=[...new Set(Object.values(Zc).map(e=>iN(e.switch.setting)))].join(` or `),yP=Math.max(...Object.values(xx).map(e=>e.configKey.length))+2,bP=[`✚ inserts`,`✖ removes`,`${gP} configures`,`↺ resets layout`],xP={band:[`animates the bar in the band above the prompt, through a Claude Code mod`,`on: installs the candybar-band mod from this checkout and types /reload-plugins`],statusline:[`animates the statusline itself, through the attach launcher shipped with cc-candybar`,`on: exits this Claude Code and starts it again under that launcher, on this session`,`or start one yourself: cc-candybar --help prints the line to type`],pane:[`animates the bar in a tmux pane under this session's`,`on: opens that pane · off: closes it`],tmuxStatus:[`draws the bar in the tmux status line, while this session's pane is the one it shows`,`tmux: the daemon draws it there · claude: puts the status line back as it was`]},SP=`
70
+ `)){let n=``;for(let i of t.split(/\s+/))i.length!==0&&(n.length===0?n=i:n.length+1+i.length<=e?n+=` ${i}`:(r.push(n),n=i));n.length>0&&r.push(n)}return r.join(t)}function Wk(e,t,n){return Uk(e,t,n)}function Gk(){return{abbrev:{fn:(e,t)=>UO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>WO(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>ok(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>sk(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>ck(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>lk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>uk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>dk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>fk(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>pk(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>hk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>gk(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>_k(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>vk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>yk(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>bk(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>xk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>Sk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>Ck(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>wk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>Tk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>Ek(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>Dk(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>kk(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>Ak(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>jk(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>Pk(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>Fk(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>Ik(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>Lk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>Rk(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>zk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>Bk(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>Vk(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>Hk(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>Wk(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function Kk(e,t){let n=qk(e),r=n.copy();return r.style=Yf(n.style,t),r}function qk(e){if(!(e instanceof q))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function Jk(e){return{fn:(t=>Kk(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function Yk(e){return{fn:((t,n)=>Kk(n,new W({[e]:U.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function Xk(e,t){return new W({[e]:t})}function Zk(){let e={};for(let t of Vf)e[t]=Jk(Xk(t,!0)),e[`not_${t}`]=Jk(Xk(t,!1));for(let[t,n]of Object.entries(Uf))e[t]=Jk(Xk(n,!0));return e}const Qk={fn:((e,t)=>Kk(t,W.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},$k={fn:((e,t)=>Kk(t,new W({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function eA(){return{fg:Yk(`color`),bg:Yk(`bgcolor`),...Zk(),link:$k,style:Qk}}function tA(e,t){let n;try{n=Cu(e.trim())}catch(n){throw n instanceof au?TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`,{cause:n}):n}return nA(n,t,JSON.stringify(e))}function nA(e,t,n){if(e.alpha===0)throw RangeError(`${t} got ${n}, which is fully transparent: it draws no colour of its own, so there is nothing to compute with — use the colour of the surface it sits on, e.g. (color "background")`);return e}function rA(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function iA(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`)}return e}const aA=rA([`string`,`int`],((e,t)=>od(tA(e,`darken`),t).hex)),oA=rA([`string`,`int`],((e,t)=>od(tA(e,`lighten`),-t).hex)),sA={min:0,max:100,note:`0 = from, 100 = toward`},cA=rA([`string`,`string`,`float`],((e,t,n)=>wu(tA(e,`mix`),tA(t,`mix`),iA(n,`mix`,`percentage`,sA)/100).hex)),lA={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},uA=rA([`string`],(e=>ud(tA(e,`contrastOn`)).hex)),dA={depth:H.TRUECOLOR},fA=e=>rA([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return dd(tA(t,`readableOn`),tA(n,`readableOn`),iA(r,`readableOn`,`ratio`,lA),i,void 0,a).hex})),pA={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function mA(){let e={};for(let[t,n]of Object.entries(pA)){let r=t;e[n]=rA([`string`,`float`],((e,t)=>{let i={...Ru,[r]:iA(t,n,`amount`)};return Xu.fromRgba(tA(e,n)).applyKey(i).toRgba().hex}))}return e}function hA(e=()=>dA){return{darken:aA,lighten:oA,mix:cA,contrastOn:uA,readableOn:fA(e),...mA()}}function gA(e,t){if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:nA(ed(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function _A(e){return{color:{fn:(t=>ed(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new Ip(Tf(n),gA(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}const vA=Up.play(0);function yA(e,t,n){if(t.length%2!=0)throw RangeError(`last hold (${String(t[t.length-1])} s) has no ${e} — the arguments are <seconds> <${e}> pairs`);let r=[];for(let e=0;e<t.length;e+=2){let i=t[e];if(!Number.isFinite(i)||i<=0)throw RangeError(`hold ${e/2} must be a positive number of seconds, got ${i}`);r.push({seconds:i,value:n(t[e+1])})}return r}const bA={...j_.loops,typewriter:e=>j_.transitions.typewriter(e).effect,scramble:e=>j_.transitions.scramble(e).effect,backspace:e=>j_.transitions.backspace(e).effect,scrambleOut:e=>j_.transitions.scrambleOut(e).effect};function xA(e){if(!Object.hasOwn(bA,e))throw RangeError(`unknown glyph effect ${JSON.stringify(e)}; expected one of ${Object.keys(bA).map(e=>JSON.stringify(e)).join(`, `)}`);return bA[e]}function SA(e,t={}){let n=t.timeline??(()=>vA),r=(e,t,r)=>[Up.run(n(),t),kf(e,r.time)],i=(t,n)=>{let i=e(),[a,o]=r(t,n,i),s=Tp(a,o,i);return i.onHold?.(Ep(s,o)),s.value},a=(e,t)=>Up.run(Up.play(e),t);return{frames:{fn:((...t)=>{let n=yA(`frame`,t,qk).map(({seconds:e,value:t})=>({seconds:e,text:t})),i=e();return N_(...r(`frames`,new M_(n),i),i)}),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...e)=>{let t=yA(`color`,e,e=>tA(e,`stepped`));return t[i(`stepped`,If(t.map(e=>e.seconds)))].value.hex}),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:2},returnType:`string`},tween:{fn:((e,t,n,r,o)=>i(`tween`,a(n,Fp(r,o,{seconds:e,ease:Tf(t)})))),argTypes:[`float`,`string`,`float`,`float`,`float`],arity:{kind:`exact`},returnType:`float`},loop:{fn:((e,t)=>i(`loop`,a(t,K.continuous(Lf.loop(e))))),argTypes:[`float`,`float`],arity:{kind:`exact`},returnType:`float`},glyphs:{fn:((t,n,i)=>{let o=xA(t),s=qk(i),c=s.plain,l=e();return N_(...r(`glyphs`,a(n,l_(s,o({z:Mh(c,0,0)}),{key:c,asciiOnly:l.asciiOnly===!0})),l),l)}),argTypes:[`string`,`float`,`liftable`],arity:{kind:`exact`},returnType:`T`}}}function CA(e){return{...eA(),...hA(e)}}new W({color:`red`,dim:!0});const wA=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i,TA=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function EA(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(wA);if(n?.groups){let{family:e,newMajor:t,newMinor:r,oldMajor:i,oldMinor:a,oldFamily:o}=n.groups,s=e||o,c=t||i,l=r||a;if(s&&c)return`${s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()} ${l?`${c}.${l}`:c}`}let r=t.match(TA);if(r?.groups){let e=r.groups.family,t=r.groups.major,n=r.groups.minor;return`${e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()} ${n?`${t}.${n}`:t}`}return t||e}function DA(e){let t=e.match(TA);if(!t?.groups)return e;let n=t.groups.family,r=t.groups.major,i=t.groups.minor;return`${n.charAt(0).toUpperCase()}${i?`${r}.${i}`:r}`}function OA(e){let t=e.split(`/`),n=t.length-1;return t.map((e,t)=>{if(t===n)return e;let r=e.match(/^\.*./);return r?r[0]:e}).join(`/`)}function kA(e){return e.toLocaleString()}function AA(e){if(e.length===0)throw Error(`a cascade needs at least one stop, e.g. "0:calm"`);let t=[];for(let[n,r]of e.entries()){let e=r.indexOf(`:`),i=e<0?NaN:Number(r.slice(0,e));if(!Number.isFinite(i))throw Error(`cascade stop ${n} ("${r}") must be "<position>:<result>", e.g. "80:hot" — the position must be a number`);let a=t[n-1];if(a!==void 0&&i<a.at)throw Error(`cascade stops must be in ascending position order; stop ${n} at ${i} follows stop ${n-1} at ${a.at}`);t.push({at:i,text:r.slice(e+1)})}return t}function jA(e,t){if(!Number.isFinite(e))throw Error(`a cascade needs a finite value, got ${e}`);let n=-1;for(;n+1<t.length&&t[n+1].at<=e;)n++;return(n<0?t[0]:t[n]).text}const MA=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],NA=MA.length;function PA(e,t){let n=t===void 0?e:t<=0?[]:e.slice(-t);if(n.length===0)return``;let r=n[0],i=n[0];for(let e of n)e<r&&(r=e),e>i&&(i=e);let a=i-r,o=``;for(let e of n){let t=a===0?0:Math.round((e-r)/a*(NA-1));o+=MA[t]}return o}function FA(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(e===``)continue;let r=Number(e);if(!Number.isFinite(r))throw TypeError(`sparkline: non-numeric series element ${JSON.stringify(n)}`);t.push(r)}return t}function IA(e,t,n){if(n.length!==0)throw Error(`${e}: takes at most ${t.length} optional argument${t.length===1?``:`s`} (${t.join(`, `)}), got ${t.length+n.length}`)}const LA=gy(),RA=[...Ry];function zA(){return{basename:{fn:e=>c(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>l(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>OA(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(hw(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>mw(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>gw(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>LA,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>RA,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(IA(`sparkline`,[`width`],n),PA(FA(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>jA(e,AA(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function BA(e,t,n,r){let i=n*6e4-(t*1e3-r);if(i<3e5||e<=0)return-1;let a=e/i;return Math.max(0,Math.round((100-e)/a/6e4))}const VA=e=>({minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e.now().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},etaMinutes:{fn:(t,n,r)=>BA(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function HA(){return{formatInteger:{fn:e=>kA(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>EA(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>DA(e),argTypes:[`string`],arity:{kind:`exact`}}}}let UA=null;function WA(e,t){if(UA!==null)throw Error(`a draw is already in progress: draws do not nest`);let n={at:e,timeline:t,frame:{time:e,onHold:({nextChange:e})=>{n.soonest=Math.min(n.soonest,e)}},soonest:1/0};return UA=n,{heard:()=>n.soonest,[Symbol.dispose]:()=>{UA=null}}}function GA(e){if((0,X._isComputingDerivation)())throw Error(`the clock was read by a value that keeps its answer (${e}): a template reaching a time variable or a clock function by a name it does not spell (index, get) is not known to read the instant — name it: {{ .clock }}`);if(UA===null)throw Error(`the clock was read outside a draw (${e})`);return UA}const KA={now:()=>ot(GA(`now`).at),frame:()=>GA(`frame`).frame,timeline:()=>GA(`timeline`).timeline};function qA(e,t){let{frames:n,stepped:r}=SA(e,t===void 0?{}:{timeline:t});if(n===void 0||r===void 0)throw Error(`rich-js's animationFuncs no longer registers frames and stepped`);return{frames:n,stepped:r}}const JA=new Set([`now`,`ago`]);function YA(e,t){return Object.fromEntries(Object.entries(SD(e)).filter(([e])=>JA.has(e)===t))}const XA=YA(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),ZA=[e=>YA(e.now,!0),e=>qA(e.frame,e.timeline),e=>Object.fromEntries(Object.entries(qA(e.frame)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),VA];function QA(e){return Object.assign({},...e.map(e=>e(KA)))}const $A=new Set(Object.keys(QA(ZA)));function ej(e){return new Set([...$A,...Object.keys(QA(e))])}function tj(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return rE({fromString:e=>new q(e),toString:e=>e.plain,isT:e=>e instanceof q,missingKey:`error`,funcs:{...AD(),...Gk(),...vO(),...BO(),...fE(),...KD(),...WD(),...XA,...CA(r),readableOn:fA(r),...QA([...ZA,...e.clockFuncs??[]]),...zA(),...HA(),...n??{}}})}function nj(e){return rj(e,new Set(e.names()),``)}function rj(e,t,n){return new Proxy(Object.create(null),{has(r,i){if(typeof i!=`string`)return!1;let a=n?`${n}.${i}`:i;if(t.has(a))return!aj(e,a);let o=`${a}.`;for(let e of t)if(e.startsWith(o))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a)){if(e.getKind(a)!==`document`)return e.read(a);let t=e.readDocument(a);return t.kind===`absent`?void 0:oj(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return rj(e,t,a)}})}function ij(e,t){return new Proxy(e,{has:(e,t)=>t===`settings`||Reflect.has(e,t),get:(e,n)=>n===`settings`?t:Reflect.get(e,n)})}function aj(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function oj(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new _w(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}var sj=class{held=new Map;declaring=null;closed=!1;take(e,t){if(this.closed)throw Error(`hold taken after close: ${e}`);this.declaring?.taken.add(e),!this.held.has(e)&&(this.held.set(e,t()),this.declaring!==null&&this.declaring.acquired++)}declare(e){if(this.declaring!==null)throw Error(`declaration within one`);let t={taken:new Set,acquired:0};this.declaring=t;let n;try{n=e()}finally{this.declaring=null}let r=0;for(let[e,n]of this.held)t.taken.has(e)||(this.held.delete(e),n(),r++);return{result:n,acquired:t.acquired,released:r}}close(){this.closed=!0;let e=this.held.size;for(let e of this.held.values())e();return this.held.clear(),e}get size(){return this.held.size}};function cj(e,t){let{dir:n,rest:r}=Gn(e,s.dirname(t));return{dir:n,name:r[0]??s.basename(t),leaf:r.length===0}}const lj=(e,t)=>Pe(t);function uj(e,t){let n=[],r=!0,i=new Map;for(let a of t.named){let{hops:t,stopped:o}=br(e,a);o!==null&&n.push({path:a,reason:o.message});for(let n of t){let{dir:t,name:a,leaf:o}=cj(e,n);r&&=o;let s=i.has(t)?i.get(t):new Set;s?.add(a),i.set(t,s)}}for(let n of t.whole.map(t=>Wn(e,t)))n!==null&&i.set(n,null);let a={dirs:[...i.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})},o=new Map(a.dirs.map(t=>{let n=Lc(e,t.path);return[t.path,zc(n)?Rc(n):null]}));return{key:JSON.stringify([a,[...o]]),targets:a,unbound:[...o.values()].includes(null),bound:o,reached:r,unresolved:n}}function dj(e,t,n){let r=[...t.derived.unresolved.map(e=>`cannot follow a link chain — ${e.reason}`),...t.held.handle.deaf.map(fj),...n===null?[]:[n]];return r.length===0?null:`${e}: ${r.join(`; `)}`}const fj=e=>e.kind===`refused`?`cannot watch ${e.path} — ${e.reason}`:`watching ${e.path} failed — ${e.reason}`;function pj(e,t){if(t.kind===`failed`)return t;if(e.kind!==`changed`)return e;if(t.kind===`unknown`)return t;for(let n of t.paths)e.paths.add(n);return e}const mj=(e,t)=>t===null?{kind:`unknown`}:{kind:`changed`,paths:new Set([s.join(e,t)])},hj=e=>({kind:`failed`,reason:`${e.path}: ${e.reason}`}),gj=(e,t)=>e.kind===`listening`&&e.handle===t,_j=(e,t)=>e?.kind===`deaf`&&e.deafness.kind===t.kind&&e.deafness.reason===t.reason,vj=(e,t)=>`${t?`names`:e.recursive===!0?`tree`:`dir`}:${e.path}`;function yj(e,t,n){try{let r=e.lstatSync(s.join(t,n)),i=r.kind===`directory`?``:`${r.size}:${r.mtimeMs}`;return`${r.kind}:${r.dev}:${r.ino}:${r.mode}:${i}`}catch(e){return`error:${e.code}`}}const bj=e=>new Set([...e.listeners].flatMap(({filter:e})=>[...e??[]]));var xj=class{slots=new Map;dirs=new Map;counters;logger;clock;filesystem;sweep=null;closed=!1;constructor(e){this.clock=e.clock,this.filesystem=e.filesystem,this.counters=e.counters,this.logger=e.logger??lj}get namesPolled(){return this.filesystem.watchReach===`tree`}acquire(e,t,n){if(this.closed)return{release:()=>{},ridesStream:!1,deaf:t.dirs.map(e=>({kind:`refused`,path:e.path,reason:`the watcher registry is closed`}))};let r=this.slots.get(e);for(let{dir:e}of r?.listeners??[])this.judged(e,`acquire`);let i=r??this.opened(e,t),a={onInvalidate:n};return i.holders.add(a),this.makeHandle(i,a)}follow(e,t,n){if(e!==null&&(e.key===t.key||t.unbound))return{watch:e,move:`kept`};let r={key:t.key,handle:this.acquire(t.key,t.targets,n)};return e?.handle.release(),{watch:r,move:`rebound`}}opened(e,t){let n={key:e,listeners:[],holders:new Set,debounce:null};for(let e of t.dirs){let t=this.dirFor(e),r={slot:n,dir:t,filter:e.filenames?new Set(e.filenames):null};t.listeners.add(r),n.listeners.push(r),this.baseline(t)}return this.slots.set(e,n),this.counters&&(n.listeners.every(e=>e.dir.state.kind!==`deaf`)?this.counters.watchersOpened++:this.counters.watchRefusals++),n}dirFor(e){let t=this.namesPolled&&e.filenames!==void 0,n=vj(e,t),r=this.dirs.get(n);if(r!==void 0)return this.judged(r,`acquire`),r;let i={path:e.path,recursive:e.recursive===!0,polled:t},a={id:n,...i,listeners:new Set,state:this.open(i,()=>a,`acquire`,null)};return this.dirs.set(n,a),a}judged(e,t){if(e.state.kind===`deaf`){this.reopen(e,t);return}if(e.state.kind===`polling`)return;let n=Lc(this.filesystem,e.path);zc(n)&&Rc(n)!==e.state.bound&&this.reopen(e,`another folder is at its path`)}judge(){for(let e of this.dirs.values())this.judged(e,`period`)}reopen(e,t){let n=e.state;n.kind===`listening`&&this.closeHandle(e.path,n.handle,t),e.state=this.open(e,()=>e,t,n),this.baseline(e),e.state.kind===`deaf`?_j(n,e.state.deafness)||this.tell(e,hj(e.state.deafness)):this.tell(e,{kind:`unknown`})}open(e,t,n,r){let i=e.path,a=Rc(Lc(this.filesystem,i));try{if(this.filesystem.opendirSync(i),e.polled)return this.logger(`info`,`dir names polled path=${z(i)} cause=${z(n)}`),this.armSweep(),{kind:`polling`,bound:a,seen:new Map};let r=this.filesystem.watch(i,{recursive:e.recursive},(e,n)=>this.heard(t(),r,n));return r.onError(e=>{this.logger(`warn`,`watcher error ${i}: ${e.message}`),this.counters&&this.counters.watchErrors++;let n=t();if(!gj(n.state,r))return;this.closeHandle(i,r,`error`);let a={kind:`failed`,path:i,reason:e.message};n.state={kind:`deaf`,deafness:a},this.tell(n,hj(a))}),this.counters&&this.counters.dirWatchesOpened++,this.logger(`info`,`dir watch opened path=${z(i)} cause=${z(n)}`),{kind:`listening`,handle:r,bound:a}}catch(e){let t={kind:`refused`,path:i,reason:e.message};return _j(r,t)||this.logger(`warn`,`watch failed ${i}: ${t.reason}`),{kind:`deaf`,deafness:t}}}heard(e,t,n){let{state:r}=e;if(!gj(r,t))return;let i=n===s.basename(e.path)&&Rc(Lc(this.filesystem,e.path))!==r.bound;for(let{slot:t,filter:r}of e.listeners)(r===null||n===null||r.has(n)||i)&&this.fire(t,mj(e.path,n));i&&this.judged(e,`moved`)}tell(e,t){for(let{slot:n}of e.listeners)this.fire(n,t)}fire(e,t){if(e.debounce!==null){e.debounce.window=pj(e.debounce.window,t);return}let n={window:t,cancel:this.clock.after(50,()=>{e.debounce=null;for(let t of e.holders)try{t.onInvalidate(n.window)}catch(t){this.logger(`warn`,`watcher invalidate threw key=${z(e.key)}: ${t.message}`)}},{unref:!0})};e.debounce=n}makeHandle(e,t){return{ridesStream:e.listeners.some(({dir:e})=>!e.polled),get deaf(){return e.listeners.flatMap(({dir:e})=>e.state.kind===`deaf`?[e.state.deafness]:[])},release:()=>{!e.holders.delete(t)||e.holders.size>0||this.slots.get(e.key)===e&&(this.closeSlot(e,`last release`),this.slots.delete(e.key))}}}closeHandle(e,t,n){try{t.close()}catch{}this.counters&&this.counters.dirWatchesClosed++,this.logger(`info`,`dir watch closed path=${z(e)} cause=${z(n)}`)}closeSlot(e,t){e.debounce!==null&&(e.debounce.cancel(),e.debounce=null);for(let n of e.listeners){let{dir:e}=n;if(e.listeners.delete(n),e.state.kind===`polling`){let t=bj(e);for(let n of e.state.seen.keys())t.has(n)||e.state.seen.delete(n)}e.listeners.size>0||(e.state.kind===`listening`&&this.closeHandle(e.path,e.state.handle,t),e.state.kind===`polling`&&this.logger(`info`,`dir names unpolled path=${z(e.path)} cause=${z(t)}`),this.dirs.delete(e.id))}this.sweep!==null&&!this.polling()&&(this.sweep(),this.sweep=null),this.counters&&this.counters.watchersClosed++}polling(){return[...this.dirs.values()].some(e=>e.state.kind===`polling`)}baseline(e){let{state:t}=e;if(t.kind===`polling`)for(let n of bj(e))t.seen.has(n)||t.seen.set(n,yj(this.filesystem,e.path,n))}armSweep(){this.sweep!==null||this.closed||(this.sweep=this.clock.after(1e3,()=>{this.sweep=null,this.armSweep(),this.pollNames()},{unref:!0}))}pollNames(){for(let e of this.dirs.values()){let{state:t}=e;if(t.kind!==`polling`)continue;let n=Rc(Lc(this.filesystem,e.path)),r=bj(e);if(n!==t.bound){t.bound=n;for(let n of r)t.seen.set(n,yj(this.filesystem,e.path,n));this.tell(e,{kind:`unknown`});continue}for(let n of r){let r=yj(this.filesystem,e.path,n);if(t.seen.get(n)!==r){t.seen.set(n,r);for(let{slot:t,filter:r}of e.listeners)r?.has(n)&&this.fire(t,mj(e.path,n))}}}}size(){return this.slots.size}dirWatches(){return[...this.dirs.values()].filter(e=>e.state.kind===`listening`).length}polledDirs(){return[...this.dirs.values()].filter(e=>e.state.kind===`polling`).length}watchedDirs(){return[...this.dirs.values()].map(e=>e.path)}closeAll(){this.closed=!0,this.sweep?.(),this.sweep=null;for(let e of this.slots.values())this.closeSlot(e,`close`);this.slots.clear()}};function Sj(e,t){return t.kind===`failed`?e.failedMs:e.okMs}function Cj(e,t,n){return t===0?e.okMs:Math.min(e.failedMs*2**(t-1),n)}var wj=class{stop=null;state=`released`;last=null;constructor(e,t){this.tick=e,this.clock=t}landed(e,t=this.clock.monotonic()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.clock.monotonic());this.stop=this.clock.after(e,()=>{this.stop=null,this.tick()},{unref:!0})}cancel(){this.stop?.(),this.stop=null}};function Tj(){return X.observable.box(Ej(`unread`),{deep:!1})}function Ej(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function Dj(e,t){let n=e.reading.get();n.kind!==`pending`&&(0,X.compareStructural)(n,t)||((0,X.runInAction)(()=>e.reading.set(t)),n.kind===`pending`&&n.land())}function Oj(e,t){let n=e.reading.get();n.kind===`pending`?n.why!==t&&t===`unread`&&(0,X.runInAction)(()=>e.reading.set({...n,why:t})):(0,X.runInAction)(()=>e.reading.set(Ej(t)))}function kj(e,t){e.reading.get().kind===`pending`&&Dj(e,t)}function Aj(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function jj(e){return e.reading.get()}async function Mj(e){for(;;){let t=e();if(!Aj(t))return t;await t.landed}}function Nj(e,t,n,r){let i=new AbortController,a=()=>i.abort(),o=t>0?r(t,a):Pj(a);return new Promise((t,r)=>{i.signal.addEventListener(`abort`,()=>t(`deadline`)),e(i.signal).then(()=>t(`answered`),e=>i.signal.aborted?n(e):r(e))}).finally(()=>{o(),i.abort()})}function Pj(e){return Promise.resolve().then(()=>process.nextTick(e)),()=>{}}function Fj(e){return{current:()=>e}}const Ij=()=>()=>{};var Lj=class{entries=new Map;refreshes;closed=!1;constructor(e){this.spec=e,this.refreshes=e.ledger.declare({name:e.name,scope:e.scope,refresh:[`first`,`period`,`change`,`supersede`]})}declare(e,t){if(this.closed)return Fj(L(`${this.spec.name} closed`,`read`));let n=this.spec.keyOf(t),r=this.touched(n)??this.firstRead(this.created(n,t));return e.take(`${this.spec.name}:${n}`,()=>this.hold(r)),{current:()=>jj(r)}}supersede(e){if(this.closed)return()=>{};let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,Oj(n,`superseded`),this.abandon(n),n.changed=!1,this.evict();let r=!1;return()=>{r||(r=!0,n.superseding--,this.entries.get(n.key)===n&&this.refresh(n,`supersede`))}}changed(e){for(let t of this.entries.values())e(t.input)&&this.heard(t)}heard(e){e.holders>0&&this.refresh(e,`change`)}isHeld(e){for(let t of this.entries.values())if(t.holders>0&&e(t.input))return!0;return!1}stats(){let e=0;for(let t of this.entries.values())t.holders>0&&e++;let{refreshes:t,failures:n,abandoned:r,lastMs:i}=this.refreshes.record();return{entries:this.entries.size,held:e,refreshes:t,failures:n,abandoned:r,lastMs:i}}close(){this.closed=!0;for(let e of[...this.entries.values()])this.drop(e)}touched(e){let t=this.entries.get(e);if(t!==void 0)return this.entries.delete(e),this.entries.set(e,t),t}created(e,t){let n={key:e,input:t,reading:Tj(),holders:0,flight:null,changed:!1,superseding:0,revisit:Rj(this.spec.every(t),this.spec.clock,{period:()=>this.refresh(n,`period`),holdReturned:()=>this.refresh(n,`change`)}),unwatch:()=>{}};return this.entries.set(e,n),n.unwatch=this.spec.watch(t,()=>this.heard(n)),n}firstRead(e){return this.refresh(e,`first`),e}refresh(e,t){if(e.superseding>0)return;if(e.flight!==null){e.changed||=t===`change`;return}let n=new AbortController;e.flight=n;let r=this.spec.clock.monotonic();Bj(()=>this.spec.read(e.input,n.signal)).then(i=>{let a=this.spec.fields(e.input,e.holders),o=Qe(this.spec.clock,r);if(n.signal.aborted){this.refreshes.abandoned(a,t,o);return}try{this.refreshes.recorded(a,t,i,o)}finally{this.store(e,i)}}).catch(t=>{this.spec.logger(`error`,`${this.spec.name} refresh threw (${this.spec.fields(e.input,e.holders)}): ${String(t)}`)})}store(e,t){e.flight=null;try{Dj(e,t)}finally{e.revisit.landed(t),e.changed&&(e.changed=!1,this.refresh(e,`change`))}}hold(e){return e.holders++,e.revisit.hold(!0),this.evict(),()=>{e.holders--,e.revisit.hold(e.holders>0),this.evict()}}evict(){for(let e of[...this.entries.values()]){if(this.entries.size<=this.spec.maxEntries)return;e.holders===0&&e.superseding===0&&this.drop(e)}}drop(e){this.entries.delete(e.key),this.abandon(e),e.unwatch(),e.revisit.dispose(),kj(e,L(`${this.spec.name} entry dropped`,`read`))}abandon(e){let t=e.flight;e.flight=null,t?.abort(Error(`${this.spec.name} read abandoned`))}};function Rj(e,t,n){if(e===null)return new zj(n.holdReturned);let r=new wj(n.period,t);return{landed:t=>r.landed(Sj(e,t)),hold:e=>r.hold(e),dispose:()=>r.dispose()}}var zj=class{state=`released`;answered=!1;constructor(e){this.reread=e}landed(){this.answered=!0}hold(e){if(this.state===`disposed`)return;let t=e&&this.state===`released`&&this.answered;this.state=e?`held`:`released`,t&&this.reread()}dispose(){this.state=`disposed`}};function Bj(e){let t=e=>L(`read threw: ${String(e)}`,`read`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}const Vj=[`first`,`period`,`change`,`request`,`supersede`];var Hj=class{tallies=new Map;constructor(e=Ie){this.logger=e}declare(e){let t=`${e.scope}/${e.name}`,n=this.tallies.get(t)??{name:e.name,scope:e.scope,refreshes:{},failures:0,abandoned:0,lastMs:null};for(let t of e.refresh)n.refreshes[t]??=0;return this.tallies.set(t,n),new Wj(n,this.logger)}snapshot(){return[...this.tallies.entries()].sort(([e],[t])=>e<t?-1:+(e>t)).map(([,e])=>({...e,refreshes:{...e.refreshes}}))}totals(){let e=Object.fromEntries(Vj.map(e=>[e,0]));for(let t of this.tallies.values())for(let n of Vj)e[n]+=t.refreshes[n]??0;return e}};const Uj={first:!0,period:!0,change:!0,request:!1,supersede:!0};var Wj=class{constructor(e,t){this.tally=e,this.logger=t}record(){return{...this.tally,refreshes:{...this.tally.refreshes}}}recorded(e,t,n,r){this.tally.refreshes[t]=(this.tally.refreshes[t]??0)+1,this.tally.lastMs=r,n.kind===`failed`&&this.tally.failures++;let i=n.kind===`failed`;if(!i&&!Uj[t])return;let a=i?` reason=${JSON.stringify(n.reason)}`:``;this.logger(i?`warn`:`info`,`${this.tally.name} refresh ${e} by=${t} outcome=${n.kind}${a} took=${r}ms`)}abandoned(e,t,n){this.tally.abandoned++,this.logger(`info`,`${this.tally.name} refresh ${e} by=${t} abandoned took=${n}ms`)}};const Gj=/\r\n|\r|\n/g,Kj=e=>F(e.replace(Gj,` `).trim());function qj(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?L(`regex no-match`,`parse`):F(n.replace(Gj,` `))}}const Jj=e=>{try{return F(JSON.parse(e))}catch(e){return L(`JSON parse failed: ${e.message}`,`parse`)}},Yj=e=>Qy(e);function Xj(e){return ie.createHash(`sha256`).update(e).digest(`hex`)}const Zj=e=>e.kind===`shell`?`output of "${e.command}" in ${e.cwd}`:`"${e.path}"`;function Qj(e,t,n,r){return{where:Zj({kind:`shell`,command:t,cwd:n}),read:async()=>{let i=await e.launch({bin:`/bin/sh`,args:[`-c`,t],cwd:n,category:`user-shell`,timeoutMs:1e4,signal:r});return i.ok?F(i.stdout):L(`shell "${t}" ${gt(i,` in ${n}`)}`,`read`)}}}function $j(e,t,n){return{where:Zj({kind:`file`,path:e,readMode:t}),read:async()=>{try{let r=await he(e,{encoding:`utf8`,signal:n});return F(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch(t){let r=t.code??String(t);return L(n.aborted?`file read aborted: ${String(n.reason)}`:`file unreadable (${r}): ${e}`,`read`)}}}}function eM(e,t,n){switch(t.kind){case`shell`:return Qj(e,t.command,t.cwd,n);case`file`:return $j(t.path,t.readMode,n)}}function tM(e){switch(e.kind){case`text`:return Kj;case`regex`:return qj(new RegExp(e.source,e.flags));case`json`:return e=>e.trim()===``?I:Jj(e)}}function nM(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?L(`${r.reason} in ${n}`,r.failedAt):r}var rM=class{entries=new Map;releaseDelivery;constructor(e,t){this.watchers=e,this.fileEvents=t,this.releaseDelivery=t.subscribe(e=>this.noticed(e))}subscribe(e,t,n){let r=this.entries.get(e)??this.arm(e);return r.subscribers.set(t,n),n(this.faultOf(e,r)),()=>this.unsubscribe(e,t)}arm(e){let t=iM(this.watchers.filesystem,e),n={bound:{derived:t,held:this.watchers.follow(null,t,t=>this.heard(e,n,t)).watch},subscribers:new Map};return this.entries.set(e,n),n}rederive(e,t){let n=iM(this.watchers.filesystem,e),{watch:r}=this.watchers.follow(t.bound.held,n,n=>this.heard(e,t,n));t.bound={derived:n,held:r},this.report(e,t)}heard(e,t,n){let r=t.bound.derived.reached;if(this.rederive(e,t),!(n.kind!==`failed`&&!r&&!t.bound.derived.reached))for(let e of t.subscribers.keys())e()}report(e,t){let n=this.faultOf(e,t);for(let e of t.subscribers.values())e(n)}faultOf(e,t){return dj(`watch_file ${e}`,t.bound,Gc(this.fileEvents.delivery(),t.bound.held.handle))}noticed(e){switch(e.kind){case`period`:return;case`moved`:case`caught-up`:(0,X.runInAction)(()=>{for(let[e,t]of this.entries){this.rederive(e,t);for(let e of t.subscribers.keys())e()}});return}}unsubscribe(e,t){let n=this.entries.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.bound.held.handle.release(),this.entries.delete(e)))}dispose(){this.releaseDelivery();for(let e of this.entries.values())e.bound.held.handle.release();this.entries.clear()}size(){return this.entries.size}};const iM=(e,t)=>uj(e,{named:[t],whole:[t]}),aM={declare:(e,t)=>({digest:Yj(t),current:()=>So(`unread`),fault:()=>null})},oM={declare:(e,t)=>{throw Error(`a directory declares no shell or file source, and ${Zj(t.read)} was declared in one: each is a session view's`)}};var sM=class{byKind;watchMgr;faults=X.observable.map(void 0,{deep:!1});constructor(e){let t=e.logger??Ie,n=e.ledger??new Hj(t);this.watchMgr=new rM(e.watchers??new xj({filesystem:mn,clock:e.clock}),e.fileEvents??Bc);let r=r=>new Lj({name:`source.${r}`,scope:`daemon`,keyOf:Yj,fields:(e,t)=>`digest=${Ln(Yj(e))} where=${z(Zj(e.read))} sharedBy=${t}`,read:async(t,n)=>{let r=eM(e.launcher,t.read,n);return nM(await r.read(),tM(t.parse),r.where)},every:({refresh:e})=>e.kind===`ttl`?{okMs:e.durationMs,failedMs:e.durationMs}:null,watch:(e,t)=>{if(e.refresh.kind!==`watch_file`)return Ij();let n=Yj(e),r=this.watchMgr.subscribe(e.refresh.path,t,e=>(0,X.runInAction)(()=>{e===null?this.faults.delete(n):this.faults.set(n,e)}));return()=>{r(),(0,X.runInAction)(()=>this.faults.delete(n))}},maxEntries:0,logger:t,ledger:n,clock:e.clock});this.byKind={shell:r(`shell`),file:r(`file`)}}declare(e,t){let n=Yj(t),r=this.byKind[t.read.kind].declare(e,t);return{digest:n,current:()=>r.current(),fault:()=>this.faults.get(n)??null}}stats(){return{shell:this.byKind.shell.stats(),file:this.byKind.file.stats(),watches:this.watchMgr.size()}}close(){this.byKind.shell.close(),this.byKind.file.close(),this.watchMgr.dispose()}};function cM(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(Pe(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function lM(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const uM=`session.id`;function dM(e){switch(e.kind){case`text`:return{kind:`text`};case`regex`:return{kind:`regex`,source:e.regex.source,flags:e.regex.flags};case`json`:return{kind:`json`}}}const fM={read:()=>So(`unread`),drawnAt:()=>{throw new _w(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}},pM=e=>({kind:`found`,value:e});function mM(e,t){let n=e,r=!1;for(let e of t.split(`.`)){if(!r&&To(n))return n;if(typeof n!=`object`||!n)return pM(void 0);r||=e===`value`&&n.kind===`ok`,n=n[e]}return!r&&To(n)?n:pM(n)}const hM=(e,t)=>`variable "${e}" reads ${t}, which the declaration its facts were gathered under does not name`;var gM=class extends Error{constructor(e,t){super(hM(e,t)),this.name=`UndeclaredReadError`}};function _M(e,t){if(t.kind===`pending`)return t;if(t.kind===`undeclared`)return L(hM(e,t.fact),`read`);let n=t.value;if(n===void 0)return L(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the preset reads`,`read`);switch(typeof n==`object`&&n?n.kind:void 0){case`ok`:case`absent`:case`failed`:return n;default:return L(`variable "${e}": the view's payload holds no source reading at "${e}"`,`read`)}}function vM(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?mw(e):t===`number`?hw(e):gw(e)}function yM(e){return e===`number`?0:e===`boolean`?!1:``}var bM=class e{lastErrors=new Map;policyFaults=X.observable.map(void 0,{deep:!1});cleanups=[];holds=new sj;identities=new Map;lanes=X.observable.map(void 0,{deep:!1});inputs=X.observable.box(fM,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=tj({drawnAt:this.drawnAt});sourceNames=X.observable.array([],{deep:!1});publishedNow=(0,X.computed)(()=>({values:this.sourceNames.map(e=>this.store.stored(e)),faults:[...this.policyFaults.values()]}));published(){return this.publishedNow.get()}sessionState;constructor(e,t,n=``,r,i=null){this.runs=e,this.store=t,this.defaultEmptyValue=n,this.parent=i,this.sessionState=r}view(t){return new e(t,new jw(this.store.clock,this.store),this.defaultEmptyValue,this.sessionState,this)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,pw(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,L(t,`parse`))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>_M(e,this.inputs.get().read(e)))}own(e){this.cleanups.push(e)}declareInput(e,t,n,r,i){this.store.defineDerived(e,n,i,()=>this.inputAt(e,t,n,r))}inputAt(e,t,n,r){let i=this.inputs.get().read(t);if(i.kind===`pending`)throw this.lastErrors.delete(e),new _w(e,`variable "${e}" has no value yet: its source has not answered`);if(i.kind===`undeclared`){let t=new gM(e,i.fact);throw this.recordError(e,t.message),t}let a=i.value;if(a===void 0)return this.fallbackOf(e,n,r,`input path "${t}" not found in payload`);try{let t=vM(a,n);return this.lastErrors.delete(e),t}catch(t){return this.fallbackOf(e,n,r,t instanceof Error?t.message:String(t))}}declareShell(e,t,n){this.declareSource(e,{kind:`shell`,command:t,cwd:n.cwd},cM(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,{kind:`file`,path:t,readMode:n.readMode??`whole`},n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r);(0,X.runInAction)(()=>this.sourceNames.push(e)),this.cleanups.push((0,X.reaction)(()=>this.lanes.get(e)?.current(),e=>{e===void 0||e.kind===`pending`||i(e)},{fireImmediately:!0})),this.registerCachePolicy(e,n,n=>this.hold(e,{read:t,parse:dM(r),refresh:n}))}hold(e,t){(0,X.runInAction)(()=>{this.identities.set(e,t);let{result:n}=this.holds.declare(()=>[...this.identities].map(([e,t])=>{let n=this.runs.declare(this.holds,t),r=this.lanes.get(e);return[e,r?.digest===n.digest?r:n]}));for(let[e,t]of n)this.lanes.set(e,t)})}publisherFor(e,t){switch(t.kind){case`text`:case`regex`:return this.scalarPublisher(e,t.default);case`json`:return this.documentPublisher(e,t.default)}}scalarPublisher(e,t){let n=this.stringInitial(t);return this.store.defineBox(e,`string`,n),t=>{this.noteOutcome(e,t),this.store.setBox(e,bo(t,n))}}documentPublisher(e,t){let n=t===void 0?So(`unread`):F(t);this.store.defineDocument(e,n);let r,i=!1;return this.cleanups.push(()=>r?.()),a=>{r?.();let o=a;this.noteOutcome(e,o);let s=o.kind===`ok`||o.kind===`failed`&&o.failedAt===`parse`,c=s||t===void 0?o:n,l=i&&s&&o.kind!==`ok`,u=()=>{i=o.kind===`ok`,this.store.setDocument(e,c)};l?r=this.store.clock.after(250,u):u()}}async inFlight(e){for(;!e.aborted&&this.awaited().length>0;)try{await(0,X.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}return this.awaited()}awaited(){return[...[...this.lanes].filter(([,e])=>e.current().kind===`pending`).map(([e])=>e),...this.parent?.awaited()??[]]}settled(e){return this.inFlight(tt(this.store.clock,e))}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(nj(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){let n=this.engine.parse(`{{ date .layout now }}`),r={layout:t.format};this.declareDerived(e,`string`,`projection`,()=>n.evaluate(r).map(e=>e.plain).join(``),t.varDefault)}declareDerived(e,t,n,r,i){this.store.defineDerived(e,t,n,()=>{try{let n=vM(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=vw(t);if(n!==void 0)throw this.lastErrors.delete(e),n;let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),i===void 0)throw Error(`variable "${e}": ${r}`);return i}})}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(uM);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}stateRevision(){let e=this.store.has(`session.id`)?this.store.read(uM):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}bindInputs(e){(0,X.runInAction)(()=>this.inputs.set(e))}getLastError(e){if(!this.declaredHere(e))return this.parent?.getLastError(e);let t=this.lastErrors.get(e),n=this.policyFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){return new Map([...this.parent?.cachePolicyFaults()??[],...this.policyFaults])}declaredHere(e){return this.store.has(e)&&!(this.parent?.store.has(e)??!1)}dispose(){for(let e of this.cleanups)e();return this.cleanups.length=0,this.holds.close(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:n({kind:`never`});break;case`ttl`:n({kind:`ttl`,durationMs:t.durationMs});break;case`watch_file`:n({kind:`watch_file`,path:t.path}),this.cleanups.push((0,X.reaction)(()=>this.lanes.get(e)?.fault()??null,t=>this.notePolicy(e,t===null?F(void 0):L(t,`read`)),{fireImmediately:!0}));break;case`key`:{let r=this.engine.parse(t.template);this.onReads(e,()=>{try{return F(r.evaluate(nj(this.store)).map(e=>e.plain).join(``))}catch(e){return vw(e)===void 0?L(`cache key: ${e instanceof Error?e.message:String(e)}`,`read`):So(`unread`)}},e=>n({kind:`key`,hash:Xj(e)}));break}case`depends_on`:this.onReads(e,()=>{let e=t.varNames.map(e=>this.store.changeKey(e));return e.every(e=>e.kind===`ok`)?F(e.map(e=>e.value).join(`,`)):So(`unread`)},e=>n({kind:`key`,hash:Xj(e)}));break}}onReads(e,t,n){let r,i=(0,X.reaction)(t,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===r)&&(r=t.value,n(t.value))},{fireImmediately:!0});this.cleanups.push(i)}fallbackOf(e,t,n,r){if(this.recordError(e,r),n!==void 0)return n;try{return vM(this.defaultEmptyValue,t)}catch{return yM(t)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:this.store.clock.now(),message:t})}notePolicy(e,t){(0,X.runInAction)(()=>{t.kind===`failed`?this.policyFaults.get(e)?.message!==t.reason&&this.policyFaults.set(e,{timestamp:this.store.clock.now(),message:t.reason}):this.policyFaults.delete(e)})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function xM(e,t){let n=ux[e],r=_x(e),i=n.kind===`session`||n.kind===`config`?n.floor:``;return r===`string`?{kind:`input`,path:t,default:``}:{kind:`input`,path:t,type:r,default:i}}const SM=Object.fromEntries([...Tx].map(([e,t])=>[t,xM(e,t)])),CM={subscribers:`number`,fps:`number`,shown:`boolean`},wM=Object.keys(CM),TM={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[uM]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`,default:``},config_path:{kind:`input`,path:`configPath`,default:``},...SM,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(Qc.flatMap(e=>wM.map(t=>[rl(e,t),{kind:`input`,path:rl(e,t),type:CM[t],default:nl[t]}]))),[tl(`by`)]:{kind:`input`,path:tl(`by`),default:el.by},[tl(`fps`)]:{kind:`input`,path:tl(`fps`),type:`number`,default:0},...Object.fromEntries([`label`,`fg`,`bg`,`open`].map(e=>[`diagnostics.${e}`,{kind:`input`,path:`diagnostics.${e}`,default:``}])),"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"tmux.pane":{kind:`input`,path:`tmux.pane`,default:``},"autocompact.window":{kind:`input`,path:`autocompact.window`,type:`number`,default:-1},...Object.fromEntries([`applied`,`lower`,`higher`].map(e=>[`autocompact.${e}`,{kind:`input`,path:`autocompact.${e}`,type:`number`,default:0}])),"autocompact.error":{kind:`input`,path:`autocompact.error`,default:``},"location.main":{kind:`input`,path:`location.main`,default:``},"location.worktree":{kind:`input`,path:`location.worktree`,default:``},"location.subpath":{kind:`input`,path:`location.subpath`,default:``},"location.noRepo":{kind:`input`,path:`location.noRepo`,type:`boolean`,default:!1},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},EM={today:`the day the draw is at`,feeds:`the frames a lane was sent up to the draw's instant`,drawing:`who the draw is for`,diagnostics:`the errors and warnings the draw owes its reader`};function DM(e){let t=e.split(`.`,1)[0];return Object.hasOwn(EM,t)?t:void 0}const OM=Object.fromEntries(xy.map(e=>[e,Tx.get(e)]));function kM(e){return xy.find(t=>OM[t]===e)}function AM(e,t,n){let r=new Set,i=(e,t=n)=>{for(let n of HC(e??``,t).keys())r.add(n)};for(let t of Object.values(e.segments)){let e=t.partials===void 0?n:{...n,...t.partials};i(t.template,e),i(t.bg,e),i(t.fg,e),i(t.when,e);for(let n of Object.values(t.partials??{}))i(n,e)}for(let e of t)for(let t of ob(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(uM);for(let t of Object.values(e.actions)){r.add(uM);for(let[,e]of vS(t))i(e);let e=`set`in t?Ex.get(t.set):void 0,n=`persist`in t?Tx.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function jM(e,t,n){let r=sw({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of AM(e,t,n.helpers)){if(ow(a,r))continue;let e=TM[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function MM(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function NM(e){return e}function PM(e,t,n){return n===void 0?SS+MM(e)+`.`+MM(t):FM(n)}function FM(e){return SS+MM(e)}function IM(e,t){return e+`.`+t}function LM(e){return CS+e}const RM=[`closeOnPick`,`paged`,`key`,`distribution`],zM=e=>RM.includes(e),BM=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${wv.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function VM(e){for(let t of Object.keys(e))if(!zM(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${BM}`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);let r=e.distribution;if(r!==void 0&&!Tv(r))throw Error(`{{ menu }} option "distribution" must be one of: ${wv.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Dv(r)}}const HM=e=>`from`in e?e.from:e.themes;function UM(e,t,n){return e===`bool`?Yy(t)!==null:`min`in e?Xy(t,e)!==null:pS(HM(e),n).members.includes(t)}function WM(e,t){let n=e.map(e=>JSON.stringify(e));if(e.length<=8)return`one of ${n.join(`, `)}`;let r=t===void 0?``:` "${t}"`;return`one of the ${e.length}${r} names, such as ${n.slice(0,3).join(`, `)}`}function GM(e,t){if(e===`bool`)return qy.join(` or `);if(!(`min`in e)){let n=HM(e),{members:r}=pS(n,t);return WM(r,typeof n==`string`?n:void 0)}return`an integer from ${e.min} to ${e.max}`}function KM(e){return{label:e.label,domain:qM(e.domain)}}function qM(e){return e===`theme`?{themes:dS}:e===`bool`||`min`in e?e:{from:e}}function JM(e,t,n,r,i){let a=ya(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...qy]}},variables:{}};if(`from`in o)return YM(t,r,i,o.from,e=>({template:`{{ carousel "${e.apply}" "${e.open}" "${a}" }}`,rows:[`{{ picker "${e.apply}" "${e.page}" false true true }}`]}));if(`themes`in o)return YM(t,r,i,o.themes,e=>({template:`{{ action "${e.open}" "${a}" .${n} }} {{ action "${e.open}" (swatch "${e.apply}") }}`,rows:[`{{ swatches "${e.apply}" "${e.page}" }}`,`{{ themePreview "${e.apply}" }}`]}));let s=e=>({set:t,min:o.min,max:o.max,by:e});return{kind:`inline`,template:`{{ action "${r}.down" "◀" }} {{ "${a}" }} {{ .${n} }} {{ action "${r}.up" "▶" }}`,actions:{[`${r}.down`]:s(-o.step),[`${r}.up`]:s(o.step)},variables:{}}}function YM(e,t,n,r,i){let a={variable:n,key:n,member:t},o=IM(n,t),s=`${t}.open`,c=LM(n),l=`${c}.current`,{template:u,rows:d}=i({apply:t,open:s,page:c});return{kind:`picker`,template:u,actions:{[t]:{set:e,from:r},[o]:Da(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:Ea(n,ma),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const XM=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],ZM=Object.fromEntries(XM.map(e=>[e.member,e.label])),QM={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},$M=Object.keys(QM),eN=Dx(e=>bx[e].place),tN=e=>Object.hasOwn(QM,e),nN=(e,t)=>e===t||tN(e)&&nN(eN[QM[e].beside],t),rN=e=>tN(e)?`${rN(eN[QM[e].beside])} › ${QM[e].trigger}`:e===`door`?`first line`:ZM[e],iN=e=>rN(eN[e]),aN=()=>[`door`,...XM.map(e=>e.member)].flatMap(e=>[e,...$M.filter(t=>nN(t,e))]).map(e=>({path:rN(e),names:xx.filter(t=>eN[t]===e)})).filter(({names:e})=>e.length>0),oN=e=>{let{setting:t,on:n,inTmux:r}=Zc[e].switch;return`${Zc[e].label} is off — turn it on in the settings menu's ${iN(t)}, or set globals.${t}: ${JSON.stringify(n)}${r?`; it runs only for a session inside a tmux pane`:``}`},sN=Object.fromEntries(Object.entries(ux).map(([e,t])=>[e,t.spec]));function cN(e){return lN(ux[e])}function lN(e){return`optionDomain`in e&&e.optionDomain!==void 0?{from:e.optionDomain.name}:e.domain}function uN(e,t){return{required:!1,json:{not:{},description:`not allowed here — ${e}`},parse:(e,n,r,i)=>{i[r]!==void 0&&e.issues.push({path:`${n}.${r}`,message:t(`${n}.${r}`),line:J(e.source,[...n.split(`.`),r])})}}}function dN(e){return uN(`${e} cannot select a preset`,t=>`${t}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`)}function fN(e){return uN(`${e} cannot change the settings menu glyph`,t=>`${t}: ${e} cannot change the settings menu glyph — one menu is shared by every preset. Set it in the top-level globals.menuGlyph instead.`)}function pN(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Sy(s)){r.issues.push({path:`${i}.${a}`,message:`${i}.${a}: a rule is not allowed here — ${t} ${n}, so it names a value. Write the rule in globals.${a} (or a preset's globals.${a}) instead.`,line:J(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const mN={default_bg:"nothing reads it — a segment with no `bg:` wears the decoration tint of its place in the bar. Delete the key, and author `bg:` on the segments that need a fixed colour.",default_fg:"nothing reads it — a segment with no `fg:` wears text chosen for contrast against its background. Delete the key, and author `fg:` on the segments that need a fixed colour.",default_truncate_marker:'nothing reads it — a segment clipped to its `width:` always ends in "…". Delete the key.',look:`it was renamed "style" — write the same name as style: "<name>"`,progression:`it was renamed "variation", and its values with it: accent (was secondary-accent), duo (was primary-secondary), mono (was primary)`,experimentalTmuxStatus:`it became the renderer setting — write renderer: "tmux" (or pick tmux in ${iN(`renderer`)} › renderer, from a session inside tmux)`,charset:"the bar always draws Nerd Font glyphs. Delete the key; `cc-candybar doctor` names what your terminal's font is missing."},hN={noun:`globals key`,fields:sN,removed:mN},gN={preset:dN(`a preset`),menuGlyph:fN(`a preset`)},_N={noun:`preset globals key`,fields:{...sN,...gN},removed:mN};function vN(e){return ON(e)&&!(e in gN)}const yN=`is decided later than any rule could be settled`,bN={noun:`editGlobals key`,removed:mN,fields:{...sN,preset:dN(`the editGlobals fragment`),menuGlyph:fN(`the editGlobals fragment`),palette:pN(sN.palette,`the editGlobals fragment`,yN),style:pN(sN.style,`the editGlobals fragment`,yN),effect:pN(sN.effect,`the editGlobals fragment`,yN)}},xN={noun:`theme default key`,fields:{...Object.fromEntries(px.map(e=>[e,sN[e]])),style:pN(sN.style,`a theme's default`,`is the look that theme wears by name`)}};function SN(e,t){if(!Zy(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${Ib(t)}`,line:J(e.source,[`themeDefaults`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=`themeDefaults.${r}`;if(!e.allowedPalettes.has(r)){e.issues.push({path:t,message:`${t}: "${r}" is not an installed theme${py(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[`themeDefaults`,r])});continue}let a=Lb(e,xN,t,i);a!==null&&(n[r]=a)}return n}function CN(e,t,n){return n===void 0?{}:Lb(e,hN,t,n)??{}}function wN(e,t,n){return Lb(e,_N,t,n)??{}}function TN(){return ote(_N)}function EN(e,t,n){return Lb(e,bN,t,n)??{}}const DN=new Set(Object.keys(sN));function ON(e){return DN.has(e)}function kN(e){return Object.hasOwn(mN,e)?mN[e]:void 0}function AN(){return[...DN]}const jN=new Map(Object.entries(ux).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function MN(e){let t=new Map;for(let[n,r]of jN){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const NN=/^segments\.([^.]+)\.palette$/,PN=/^presets\.(.+)\.root$/,FN=/^presets\.(.+)\.globals\.([^.]+)$/,IN=/^themeDefaults\.(.+)\.([^.]+)$/;function LN(e){return`presets.${e}.root`}function RN(e,t){return`themeDefaults.${e}.${t}`}const zN=e=>px.includes(e);function BN(e,t){return`presets.${e}.globals.${t}`}function VN(e){if(ON(e))return{scope:`globals`,field:e};let t=NN.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=FN.exec(e);if(n&&vN(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=IN.exec(e);if(r&&zN(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=PN.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function HN(e){switch(e.scope){case`globals`:return[`globals`,e.field];case`preset-globals`:return[`presets`,e.preset,`globals`,e.field];case`segment-palette`:return[`segments`,e.segment,`palette`];case`theme-default`:return[`themeDefaults`,e.theme,e.field]}}const UN=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],WN=[...UN,`other`],GN={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},KN=rE({fromString:e=>e});function qN(e){let t=MM(e);return ES.find(e=>t.startsWith(MM(e)))}function JN(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:J(e.source,[`root`])})}function YN(e,t,n){for(let r of[`variables`,`actions`,`helpers`,`segments`])for(let i of Object.keys(t[r]??{})){let t=TC(i);t!==void 0&&(r!==`variables`&&i===t||r===`segments`&&n.has(i)||e.issues.push({path:`${r}.${i}`,message:`"${i}" is in "${t}", the namespace plugins own (each declares its names there from its own definition) — rename it`,line:J(e.source,[r,i])}))}for(let[r,i]of Object.entries(t.segments??{}))for(let t of Object.keys(i.vars??{})){let i=`${r}.${t}`,a=TC(i);a===void 0||n.has(r)||e.issues.push({path:`segments.${r}.vars.${t}`,message:`segment "${r}"'s var "${t}" is named "${i}", in "${a}", the namespace plugins own — rename the var or the segment`,line:J(e.source,[`segments`,r,`vars`,t])})}}const XN=`edit.mode`,ZN=`edit.configure`,QN=`edit.toggle`,$N=`arrange`,eP=`${wS}draft.`;function tP(e,t){return`${e}:${t}`}const nP={variable:XN,key:XN,member:$N},rP=xa(nP);function iP(e){try{return KN.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function aP(e){if(Object.values(e.actions??{}).some(e=>`do`in e&&e.do.includes(`edit.toggle`)))return!0;for(let t of Object.values(e.segments??{})){let e=[t.template,t.bg,t.fg,...Object.values(t.partials??{})];for(let t of e)if(typeof t==`string`&&iP(t))return!0}return!1}function oP(e,t){if(JN(e,t,wS,`edit mode`),!aP(t))return;let{variables:n,actions:r}=sP();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function sP(){return{variables:{[XN]:{...Ea(XN,ma),within:[AS]},[ZN]:{...Ea(ZN,ma),within:[nP]}},actions:{[QN]:Da(XN,$N),"edit.unconfigure":{set:ZN,to:ma}}}}function cP(e,t,n,r){let i={variable:e,key:e,member:ha};return r.variables[e]={...Ea(e,ma),...n.length>0&&{within:n}},r.actions[e]=Da(e,ha),r.segments[e]={template:Ca(e,`(?)`,`✕`),...lP(n)},ba(e,i,{kind:`container`,direction:`horizontal`,children:t.map((t,n)=>{let i=`${e}.${n}`;return r.segments[i]={template:t},{kind:`segment`,name:i}})},`drop`)}function lP(e){let[t,...n]=e;return t===void 0?{}:{when:xa(t,...n)}}const uP=`none`;function dP(e){return ed(e,`background`)}var fP=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function pP(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=mP(n,i),l=c!==uP,u=l?c===void 0?o:hP(a,c,`bg`):dP(a);e.bg=u;let d=mP(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:Uv(a,e,t))(u):void 0:hP(a,d,`fg`);return new W({...l&&{bgcolor:U.fromRgba(u)},...f!==void 0&&{color:U.fromRgba(f)}})}function mP(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function hP(e,t,n){try{return ed(e,t)}catch(e){throw e instanceof $u?new fP(t,n,e.message):e}}const gP=`🔧`,_P={help:[`-h`,`--help`],version:[`-V`,`--version`]},vP=[...new Set(Object.values(Zc).map(e=>iN(e.switch.setting)))].join(` or `),yP=Math.max(...Object.values(bx).map(e=>e.configKey.length))+2,bP=[`✚ inserts`,`✖ removes`,`${gP} configures`,`↺ resets layout`],xP={band:[`animates the bar in the band above the prompt, through a Claude Code mod`,`on: installs the candybar-band mod from this checkout and types /reload-plugins`],statusline:[`animates the statusline itself, through the attach launcher shipped with cc-candybar`,`on: exits this Claude Code and starts it again under that launcher, on this session`,`or start one yourself: cc-candybar --help prints the line to type`],pane:[`animates the bar in a tmux pane under this session's`,`on: opens that pane · off: closes it`],tmuxStatus:[`draws the bar in the tmux status line, while this session's pane is the one it shows`,`tmux: the daemon draws it there · claude: puts the status line back as it was`]},SP=`
71
71
  cc-candybar - Beautiful powerline statusline for Claude Code
72
72
 
73
73
  Usage: cc-candybar [options]
@@ -102,7 +102,7 @@ Configuration:
102
102
  A change applies to this session at once.
103
103
  Where each setting is in the menu: the globals field that sets it in a
104
104
  config file, then the control's label.
105
- ${aN().flatMap(({path:e,names:t})=>[` ${e}`,...t.map(e=>` ${xx[e].configKey.padEnd(yP)}${xx[e].label}`)]).join(`
105
+ ${aN().flatMap(({path:e,names:t})=>[` ${e}`,...t.map(e=>` ${bx[e].configKey.padEnd(yP)}${bx[e].label}`)]).join(`
106
106
  `)}
107
107
  The 🧰 tools tab holds 🩺 doctor: click it to check your setup, and click a
108
108
  failed row's [fix] to repair it (the same checks \`cc-candybar doctor\` runs).
@@ -187,27 +187,27 @@ Config tooling:
187
187
  config [--json] The effective merged config. (All three query the
188
188
  running daemon; none spawn one.)
189
189
 
190
- `,CP=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`;function wP(e,t){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?t+e.slice(1):e}function TP(e,t,n){return s.resolve(e,wP(t,n))}function EP(e,t,n){return typeof t==`string`&&t!==``?TP(e,t,n):void 0}const DP=`CC_CANDYBAR_CONFIG`;function OP({env:e,home:t},n){return EP(n,e[DP],t)}function kP(e,t){return e===void 0?t===void 0?{source:`search`}:{source:`environment`,path:t}:{source:`argument`,path:e}}function AP(e,t,n){return kP(EP(n,e,t.home),OP(t,n))}function jP(e,t=`bundled default (no config file loaded)`){return e.join(` < `)||t}const MP=[`approved`,`declined`];function NP(e){return e.link.kind===`linked`?e.link.main:e.dir}const PP=(e,t)=>Object.hasOwn(e,t)?e[t]:null;function FP(e,t){let n=NP(t);if(e.kind===`failed`)return{standing:`unread`,under:n};let r=PP(e.value,n),i=PP(e.value,t.dir);return r===null?i===null?{standing:`awaiting`,under:n}:{standing:i,under:t.dir}:{standing:i===null||i===r?r:`awaiting`,under:n}}function IP(e,t,n){let r=[...new Map([...t,...n?.ships?[n]:[]].map(e=>[e.dir,e])).values()],i=r.map(t=>({dir:t.dir,...FP(e,t)})),a=e=>i.filter(t=>t.standing===e),o=e=>[...new Set(a(e).map(e=>e.under))];return{plugins:n!==null&&FP(e,n).standing===`approved`?n.path:null,approved:a(`approved`).map(e=>e.dir),awaiting:o(`awaiting`),declined:o(`declined`),unproven:r.flatMap(e=>e.link.kind===`unproven`?[{dir:e.dir,reason:e.link.reason}]:[]),unread:e.kind===`failed`?e.reason:null}}function LP(e,t,n,r){if(e[t]===n&&r.length===0)return e;let i=Object.entries(e).filter(([e])=>!r.includes(e));return{...Object.fromEntries(i),[t]:n}}function RP(e){if(typeof e!=`object`||!e||Array.isArray(e))return{kind:`failed`,reason:`is not an object`};for(let[t,n]of Object.entries(e))if(!MP.includes(n))return{kind:`failed`,reason:`answers ${JSON.stringify(t)} ${JSON.stringify(n)}, not ${MP.join(` or `)}`};return{kind:`ok`,value:e}}function zP(e){return e.unread===null?null:`Repository config answers could not be read: ${e.unread} — no repository's config runs until they can be`}function BP(e){let t=zP(e);return[...t===null?[]:[t],...VP(e),...HP(e)]}function VP(e){return e.awaiting.map(e=>`awaiting approval: ${e} — its cc-candybar config runs once it is approved in the bar`)}function HP(e){return[...e.declined.map(e=>`declined: ${e} — its cc-candybar config does not run`),...e.unproven.map(e=>`not proven a worktree: ${e.dir} — it answers for itself, because ${e.reason}`)]}const UP=new Xf({"strip.separator":`default`,"strip.rail":`default`});function WP(e){return UP.resolve(e)}const GP={kind:`still`},gne=e=>Up.at(e.timeline,e.wall),KP=Symbol(`bar`);function _ne(e){return e.name!==Oy}function vne(e){return t=>K.map(K.all(e.map(({timeline:e,effect:n})=>Up.run(e,n(t)))),e=>(t,n)=>e.reduce((e,t)=>t(e,n),t))}const qP=Dee;function yne(e,t){let n=new Eu(t,qP.foregroundColor,qP.ansiColors,qP.palette);return t=>e({...t,theme:n})}function bne(e,t){return n=>Vh(()=>e(n),...t)(n)}function JP(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t/4294967296}const YP=4096;function xne(e,t,n){let r=(n,{terminal:r})=>({...n,bg:r.bg?n.bg:e,fg:r.fg?n.fg:r.bg?e:t}),i=e=>e,a=ex.reduceRight((e,{lit:t,seconds:n})=>K.sequence(K.constant(t?r:i),n,e),K.constant(i)),o=K.sequence(K.constant(i),n,a);return()=>o}var XP=class{inForce=null;anchor=Up.play(0);placements=new Map;made=new Map;passages=null;frame={effect:Oy,t:0,speed:1,made:0,reused:0,own:[],basis:`off`,revision:0,fades:[],leaves:[]};constructor(e){this.key=e}lastFrame(){return this.frame}get heldCount(){let e=this.passages?.size??0;return[...this.made.values()].reduce((e,t)=>e+t.size,e)}clockAt(e,t){return{wall:e,timeline:Up.withRate(this.anchor,e,t)}}motion(e,t,n,r=null){let i=gne(t),a=e=>Up.seek(t.timeline,t.wall,e),o=this.inForce?.name===e?this.inForce:{name:e,since:i},s={scope:KP,name:e,t:i-o.since},c=this.placements,l=new Map,u=this.made,d=new Map,f=[],{last:p}=n,m=this.passages,h=n.transitions?m!==null&&p!==null?`compared`:`fresh`:`off`,g=h===`compared`?e=>{let t=p.placements.get(e);return t?.kind===`drew`?{drawing:t.drawing,passage:m.get(e)??null}:void 0}:null,_=new Set,v=new Map,y=[],b=[],x={effect:e,t:s.t,speed:t.timeline.rate,made:0,reused:0,own:f,basis:h,revision:n.source.revision,fades:y,leaves:b},S=(e,t,{ground:n})=>{let r=o_.transitions[e]({z:JP(`${this.key}@${t}`)*YP});return{name:e,since:i,done:e=>r.done(e),effect:yne(r.effect,n)}},C=({since:e,done:t})=>t(i-e),w=(e,t,n)=>({drawing:t,passage:g===null?null:n===void 0||n.passage?.name===`dissolve`?S(`fade`,e,t):n.passage!==null&&!C(n.passage)?n.passage:null}),T=(e,t)=>{if(t===void 0||t.drawing.opened||t.drawing.own.length===0)return;if(t.passage?.name===`dissolve`)return C(t.passage)?void 0:t;let r={...t.drawing,own:t.drawing.own.map(n.hold)};return{drawing:r,passage:S(`dissolve`,e,r)}},E=(e,t)=>{if(_.has(e))throw Error(`placement "${e}" was reached twice in one frame`);_.add(e);let r=g?.(e),{drawing:a,deeper:o}=n.returned(e,t),s=a===null?T(e,r):w(e,a,r);return s===void 0?t:(s.passage!==null&&(v.set(e,s.passage),(s.passage.name===`fade`?y:b).push({placement:e,t:i-s.passage.since})),a===null?[...s.drawing.own,...o]:t)},ee=(e,t)=>{let n=l.get(e)??c.get(e),r=n?.name===t?n:{name:t,since:i},a=i-r.since;return l.has(e)||(l.set(e,r),f.push({placement:e,effect:t,t:a})),{scope:e,name:t,t:a}},D=(e,t)=>{let n=d.get(e)??new Map;d.set(e,n);let r=n.get(t.scope);if(r!==void 0)return r.effect;let i=u.get(e)?.get(t.scope),a=i?.name===t.name,o=JP(t.scope===KP?e:`${e}@${t.scope}`),s=a?i.effect:o_.loops[t.name]({z:o*YP});return x[a?`reused`:`made`]++,n.set(t.scope,{name:t.name,effect:s}),s},te=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?s:ee(r.id,r.effect),i=t.get(e.scope);i===void 0?t.set(e.scope,{...e,owners:[n]}):i.owners.push(n)}return[...t.values()]},O=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=t.get(r.id);e===void 0?t.set(r.id,[n]):e.push(n)}return[...t].flatMap(([e,t])=>{let n=v.get(e)??null;return n===null?[]:[{timeline:a(i-n.since),effect:Vh(n.effect,...t)}]})},k=r===null?[]:[{timeline:Up.play(r.idleSince),effect:xne(r.fill,r.text,dte(r.timeoutS))}],ne=e=>e===`menu`?k:[];return{placed:h===`off`?(e,t)=>t:E,row:(e,n,r)=>{let i=(r.some(e=>e.placement.effect!==`bar`)?te(r):[{...s,owners:void 0}]).filter(_ne),o=O(r),c=ne(n);if(i.length===0&&o.length===0&&c.length===0)return GP;let l=`${this.key}#${e}`;return{kind:`moving`,time:t.wall,wrap:e=>new jh(e,vne([...i.map(e=>{let t=D(l,e);return{timeline:a(e.t),effect:e.owners===void 0?t:bne(t,e.owners)}}),...o,...c]),{key:l,theme:qP})}},drawn:()=>{this.anchor=t.timeline,this.inForce=o,this.placements=l,this.made=d,this.passages=h===`off`?null:v,this.frame=x}}}},Sne=class{sessions=new Map;constructor(e=256){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new XP(e);this.sessions.delete(e),this.sessions.set(e,t);for(let e of this.sessions.keys()){if(this.sessions.size<=this.maxSessions)break;this.sessions.delete(e)}return t}getStats(){let e=0;for(let t of this.sessions.values())e+=t.heldCount;return{sessions:this.sessions.size,effects:e}}};const ZP={fg:`#ffffff`,bg:`#c82828`},QP={fg:`#000000`,bg:`#dca028`};function $P(e,t){return`\x1b[${e};2;${[1,3,5].map(e=>Number.parseInt(t.slice(e,e+2),16)).join(`;`)}m`}const Cne=$P(38,ZP.fg),wne=$P(48,ZP.bg),Tne=[[0,31],[127,159],[8234,8238],[8294,8303]];function Ene(e){return Tne.some(([t,n])=>e>=t&&e<=n)}function eF(e){let t=``;for(let n of e)t+=Ene(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function tF(e,t){let n=eF(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const Dne=`${wne}${Cne}`;function nF(e){return`⚠ cc-candybar: ${kne(e)}`}function One(e){return`${Dne}${nF(e)}\n`}function kne(e){switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:return`daemon rejected request: ${tF(e.message,60)}`;case`render_failed`:return`render failed: ${tF(e.message,60)}`;case`switched_off`:return`switched off: ${tF(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${tF(e.message,60)}`}}function rF(e,t){return{depth:e.depth,rows:t,nextChange:1/0,motion:e.motion===`still`?`still`:`can-move`,pending:[]}}function iF(e,t){return{depth:`truecolor`,rows:[{kind:`diagnostic`,runs:[{text:eF(e),...t}]}],nextChange:1/0,motion:`still`,pending:[]}}function Ane(e){return iF(nF({kind:`permanent`,cause:`render_failed`,message:e}),ZP)}function aF(e,t){try{return e(t)}catch(t){return e(iF(`⚠ cc-candybar ${t instanceof Error?t.message:String(t)}`,ZP))}}function oF(e){return e.type===H.TRUECOLOR?e.value.hex:e.number===void 0?e.name:`color(${e.number})`}const jne=Object.keys(new W().attributes);function Mne(e,t){let{color:n,bgcolor:r}=e.drawnColors(t),i=jne.filter(t=>e[t]===!0);return{...n!==void 0&&{fg:oF(n)},...r!==void 0&&{bg:oF(r)},...i.length>0&&{attrs:i}}}function Nne({text:e,style:t},n){return{text:e,...t!==void 0&&n!==null&&Mne(t,n),...t?.link!==void 0&&{link:t.link}}}function Pne(e,t){let n=e.filter(e=>!e.isControl&&e.text.length>0);return G.splitLines(n).map(e=>e.map(e=>Nne(e,t)))}function Fne({text:e,fg:t,bg:n,attrs:r=[],link:i}){return new G(e,new W({color:t,bgcolor:n,link:i,...Object.fromEntries(r.map(e=>[e,!0]))}))}function sF(e,t){let n=ru(t);return e.map(e=>Dh(e.map(Fne),n)).join(`
190
+ `,CP=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`;function wP(e,t){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?t+e.slice(1):e}function TP(e,t,n){return s.resolve(e,wP(t,n))}function EP(e,t,n){return typeof t==`string`&&t!==``?TP(e,t,n):void 0}const DP=`CC_CANDYBAR_CONFIG`;function OP({env:e,home:t},n){return EP(n,e[DP],t)}function kP(e,t){return e===void 0?t===void 0?{source:`search`}:{source:`environment`,path:t}:{source:`argument`,path:e}}function AP(e,t,n){return kP(EP(n,e,t.home),OP(t,n))}function jP(e,t=`bundled default (no config file loaded)`){return e.join(` < `)||t}const MP=[`approved`,`declined`];function NP(e){return e.link.kind===`linked`?e.link.main:e.dir}const PP=(e,t)=>Object.hasOwn(e,t)?e[t]:null;function FP(e,t){let n=NP(t);if(e.kind===`failed`)return{standing:`unread`,under:n};let r=PP(e.value,n),i=PP(e.value,t.dir);return r===null?i===null?{standing:`awaiting`,under:n}:{standing:i,under:t.dir}:{standing:i===null||i===r?r:`awaiting`,under:n}}function IP(e,t,n){let r=[...new Map([...t,...n?.ships?[n]:[]].map(e=>[e.dir,e])).values()],i=r.map(t=>({dir:t.dir,...FP(e,t)})),a=e=>i.filter(t=>t.standing===e),o=e=>[...new Set(a(e).map(e=>e.under))];return{plugins:n!==null&&FP(e,n).standing===`approved`?n.path:null,approved:a(`approved`).map(e=>e.dir),awaiting:o(`awaiting`),declined:o(`declined`),unproven:r.flatMap(e=>e.link.kind===`unproven`?[{dir:e.dir,reason:e.link.reason}]:[]),unread:e.kind===`failed`?e.reason:null}}function LP(e,t,n,r){if(e[t]===n&&r.length===0)return e;let i=Object.entries(e).filter(([e])=>!r.includes(e));return{...Object.fromEntries(i),[t]:n}}function RP(e){if(typeof e!=`object`||!e||Array.isArray(e))return{kind:`failed`,reason:`is not an object`};for(let[t,n]of Object.entries(e))if(!MP.includes(n))return{kind:`failed`,reason:`answers ${JSON.stringify(t)} ${JSON.stringify(n)}, not ${MP.join(` or `)}`};return{kind:`ok`,value:e}}function zP(e){return e.unread===null?null:`Repository config answers could not be read: ${e.unread} — no repository's config runs until they can be`}function BP(e){let t=zP(e);return[...t===null?[]:[t],...VP(e),...HP(e)]}function VP(e){return e.awaiting.map(e=>`awaiting approval: ${e} — its cc-candybar config runs once it is approved in the bar`)}function HP(e){return[...e.declined.map(e=>`declined: ${e} — its cc-candybar config does not run`),...e.unproven.map(e=>`not proven a worktree: ${e.dir} — it answers for itself, because ${e.reason}`)]}const UP=new Xf({"strip.separator":`default`,"strip.rail":`default`});function WP(e){return UP.resolve(e)}const GP={kind:`still`},gne=e=>Up.at(e.timeline,e.wall),KP=Symbol(`bar`);function _ne(e){return e.name!==Oy}function vne(e){return t=>K.map(K.all(e.map(({timeline:e,effect:n})=>Up.run(e,n(t)))),e=>(t,n)=>e.reduce((e,t)=>t(e,n),t))}const qP=Dee;function yne(e,t){let n=new Eu(t,qP.foregroundColor,qP.ansiColors,qP.palette);return t=>e({...t,theme:n})}function bne(e,t){return n=>Vh(()=>e(n),...t)(n)}function JP(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t/4294967296}const YP=4096;function xne(e,t,n){let r=(n,{terminal:r})=>({...n,bg:r.bg?n.bg:e,fg:r.fg?n.fg:r.bg?e:t}),i=e=>e,a=$b.reduceRight((e,{lit:t,seconds:n})=>K.sequence(K.constant(t?r:i),n,e),K.constant(i)),o=K.sequence(K.constant(i),n,a);return()=>o}var XP=class{inForce=null;anchor=Up.play(0);placements=new Map;made=new Map;passages=null;frame={effect:Oy,t:0,speed:1,made:0,reused:0,own:[],basis:`off`,revision:0,fades:[],leaves:[]};constructor(e){this.key=e}lastFrame(){return this.frame}get heldCount(){let e=this.passages?.size??0;return[...this.made.values()].reduce((e,t)=>e+t.size,e)}clockAt(e,t){return{wall:e,timeline:Up.withRate(this.anchor,e,t)}}motion(e,t,n,r=null){let i=gne(t),a=e=>Up.seek(t.timeline,t.wall,e),o=this.inForce?.name===e?this.inForce:{name:e,since:i},s={scope:KP,name:e,t:i-o.since},c=this.placements,l=new Map,u=this.made,d=new Map,f=[],{last:p}=n,m=this.passages,h=n.transitions?m!==null&&p!==null?`compared`:`fresh`:`off`,g=h===`compared`?e=>{let t=p.placements.get(e);return t?.kind===`drew`?{drawing:t.drawing,passage:m.get(e)??null}:void 0}:null,_=new Set,v=new Map,y=[],b=[],x={effect:e,t:s.t,speed:t.timeline.rate,made:0,reused:0,own:f,basis:h,revision:n.source.revision,fades:y,leaves:b},S=(e,t,{ground:n})=>{let r=o_.transitions[e]({z:JP(`${this.key}@${t}`)*YP});return{name:e,since:i,done:e=>r.done(e),effect:yne(r.effect,n)}},C=({since:e,done:t})=>t(i-e),w=(e,t,n)=>({drawing:t,passage:g===null?null:n===void 0||n.passage?.name===`dissolve`?S(`fade`,e,t):n.passage!==null&&!C(n.passage)?n.passage:null}),T=(e,t)=>{if(t===void 0||t.drawing.opened||t.drawing.own.length===0)return;if(t.passage?.name===`dissolve`)return C(t.passage)?void 0:t;let r={...t.drawing,own:t.drawing.own.map(n.hold)};return{drawing:r,passage:S(`dissolve`,e,r)}},E=(e,t)=>{if(_.has(e))throw Error(`placement "${e}" was reached twice in one frame`);_.add(e);let r=g?.(e),{drawing:a,deeper:o}=n.returned(e,t),s=a===null?T(e,r):w(e,a,r);return s===void 0?t:(s.passage!==null&&(v.set(e,s.passage),(s.passage.name===`fade`?y:b).push({placement:e,t:i-s.passage.since})),a===null?[...s.drawing.own,...o]:t)},ee=(e,t)=>{let n=l.get(e)??c.get(e),r=n?.name===t?n:{name:t,since:i},a=i-r.since;return l.has(e)||(l.set(e,r),f.push({placement:e,effect:t,t:a})),{scope:e,name:t,t:a}},D=(e,t)=>{let n=d.get(e)??new Map;d.set(e,n);let r=n.get(t.scope);if(r!==void 0)return r.effect;let i=u.get(e)?.get(t.scope),a=i?.name===t.name,o=JP(t.scope===KP?e:`${e}@${t.scope}`),s=a?i.effect:o_.loops[t.name]({z:o*YP});return x[a?`reused`:`made`]++,n.set(t.scope,{name:t.name,effect:s}),s},te=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?s:ee(r.id,r.effect),i=t.get(e.scope);i===void 0?t.set(e.scope,{...e,owners:[n]}):i.owners.push(n)}return[...t.values()]},O=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=t.get(r.id);e===void 0?t.set(r.id,[n]):e.push(n)}return[...t].flatMap(([e,t])=>{let n=v.get(e)??null;return n===null?[]:[{timeline:a(i-n.since),effect:Vh(n.effect,...t)}]})},k=r===null?[]:[{timeline:Up.play(r.idleSince),effect:xne(r.fill,r.text,fte(r.timeoutS))}],ne=e=>e===`menu`?k:[];return{placed:h===`off`?(e,t)=>t:E,row:(e,n,r)=>{let i=(r.some(e=>e.placement.effect!==`bar`)?te(r):[{...s,owners:void 0}]).filter(_ne),o=O(r),c=ne(n);if(i.length===0&&o.length===0&&c.length===0)return GP;let l=`${this.key}#${e}`;return{kind:`moving`,time:t.wall,wrap:e=>new jh(e,vne([...i.map(e=>{let t=D(l,e);return{timeline:a(e.t),effect:e.owners===void 0?t:bne(t,e.owners)}}),...o,...c]),{key:l,theme:qP})}},drawn:()=>{this.anchor=t.timeline,this.inForce=o,this.placements=l,this.made=d,this.passages=h===`off`?null:v,this.frame=x}}}},Sne=class{sessions=new Map;constructor(e=256){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new XP(e);this.sessions.delete(e),this.sessions.set(e,t);for(let e of this.sessions.keys()){if(this.sessions.size<=this.maxSessions)break;this.sessions.delete(e)}return t}getStats(){let e=0;for(let t of this.sessions.values())e+=t.heldCount;return{sessions:this.sessions.size,effects:e}}};const ZP={fg:`#ffffff`,bg:`#c82828`},QP={fg:`#000000`,bg:`#dca028`};function $P(e,t){return`\x1b[${e};2;${[1,3,5].map(e=>Number.parseInt(t.slice(e,e+2),16)).join(`;`)}m`}const Cne=$P(38,ZP.fg),wne=$P(48,ZP.bg),Tne=[[0,31],[127,159],[8234,8238],[8294,8303]];function Ene(e){return Tne.some(([t,n])=>e>=t&&e<=n)}function eF(e){let t=``;for(let n of e)t+=Ene(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function tF(e,t){let n=eF(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const Dne=`${wne}${Cne}`;function nF(e){return`⚠ cc-candybar: ${kne(e)}`}function One(e){return`${Dne}${nF(e)}\n`}function kne(e){switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:return`daemon rejected request: ${tF(e.message,60)}`;case`render_failed`:return`render failed: ${tF(e.message,60)}`;case`switched_off`:return`switched off: ${tF(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${tF(e.message,60)}`}}function rF(e,t){return{depth:e.depth,rows:t,nextChange:1/0,motion:e.motion===`still`?`still`:`can-move`,pending:[]}}function iF(e,t){return{depth:`truecolor`,rows:[{kind:`diagnostic`,runs:[{text:eF(e),...t}]}],nextChange:1/0,motion:`still`,pending:[]}}function Ane(e){return iF(nF({kind:`permanent`,cause:`render_failed`,message:e}),ZP)}function aF(e,t){try{return e(t)}catch(t){return e(iF(`⚠ cc-candybar ${t instanceof Error?t.message:String(t)}`,ZP))}}function oF(e){return e.type===H.TRUECOLOR?e.value.hex:e.number===void 0?e.name:`color(${e.number})`}const jne=Object.keys(new W().attributes);function Mne(e,t){let{color:n,bgcolor:r}=e.drawnColors(t),i=jne.filter(t=>e[t]===!0);return{...n!==void 0&&{fg:oF(n)},...r!==void 0&&{bg:oF(r)},...i.length>0&&{attrs:i}}}function Nne({text:e,style:t},n){return{text:e,...t!==void 0&&n!==null&&Mne(t,n),...t?.link!==void 0&&{link:t.link}}}function Pne(e,t){let n=e.filter(e=>!e.isControl&&e.text.length>0);return G.splitLines(n).map(e=>e.map(e=>Nne(e,t)))}function Fne({text:e,fg:t,bg:n,attrs:r=[],link:i}){return new G(e,new W({color:t,bgcolor:n,link:i,...Object.fromEntries(r.map(e=>[e,!0]))}))}function sF(e,t){let n=ru(t);return e.map(e=>Dh(e.map(Fne),n)).join(`
191
191
  `)}function cF(e){return sF(e.rows.map(e=>e.runs),e.depth)}function Ine(e){return cF(e)+`
192
192
  `}const Lne=(e,t)=>e.fg===t.fg&&e.bg===t.bg&&e.link===t.link&&e.attrs?.join()===t.attrs?.join();function lF({runs:e}){let t=[];for(let n of e){let e=t.at(-1);e!==void 0&&Lne(e,n)?t[t.length-1]={...e,text:e.text+n.text}:t.push(n)}return t}function uF(e){return e.map(e=>e.text).join(``)}const Rne={};function dF(e,t){let n=ru(t.colorSystem),{time:r}=t,i=1/0,a=[...hp(e,{maxWidth:t.width??80,isTerminal:!1,asciiOnly:!1,theme:UP,colorSystem:n.colorSystem,...r===void 0?{}:{frame:{time:r,host:Rne}},onStyleError:e=>{throw e},onHold:({nextChange:e})=>{i=Math.min(i,e)}})];return{lines:Pne(a,n.colorSystem),nextChange:Math.min(G.nextChange(a),i)}}const fF=new Map;function zne(e){let t=fF.get(e);if(t!==void 0)return t;let n=t=>({seam:t.seam.map(t=>`cap`in t?t:{...t,glyph:e})}),{seam:r,caps:i}=wh.plain,a=new Zm({glyph:n(r.glyph),ascii:r.ascii},i);return fF.set(e,a),a}function pF(e,t){return e===`plain`&&t!==void 0?zne(t):wh[e]}const mF=new Map;function hF(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=mF.get(t);if(n!==void 0)return n;let r=pF(e.endcaps,e.separator),i=e=>new q(`x`,{end:``,overflow:`ignore`,style:new W({bgcolor:e})}),a=e=>{let{lines:t}=dF(new bm(e,r),{colorSystem:null});return new q(uF(t.flat())).cellLength},o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return mF.set(t,s),s}function gF(e){return hF(e).chrome}function _F(e){return hF(e).seam}const Bne=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function vF(e){return[...new Set(e.match(Bne)??[])].join(``)}function Vne(e){let t=pF(e.endcaps,e.separator),n=e=>new q(`x`,{end:``,style:new W({bgcolor:e})}),{lines:r}=dF(new bm([n(`#101010`),n(`#202020`)],t),{colorSystem:null});return vF(uF(r.flat()))}function yF(e){return e.wrap?e.width:1/0}function Hne(e,t){return dF(new q(e,{overflow:`fold`,end:``}),{colorSystem:null,width:t}).lines.map(uF)}function bF(e,t,n=GP){if(e.length===0)return{lines:[[]],nextChange:1/0};let r=pF(t.endcaps,t.separator),i=Number.isFinite(yF(t)),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new z_([...e],{joiner:r}):new bm([...e],r),s=n.kind===`still`?dF(o,a):dF(n.wrap(o),{...a,time:n.time});if(s.lines.length===0)throw Error(`drawStripCells: rich-js strip drew no line`);return s}function Une(e,t){return sF(bF(e,t).lines,t.colorCompatibility)}const Wne=[`moves`,`can-move`,`still`];function xF(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const Gne=[`statusline`,`frames`],SF=e=>e?.kind===`frames`?`frames`:`statusline`,Kne=[`carried`,`missing`,`unanswered`];function qne(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:xF(e)===`no`?`unanswered`:`missing`}function Jne(e){return{path:e.transcript_path,answered:xF(e)===`yes`}}const CF=[...Wne,`failed`,`drawing`];var Yne=class{seen=new Map;see(e,t,n,r){let i=SF(t.client),a=JSON.stringify([e,i]),o=this.seen.get(a);o!==void 0&&o.order>r||(this.seen.delete(a),this.seen.set(a,{sessionId:e,said:{...t,role:i},at:n,order:r}),this.seen.size>64&&this.seen.delete(this.seen.keys().next().value))}list(e){return[...this.seen.values()].map(({sessionId:t,said:n,at:r})=>({...n,sessionId:t,ago:e-r}))}ofSession(e,t){return this.list(t).filter(t=>t.sessionId===e)}};const wF={kitty:{label:`kitty`,xtversion:`kitty`,program:null,programVersion:!0,term:`xterm-kitty`,links:{since:`0.19.0`},glyphs:{kind:`bundled`,since:`0.36.0`}},wezterm:{label:`WezTerm`,xtversion:`WezTerm`,program:`WezTerm`,programVersion:!0,term:`wezterm`,links:{since:null},glyphs:{kind:`bundled`,since:`20230712`}},ghostty:{label:`Ghostty`,xtversion:`ghostty`,program:`ghostty`,programVersion:!0,term:`xterm-ghostty`,links:{since:null},glyphs:{kind:`bundled`,since:null}},iterm2:{label:`iTerm2`,xtversion:`iTerm2`,program:`iTerm.app`,programVersion:!0,term:null,links:{since:`3.1`},glyphs:{kind:`configured`}},alacritty:{label:`Alacritty`,xtversion:`alacritty`,program:null,programVersion:!0,term:`alacritty`,links:{since:`0.11.0`},glyphs:{kind:`configured`}},"apple-terminal":{label:`Terminal`,xtversion:null,program:`Apple_Terminal`,programVersion:!0,term:null,links:null,glyphs:{kind:`unread`}},vscode:{label:`VS Code`,xtversion:null,program:`vscode`,programVersion:!1,term:null,links:{since:`1.72`},glyphs:{kind:`unread`}}},TF=e=>wF[e];function Xne(e){return TF(e).glyphs.kind===`bundled`}function Zne(e){return TF(e).glyphs.kind===`configured`}const EF=e=>TF(e).label,Qne=[{since:`3.5.0`,from:57504,to:57507},{since:`3.5.0`,from:57520,to:57554},{since:`3.5.0`,from:57556,to:57556},{since:`3.5.6`,from:57558,to:57559}];function $ne(e,t){let n=t.codePointAt(0);return Qne.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&kF(e,t)===!0)}const DF=Object.keys(wF);function OF(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function kF(e,t){let n=OF(e),r=OF(t);if(n===null)return null;for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t>i}return!0}function ere(e){for(let t of DF){let n=TF(t).xtversion;if(n!==null&&e.toLowerCase().startsWith(n.toLowerCase())){let r=e.slice(n.length).replace(/^[\s(]+/,``);return{name:t,version:/^[^\s)]+/.exec(r)?.[0]??null}}}return null}function AF(e){let t=DF.find(t=>TF(t).term===e);return t===void 0?null:{name:t,version:null}}function tre(e){let t=ere(e.termtype)??AF(e.termname);if(t!==null)return{kind:`known`,terminal:t};let n=/^[^\s(]*/.exec(e.termtype)[0];return n===``?{kind:`unnamed`,term:e.termname}:{kind:`unknown`,called:n}}function nre(e){let t=e.TERM_PROGRAM,n=DF.find(e=>TF(e).program===t),r=n===void 0?AF(e.TERM):{name:n,version:TF(n).programVersion?e.TERM_PROGRAM_VERSION??null:null};return r===null?t===void 0||t===`tmux`?{kind:`unnamed`,term:e.TERM??``}:{kind:`unknown`,called:t}:{kind:`known`,terminal:r}}function jF(e){switch(e.kind){case`known`:return EF(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function MF(e){switch(e.kind){case`known`:return EF(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function rre({name:e,version:t}){let n=TF(e).links;if(n===null)return{kind:`none`};if(n.since===null)return{kind:`draws`};if(t===null)return{kind:`unsaid`,since:n.since};let r=kF(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const ire=DF.filter(e=>TF(e).links!==null).map(EF).join(`, `);function NF(e){if(e.kind===`failed`)return{kind:`unread`,reason:e.reason};let t=e.value.flatMap(({scope:e,path:t,settings:n})=>`statusLine`in n?[{from:{scope:e,path:t},line:n.statusLine}]:[]),n=t[0];if(n===void 0)return{kind:`absent`,read:e.value.map(e=>e.path)};if(!ts(n.line))return{kind:`not-an-object`,value:n.line,from:n.from};for(let{from:e,line:r}of t){if(e.scope!==n.from.scope||!ts(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function PF(e,t){if(e.kind===`failed`)return e;let n=e.value.find(e=>Object.hasOwn(e.env,t));return{kind:`ok`,value:n===void 0?{kind:`unset`}:{kind:`set`,value:n.env[t],from:{scope:n.scope,path:n.path}}}}const are=[`managed`,`project`],ore=e=>!are.includes(e.scope),sre={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:es(t.projectDir)}),user:e=>({scope:`user`,path:e})},FF=[`drawn`,`boxes`],IF=1024*1024,LF=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function cre(e){switch(e.kind){case`claude-settings`:return`${e.kind} ${e.path.join(`.`)}=${JSON.stringify(e.value)} file=${JSON.stringify(e.file.path)} scope=${e.file.scope}`;case`post-mortems-read`:return`${e.kind} through=${e.through}`}}function RF(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const zF=kc.truecolor;function BF(e,t){switch(e.kind){case`unreported`:return{ok:!1,reason:"the client reported no tmux facts — re-run `cc-candybar install` to stage a current client"};case`outside`:return{ok:!0};case`inside`:return e.client.kind===`failed`?{ok:!1,reason:`tmux could not be asked: ${e.client.reason}`}:e.client.value===null?{ok:!0}:t(e.client.value,e.hint)}}const lre={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>BF(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=PF(t.sources,zF);if(r.kind===`failed`)return{ok:!1,reason:r.reason};let i=r.value;if(i.kind===`set`&&typeof i.value==`string`&&i.value!==``)return{ok:!1,reason:`${zF} is set in ${i.from.path} — restart Claude Code to apply`};let a=`Claude Code renders the bar in 256 colours inside tmux`,o=e=>({ok:!1,reason:a,fix:{kind:`claude-settings`,file:e,path:[`env`,zF],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=sre[i.from.scope](i.from.path,t.at);return s===null?{ok:!1,reason:`${a} — the value that counts is in managed settings, ${i.from.path}: set ${zF} to "1" there`}:o(s)})},ure={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>BF(e,e=>e.utf8?{ok:!0}:{ok:!1,reason:"tmux draws this terminal without UTF-8, so every glyph on the bar arrives as `_` — attach with `tmux -u`, or set a UTF-8 LC_ALL/LC_CTYPE/LANG in the shell that runs tmux"})},dre={name:`termWidth`,label:`terminal width`,takesMark:!1,probe:({width:e})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.columns===null?{ok:!1,reason:`${LF(e.value.of)} measured no width (no COLUMNS, and no terminal to ask — or the daemon refused the width sent, which the bar's diagnostics name), so the bar is laid out as if the terminal were 120 columns wide`}:{ok:!0,note:`${e.value.columns} columns, as ${LF(e.value.of)} measured`}},fre={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},pre={argument:`command argument`,environment:`$${DP}`,unknown:`source unknown`};function mre({target:e,layers:t}){return e.source===`search`?t.length===0?jP(t):`${jP(t)} (searched)`:`${e.path} (${pre[e.source]})`}function hre(e){switch(e.kind){case`failed`:{let t=[...e.error.split(`
193
- `).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return t.length===0?[`the config failed to load`]:t}case`loaded`:return[...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${fre[e]}`)]}}const gre={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{let t=mre(e),[n,...r]=[...hre(e),...VP(e.repos)],i=t=>[t,...HP(e.repos)].join(`; `);return n===void 0?{ok:!0,note:i(t)}:{ok:!1,reason:i(`${t}: ${n}`),more:r}}},VF="re-run `cc-candybar install`";function _re(e){if(e.kind===`failed`)return[`Launch Services could not be asked which app opens cc-candybar:// — ${e.reason}`];if(e.value===null)return[`no app is registered for cc-candybar:// — ${VF}`];let{app:t,forwarder:n}=e.value;return n?[]:[`${t} opens cc-candybar://, but it is not the forwarder app \`cc-candybar install\` builds — ${VF}`]}function vre(e){return e===null?[]:[`the daemon (${e.theirs}) is another build than this client (${e.mine}), so it may not read the link this build sends`]}const yre={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.delivery.kind===`forwarder`?{ok:!0}:{ok:!1,reason:`the link was delivered by a click request (\`cc-candybar url-handle\`), not the forwarder app — ${VF}`};case`lost`:return RF([..._re(e.opener),...e.unopened===null?[...vre(e.otherBuild),`a cc-candybar:// link was opened and did not arrive at the daemon`]:[`a cc-candybar:// link could not be opened — ${e.unopened}`]])}}};function HF({bundle:e,checkout:t},n){return{bundle:n.bundle.kind===`failed`?{kind:`unresolved`,reason:n.bundle.reason}:n.bundle.value===e?{kind:`same`}:{kind:`other`,path:n.bundle.value},source:n.client!==`native`||t===null?{kind:`uncompared`}:t.rustSource.kind===`failed`?{kind:`unreadable`,root:t.root,reason:t.rustSource.reason}:n.source===null?{kind:`unstamped`}:n.source===t.rustSource.value?{kind:`same`}:{kind:`other`,root:t.root}}}function UF(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${Qc.join(`|`)}>\``:e.checkout===null?VF:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function bre(e,t,n){let{checkout:r}=e;if(n.kind===`unreported`)return[`the bar is drawn by a statusline client too old to say what it is — ${UF(e,`native`)}`];let{bundle:i,source:a}=HF(e,n);switch(i.kind){case`unresolved`:return[`the statusline client's bundle cannot be resolved: ${i.reason}`];case`other`:return[`the statusline client runs ${i.path}, not the daemon's ${e.bundle} — ${UF(e,n.client)}`];case`same`:break}if(n.client===`node`&&(t||r!==null))return[`the bar is drawn by the Node fallback, which starts node on every render — ${UF(e,`native`)}`];switch(a.kind){case`uncompared`:case`same`:return[];case`unreadable`:return[`${a.root}/rust-client could not be read: ${a.reason}`];case`unstamped`:return["the native client carries no source stamp, so which source it was built from is unknown — run `just install-rust`"];case`other`:return[`the native client was built from other source than ${a.root}/rust-client holds — run \`just install-rust\``]}}const WF=e=>{let t=`restarted since the bar was drawn, or has served 64 newer sessions`;return e.kind===`clicked`?`this daemon holds no render of this bar (it ${t})`:`this daemon holds no render of session ${e.sessionId}'s bar (its statusLine does not run cc-candybar — a \`claude -p\` session draws none — or the daemon ${t}; unset CLAUDE_CODE_SESSION_ID to judge every bar drawn recently)`},xre={name:`install`,label:`install`,takesMark:!1,probe:({install:e,sighted:t})=>{if(e.kind===`failed`)return{ok:!1,reason:`the daemon could not be asked which clients draw the bar: ${e.reason}`};let{daemon:n,nativeShipped:r,clients:i}=e.value;return i.length===0?{ok:!1,reason:t.kind===`recent`?`no statusline client has drawn a bar for this daemon in the last ${300/60} minutes — run the doctor again once the bar has redrawn; if it never does, the statusLine command does not run cc-candybar`:`${WF(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:RF([...new Set(i.flatMap(e=>bre(n,r,e)))])}};function GF({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||Fi(e.identity,t.value.through)):[]}function KF(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const Sre={name:`daemon`,label:`daemon`,takesMark:!1,probe:({daemon:{serving:e,processes:t,read:n}})=>{let r=t.kind===`failed`?[`the process table could not be read: ${t.reason}`]:[],i=t.kind===`ok`?KF(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return RF([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=GF(e.value,n),u=RF([...l.map(e=>`the daemon ran out of memory and restarted (${e.identity}) — post-mortem: ${Object.values(e.artifacts).join(`, `)}`),...c.kind===`failed`?[`the daemon's post-mortems could not be listed: ${c.reason}`]:[],...n.kind===`failed`&&!(c.kind===`ok`&&c.value.length===0)?[`which post-mortems were read could not be read: ${n.reason}`]:[],...r,...i.map(e=>`daemon ${e.pid} (started ${e.started}, rss ${P(e.rss)} MB${e.ppid===1?``:`, child of ${e.ppid}`}) runs beside the one serving the bar (${a}) — \`kill ${e.pid}\``),...o.kind===`measured`&&o.charge.kind===`stand-in`?[`the daemon could not read what macOS charges it (${o.charge.unread}), so its memory limit judges ${o.charge.gap===0?`RSS, which counts pages macOS has reclaimed`:`RSS less the ${P(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&Ri(o.charge.bytes,s)?[`the daemon holds ${Hi(o.charge)} of its ${P(s)} MB limit — at the limit it records a post-mortem and restarts`]:[]]);if(u.ok&&o.kind===`unmeasured`)return{ok:!0,note:`the daemon has not measured its memory yet`};let d=l[0];return u.ok||d===void 0?u:{...u,fix:{kind:`post-mortems-read`,through:d.identity}}}},qF=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function Cre(e,t){let n=jF(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?rre(e.terminal):{kind:`unknown`}}function wre({identified:e,tmuxClient:t},n){let r=MF(e),i=Cre(e,n),a=jF(e)===null?qF:`${qF}, and the doctor remembers it for this terminal`,o=(()=>{switch(i.kind){case`draws`:return[];case`none`:return[`${r} draws no links (OSC 8), so nothing on the bar can be clicked — run Claude Code in a terminal that draws them: ${ire}`];case`older`:return[`${r} ${i.version} draws no links (OSC 8 came in ${i.since}) — update ${r}`];case`unsaid`:return[`${r} draws links (OSC 8) since ${i.since}, and did not say which release this is — ${a}`];case`unknown`:return[`the doctor does not know whether ${r} draws links (OSC 8) — ${a}`]}})(),s=n.kind===`failed`&&i.kind!==`draws`?[`the terminals a doctor click came back from could not be read: ${n.reason}`]:[],c=i.kind===`none`||t===null||t.features.includes(`hyperlinks`)?[]:[`tmux does not pass links through to ${r} — add \`set -as terminal-features ",${t.termname}:hyperlinks"\` to tmux.conf, then detach and reattach (tmux 3.4 or later)`];return[...o,...s,...c]}const Tre={name:`links`,label:`links`,takesMark:!1,probe:({sighted:e,terminal:t,clicked:n})=>{if(e.kind===`clicked`&&e.via===`link`)return{ok:!0};switch(t.kind){case`unreported`:return{ok:!1,reason:"the client reported no terminal — re-run `cc-candybar install` to stage a current client"};case`unasked`:return{ok:!1,reason:`tmux could not be asked which terminal is attached: ${t.reason}`};case`seen`:return RF(wre(t,n))}}},JF=e=>e.filter(e=>e.role===`statusline`),Ere={name:`effectRefresh`,label:`effect refresh`,takesMark:!1,probe:({frames:e,claudeSettings:{origin:t,elsewhere:n},sighted:r})=>{let i=[t,...n].flatMap(({sources:e,bars:t})=>Ore(e,Dre(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:YF(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:WF(r));let[o,...s]=i.flatMap(e=>e.ok?[]:[e]);if(o===void 0)return a;let c=[...new Set(s.map(e=>e.reason))].filter(e=>e!==o.reason);return c.length===0?o:{...o,more:c}}},Dre=e=>{let t=JF(e).map(e=>e.frame);return t.includes(`moves`)?{kind:`moving`,wearing:`the bar moves (an effect, a fade, an animated segment, or an open menu counting down to its close)`}:t.includes(`can-move`)?{kind:`moving`,wearing:`the bar can start moving (an open menu, which flashes and closes on its own, a globals.effect rule, placements that fade in and out, or a placement with an effect of its own that is not drawn now)`}:t.includes(`still`)?{kind:`still`}:t.includes(`drawing`)?{kind:`unknown`,unseen:`the bar's latest render has not finished`}:t.length>0?{kind:`unknown`,unseen:`the bar's recent renders failed`}:e.length>0?{kind:`unknown`,unseen:"only a `cc-candybar frames` display has drawn this bar, not Claude Code's statusline"}:{kind:`none`}},YF=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function Ore(e,t){let n=NF(e);if(n.kind===`present`&&n.refreshInterval===1)return{ok:!0,note:`statusLine.refreshInterval is 1 in ${n.from.path}`};switch(t.kind){case`none`:return null;case`still`:return{ok:!0};case`unknown`:return YF(t.unseen);case`moving`:break}let{wearing:r}=t;switch(n.kind){case`unread`:return{ok:!1,reason:`${r}, and Claude Code's settings could not be read: ${n.reason}`};case`absent`:return{ok:!1,reason:`${r}, and no settings file Claude Code reads here sets a statusLine (read: ${n.read.join(`, `)||`none`}) — the one that runs the bar comes from --settings, MDM or server-managed settings, which the doctor cannot read; set "refreshInterval": 1 beside its command there`};case`not-an-object`:return{ok:!1,reason:`${r}, and ${n.from.path} sets statusLine to ${JSON.stringify(n.value)}, not a statusLine object — ${n.from.scope===`user`?"re-run `cc-candybar install` to write one":`replace it there with the statusLine object that runs cc-candybar`}`};case`present`:{let{from:e,refreshInterval:t}=n,i=t===void 0?`its statusLine sets no refreshInterval, so Claude Code redraws it only on events`:typeof t==`number`&&t>1?`its statusLine redraws it only every ${t} s`:`its statusLine.refreshInterval is ${JSON.stringify(t)}, not a number of seconds Claude Code accepts (its minimum is 1)`;return ore(e)?{ok:!1,reason:`${r}, but ${i} (statusLine from ${e.path})`,fix:{kind:`claude-settings`,file:e,path:[`statusLine`,`refreshInterval`],value:1}}:{ok:!1,reason:`${r}, but ${i} — its statusLine is in ${e.scope===`managed`?`managed settings`:`the project's shared settings`}, ${e.path}: set "refreshInterval": 1 there`}}}}const XF=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function kre(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return MF(e);case`bundling`:case`unread`:case`configured`:return[EF(e.name),e.version].filter(e=>e!==null).join(` `)}}function Are(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return jF(e);case`bundling`:case`unread`:return EF(e.name);case`configured`:{let t=EF(e.name);return e.font.kind===`ok`?`${t} with ${e.font.value.font} (${e.font.value.from})`:`${t}, its font unread: ${e.font.reason}`}}}function ZF(e){let t=Are(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${XF(e.glyphs)}`}}const jre={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=ZF(e),r=e=>t.kind===`failed`&&n!==void 0?{ok:!1,reason:e,more:[`the mark book could not be read: ${t.reason}`]}:{ok:!1,reason:e,...n!==void 0&&{sighting:n}},i=e.terminal,a=kre(i);switch(n===void 0||t.kind===`failed`?null:t.value.nerdFont?.[n.id]??null){case`drawn`:return{ok:!0};case`boxes`:return r(`${a} draws ${XF(e.glyphs)} as boxes — set a Nerd Font as its font`);case null:break}switch(i.kind){case`unreported`:return r("the client reported no terminal — re-run `cc-candybar install` to stage a current client");case`unasked`:return r(`tmux could not be asked which terminal is attached: ${i.reason}`);case`unknown`:case`unnamed`:case`unread`:return r(`the doctor cannot read ${a}'s font`);case`bundling`:{let e=wF[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:kF(i.version,e);if(t===!0)return{ok:!0};let n=EF(i.name);return r(t===null?`${n} ships Nerd Font symbols since ${e}, and did not say which release this is`:`${a} ships no Nerd Font symbols (they came in ${e}) — update ${n}, or set a Nerd Font as its font`)}case`configured`:{if(i.font.kind===`failed`)return r(`the doctor cannot read ${a}'s font: ${i.font.reason}`);let{font:e,from:t,lacks:n}=i.font.value;return n===null?r(`${a} is set to ${e} (${t}), which is not installed — install it or set a Nerd Font`):n.length===0?{ok:!0}:r(`${a} draws with ${e} (${t}), which has no ${XF(n)} — set a Nerd Font as its font`)}}}};function QF(e){return e.join(`, `)}function $F(e){return`or set missingData: "ignore" on ${QF(e)}`}function Mre(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${QF(t)}: whether the forge CLI is ready could not be asked: ${n.reason}`];if(n.value===null)return[];let{cli:r,host:i,status:a}=n.value;return a===`ready`?[]:a===`missing`?[`${QF(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${$F(t)}`]:[`${QF(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${$F(t)}`]}function Nre(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${QF(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${QF(n)}: no session of this Claude Code has drawn a bar for this daemon in the last ${300/60} minutes, so whether it sends rate_limits is unseen — run the doctor again once the bar has redrawn`:`${QF(n)}: ${WF(t)}, so whether Claude Code sends rate_limits is unseen — run the doctor again once the bar has redrawn`]:r.value.includes(`missing`)&&!r.value.includes(`carried`)?[`${QF(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${QF(n)}`]:[]}const Pre={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>RF([...Mre(e.pullRequests),...Nre(e.rateLimits,t)])};function Fre({path:e,answered:t,read:n}){switch(n.kind){case`absent`:return t?[`the transcript ${e} does not exist, though Claude Code has answered in its session — the bar's session cost, metrics and activity read nothing`]:[];case`failed`:return[`the transcript ${e} cannot be read: ${n.reason}`];case`ok`:{let{lines:t,unparsed:r,whole:i}=n.value;return r===0?[]:[`${r} of the ${t} lines ${i?`in`:`in the last ${IF/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const eI=[gre,xre,Sre,yre,Tre,lre,ure,dre,Ere,jre,Pre,{name:`sessionData`,label:`session data`,takesMark:!1,probe:({transcripts:e,sighted:t})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.length===0?{ok:!1,reason:t.kind===`recent`?`no session has drawn a bar for this daemon in the last ${300/60} minutes, so no transcript was named — run the doctor again once the bar has redrawn`:`${WF(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:RF(e.value.flatMap(Fre))}],Ire=eI.filter(e=>e.takesMark);function tI(e){return eI.map(t=>({check:t,verdict:t.probe(e)}))}function nI(e){return eI.find(t=>t.name===e)}const Lre=`${ES}doctor.`;function rI(e){let t=`${Lre}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function Rre({target:e,repos:t}){return`configTarget=${e.source} repos=${t.awaiting.length}/${t.declined.length} unproven=${t.unproven.length}`}function zre(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?jF(e.identified):null,i=t.kind===`failed`?`unread`:r===null?`-`:t.value.includes(r)?`yes`:`no`;return`tmuxLinks=${n===null?`-`:n.features.includes(`hyperlinks`)?`yes`:`no`} clicked=${i}`}function Bre(e,t){let n=e.kind===`seen`?e.tmuxClient:null;return`cols=${t.kind===`failed`?`failed widthOf=-`:`${t.value.columns??`-`} widthOf=${t.value.of.kind}`} clientUtf8=${n===null?`-`:n.utf8?`yes`:`no`}`}function Vre(e){if(e.kind===`failed`)return`clients=unasked`;let{daemon:t,clients:n}=e.value;return`clients=${n.map(e=>{if(e.kind===`unreported`)return`unreported/-/-`;let{bundle:n,source:r}=HF(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const Hre=e=>`${e>=0?`+`:``}${P(e)}`;function Ure({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${KF(e,t.value).map(e=>e.pid).join(`,`)||`-`}`;if(e.kind===`failed`)return`${r} memory=unasked postMortems=unasked`;let{memory:i,limit:a,postMortems:o}=e.value,s=o.kind===`failed`||n.kind===`failed`?`unread`:`${GF(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Ui(i.charge)}${i.charge.kind===`stand-in`?`(${Hre(-i.charge.gap)})`:``}:${P(i.charge.bytes)}`}/${P(a)} postMortems=${s}`}function Wre(e){return`data=pr:${(()=>{if(e.pullRequests.kind===`unneeded`)return`-`;let t=e.pullRequests.fact;if(t.kind===`failed`)return`failed`;if(t.value===null)return`no-forge`;let{status:n}=t.value;return typeof n==`string`?n:`logged-out`})()},rateLimits:${(()=>{if(e.rateLimits.kind===`unneeded`)return`-`;let t=e.rateLimits.fact;if(t.kind===`failed`)return`failed`;let n=e=>t.value.filter(t=>t===e).length;return`${n(`carried`)}/${n(`missing`)}/${n(`unanswered`)}`})()}`}function Gre(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>Kre(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${z(i)}`;let a=JF(r.flatMap(e=>e.bars));return`frames=${CF.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${z(i)}`}function Kre(e){let t=NF(e);switch(t.kind){case`unread`:return`failed`;case`absent`:case`not-an-object`:return t.kind;case`present`:return`${t.from.scope}:${t.refreshInterval===void 0?`-`:JSON.stringify(t.refreshInterval)}`}}function qre(e){let t=PF(e,zF);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${z(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function Jre(e){if(e.kind===`failed`)return`transcripts=failed`;let t=t=>e.value.filter(e=>e.read.kind===t).length,n=e.value.reduce((e,t)=>e+(t.read.kind===`ok`?t.read.value.unparsed:0),0);return`transcripts=${t(`ok`)}/${t(`absent`)}/${t(`failed`)} unparsed=${n}`}function Yre(e,t){if(e.kind===`none`)return`glyphs=- terminal=- font=- mark=-`;let{glyphs:n,terminal:r}=e,i=[...n].map(e=>e.codePointAt(0).toString(16)),a=(()=>{switch(r.kind){case`unreported`:case`unasked`:return r.kind;case`unknown`:return`unknown:${JSON.stringify(r.called)}`;case`unnamed`:return`unnamed:${JSON.stringify(r.term)}`;case`bundling`:case`unread`:case`configured`:return`${r.name}@${r.version??`-`}`}})(),o=(()=>{if(r.kind!==`configured`)return`-`;if(r.font.kind===`failed`)return`failed`;let{font:e,lacks:t}=r.font.value;return`${JSON.stringify(e)}:${t===null?`not-installed`:`lacks${t.length}`}`})(),s=ZF(e),c=t.kind===`failed`?`unread`:s===void 0?`-`:t.value.nerdFont?.[s.id]??`-`;return`glyphs=${i.join(`,`)} terminal=${a} font=${o} mark=${c}`}function Xre(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function Zre(e){return e.flatMap(({check:e,verdict:t})=>{let n=rI(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:qy},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:Xre(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?qy:Ky},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const Qre={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function iI(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries(Qre).map(([t,n])=>[`${e}${t}`,n]))}}const aI=`armed`,oI=`disarmed`,sI=`.armed`,cI=e=>e.endsWith(sI);function lI(e,t,n){let r=[...new Set(n.map(e=>e.when))].filter(e=>e!==`true`),i=t=>r.length===0?e:`${e}.${t}`,a={};for(let e=0;e<2**r.length;e++)a[i(e)]={do:[t,...n.filter(t=>t.when===`true`||e&1<<r.indexOf(t.when)).map(e=>e.action)]};let o=(e,t)=>e===r.length?`"${i(t)}"`:`(ternary ${o(e+1,t|1<<e)} ${o(e+1,t)} (${r[e]}))`;return{link:o(0,0),actions:a}}function uI(e,t,n){let r=`${e}${sI}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${aI}")`,s=lI(e,a,n);return{template:`{{ if ${o} }}{{ action ${s.link} "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:aI},[a]:{set:r,to:oI},...s.actions},armed:o,variables:{[e]:{kind:`state`,key:r,default:oI}},disarm:a}}const dI=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function fI(e){return typeof e==`string`&&dI.test(e)?{kind:`line`,line:e}:{kind:`refused`,reason:`a slash command is "/" then its name, e.g. "/compact" or "/model opus", on one line with no control characters, got ${JSON.stringify(e)}`}}function pI(e){let t=fI(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const mI=[`/compact`,`/model`],hI=`/clear`;function gI(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=uI(`${e}clear`,{arm:hI,confirm:`${hI} ✓ confirm`},[{action:n,when:`true`}]);return{template:mI.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${Xc} }}`,actions:{...Object.fromEntries(mI.map(e=>[t(e),{slash:pI(e)}])),...r.actions,[n]:{slash:pI(hI)}},variables:r.variables,disarm:r.disarm}}const _I=Array.from({length:10},(e,t)=>(t+1)*1e5),vI=_I[0],yI=_I[_I.length-1];function bI(e){let t=Qo(e);if(t.kind!==`ok`)return t;let n=t.value.autoCompactWindow;return n===void 0?F(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=vI&&n<=yI?F(n):L(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${vI}–${yI} tokens)`,`parse`)}function xI(e,t){let n=Math.min(t??yI,yI),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:_I.filter(e=>e<r).at(-1)??0,higher:_I.find(e=>e>r&&e<=n)??0}}function SI(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${Xc} }}{{ if gt .autocompact.lower 0 }} {{ action (printf "${e}%d" .autocompact.lower) "−" }}{{ end }}{{ if gt .autocompact.higher 0 }} {{ action (printf "${e}%d" .autocompact.higher) "+" }}{{ end }}{{ if gt .autocompact.window 0 }} {{ action "${e}auto" "↺" }}{{ end }}{{ end }}{{ end }}`,bg:`{{ if ne .autocompact.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .autocompact.window 0) (ne .autocompact.error "") }}`,actions:{[`${e}auto`]:{slash:pI(`/autocompact auto`)},...Object.fromEntries(_I.map(t=>[`${e}${t}`,{slash:pI(`/autocompact ${t}`)}]))}}}const CI=e=>`{{ if ge ${e} 1000000 }}{{ printf "%.1f" (divf ${e} 1000000) }}M{{ else if ge ${e} 1000 }}{{ printf "%.1f" (divf ${e} 1000) }}K{{ else }}{{ ${e} }}{{ end }}`,wI=`${ES}edit`,TI=`${ES}toolbar`,EI=iI(ES),DI=`${ES}commands`,OI=gI(`${DI}.`),kI=`${ES}autocompact`,AI=SI(`${kI}.`,CI),jI=e=>({kind:`segment`,name:e}),MI=`${ES}tab`,NI=e=>`${MI}.${e}`,PI=e=>`${NI(e)}.toggle`,FI=e=>({variable:MI,key:MI,member:e}),II=`${ES}save`,LI=`${ES}preset.save`,RI=`${ES}preset.delete`,zI=e=>`${ES}${e}`,BI=e=>`${ES}apply.${e}`,VI=e=>`${ES}reset.${e}`,HI=`${ES}themeDefault.save`,UI=`${ES}themeDefault.differs`,WI=`${ES}themeDefault.theme`,GI={when:`{{ .${UI} }}`,template:`{{ action "${HI}" (printf "⤓ default for %s" .${WI}) }} {{ swatch "${BI(`theme`)}" .${WI} }}`},KI=`${ES}resetAll`,qI=`${kS}.toggle`,JI=`${ES}undo`,YI=`${ES}back`,XI=`${YI}.step`,ZI=`${ES}navigation.back`,QI=YI,$I={template:`{{ if gt .${ZI} 0 }}{{ action "${YI}" "◁" }}{{ else }}{{ fg (${CP}) "◁" }}{{ end }}`},eL=`${ES}redo`,tL=`${ES}doctor`,nL=`${tL}.run`,rL=e=>`${tL}.fix.${e}`,iL=(e,t)=>`${tL}.mark.${e}.${t}`,aL=e=>`${tL}.${e}`,oL={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},sL=FM(`${ES}pickers`),cL=e=>`${ES}${e}`,lL=e=>`${cL(e)}.toggle`,uL=e=>tN(e)?FM(`${ES}${e}Pickers`):sL,dL=e=>{let t=uL(eN[QM[e].beside]);return{variable:t,key:t,member:e}},fL={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${RI}" (printf "🚮 delete %s" .${xx.preset.effectiveVar}) }}`}},pL=(e,t)=>`${ES}list.${e}.${t}`,mL=e=>`${ES}resettable.${e}`,hL=e=>e.length===0?`false`:`(or ${e.map(e=>`(and (${e.shown}) .${mL(e.name)})`).join(` `)})`,gL=Qc.map(e=>[Zc[e].switch.setting,e]),_L={variables:{},actions:{},segments:{}},vL=Object.fromEntries(gL.map(([e,t])=>[e,cP(`${ES}help.${e}`,xP[t],[],_L)])),yL=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],bL=e=>{let t=t=>`.${rl(e,t)}`,n=yL.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if eq .${xx[Zc[e].switch.setting].effectiveVar} ${JSON.stringify(Zc[e].switch.on)} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},xL=`{{ if .diagnostics.label }} {{ bg .diagnostics.bg (fg .diagnostics.fg (action "${MS}" .diagnostics.label .diagnostics.open)) }}{{ end }}`,SL=`${ES}fps`,CL=`{{ if eq .${tl(`by`)} "feed" }}{{ printf "%3s" (printf "≤%d" (int .${tl(`fps`)})) }} fps{{ else }}${`polled`.padStart(7)}{{ end }}`,wL=Object.fromEntries(gL.map(([e,t])=>[e,bL(t)])),TL=e=>$M.filter(t=>QM[t].beside===e),EL=Object.keys(xx).map(e=>{let t=xx[e],n=eN[e];return{...t,name:e,place:n,control:JM({label:t.label,domain:cN(t.configKey)},t.sessionKey,t.effectiveVar,BI(e),uL(n)),beneath:t.previews.map(e=>fL[e]),help:[vL[e]].filter(e=>e!==void 0),submenus:TL(e)}}),DL=e=>EL.filter(t=>t.place===e),OL=e=>EL.filter(t=>nN(t.place,e)),kL=e=>t=>`(print ${Ta(t)} (ternary ${Ta(` •`)} "" ${hL(OL(e))}))`,AL=e=>DL(e).flatMap(e=>[HL(e),...e.help,...e.submenus.map(e=>ba(cL(e),dL(e),YL(e),`drop`))].map(t=>({...t,when:`{{ ${e.shown} }}`})));new Set(EL.flatMap(e=>[e.sessionKey,e.configKey]));const jL=uI(KI,{arm:`⟲`,confirm:`⟲ reset all?`},EL.map(e=>({action:VI(e.name),when:e.shown}))),ML=[`unsaved`,`history.undo`,`history.redo`],NL=e=>`${ES}${e}`,PL=NL(`unsaved`),FL=(e,t)=>({body:t,shown:`(gt .${NL(e)} 0)`}),IL=[FL(`unsaved`,`{{ action "${II}" (printf "💾 save %d" .${PL}) }}`),FL(`history.undo`,`{{ action "${JI}" "↶" }}`),FL(`history.redo`,`{{ action "${eL}" "↷" }}`),{body:jL.template,shown:`(or ${hL(EL)} ${jL.armed})`}],LL={when:`{{ or ${IL.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+IL.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},RL=[{step:jL,place:`door`},{step:OI,place:`session`}],zL=e=>e.map(e=>e.step.disarm),BL=zL(RL),VL=zL(RL.filter(e=>e.place!==`door`));function HL(e){let t=zI(e.name);return e.control.kind===`inline`?jI(t):ba(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>jI(pL(e.name,n)))},`drop`)}function UL(e){return e===kS}function WL(e){let t=jI(kS);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[WL(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[t,e]};if(e.when===void 0)return{...e,children:[t,...e.children]};let{when:n,children:r,...i}=e;return{...i,children:[t,{kind:`container`,direction:i.direction,when:n,children:r}]}}function GL(e){return KL(e)>0?e:WL(e)}function KL(e){let t=0;for(let n of sb(e))n.kind===`segment`&&UL(n.name)&&(t+=1);return t}function qL(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&UL(e.name)||e.opens!==void 0&&qL(e.opens.body,!0):e.children.some(e=>qL(e,n))}const JL={door:{direction:`horizontal`,content:[jI(QI)],after:[jI(wI),jI(II)]},session:{direction:`vertical`,content:[jI(TI),{kind:`container`,direction:`horizontal`,children:[jI(DI),jI(kI)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[jI(LI)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[jI(tL),...eI.map(e=>jI(aL(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[jI(HI)]},toggles:{direction:`horizontal`,content:[],after:[]}};function YL(e){let{direction:t,content:n,after:r}=JL[e];return{kind:`container`,direction:t,children:[...n,...AL(e),...r]}}function XL(e){return e.kind===`segment`?UL(e.name)?{kind:`container`,direction:`horizontal`,children:[ba(e.name,jS,QL,`above`),jI(SL)]}:e:$L(e)}function ZL(){return{kind:`container`,direction:`vertical`,children:[YL(`door`),{kind:`container`,direction:`horizontal`,children:XM.map(({member:e})=>ba(NI(e),FI(e),YL(e),`drop`))}]}}const QL=ZL();function $L(e){return{...e,children:e.children.map(e=>XL(e))}}function eR(e){let t={variables:{[kS]:Ea(kS,ma),[MS]:{kind:`state`,key:MS,default:`0`}},actions:{[qI]:Da(kS,AS),[MS]:{set:MS,int:!0},[kS]:{do:[qI,...BL]},[nL]:{doctor:`run`},...EI.actions,...OI.actions,...AI.actions,[II]:{save:!0},[JI]:{undo:!0},[XI]:{back:!0},[YI]:{do:[XI,...BL]},[eL]:{redo:!0},[LI]:{preset:`save`},[HI]:{themeDefault:`save`},[RI]:{preset:`delete`,name:`{{ .${xx.preset.effectiveVar} }}`}},segments:{[kS]:{template:`{{ $door := ${wa(kS,Ta(e),Ta(`✖`))} }}{{ if ${Sa(jS)} }}{{ fg (roleTextOn "error" (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+xL},[SL]:{template:CL},[TI]:{template:EI.template},[DI]:{template:OI.template,when:OI.when},[kI]:{template:AI.template,bg:AI.bg,when:AI.when},[QI]:$I,[II]:LL,[HI]:GI,[LI]:{template:`{{ action "${LI}" "+ preset" }}`},[tL]:{template:`{{ action "${nL}" "🩺 doctor" }}`},[wI]:{template:`{{ action "${QN}" "✎ arrange" "✎ done" }}`}}};t.variables[UI]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[WI]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[ZI]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of ML)t.variables[NL(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[MI]=Ea(MI,ma);for(let{member:e,label:n}of XM){t.actions[PI(e)]=Da(MI,e),t.actions[NI(e)]={do:[PI(e),...VL]};let r=kL(e);t.segments[NI(e)]={template:`{{ ${wa(NI(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,OI.variables,jL.variables),nR(t),tR(t),t}function tR(e){for(let t of eI){let n=rI(t.name),r=rL(t.name);for(let t of Object.values(n))e.variables[t]={kind:`state`,key:t,default:``};e.actions[r]={doctor:`fix`,check:t.name};let i=t.takesMark?FF:[];for(let n of i)e.actions[iL(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${iL(t.name,e)}" "${oL[e]}" }}`).join(``);e.segments[aL(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ if ne .${n.reason} "" }} — {{ .${n.reason} }}{{ end }}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${Ky}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function nR(e){for(let t of EL){Object.assign(e.actions,t.control.actions);let n=VI(t.name);e.actions[n]={reset:t.configKey},e.variables[mL(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${mL(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[zI(t.name)]={template:`${t.control.template}${wL[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[pL(t.name,r)]=n})}Object.assign(e.actions,jL.actions),Object.assign(e.variables,_L.variables),Object.assign(e.actions,_L.actions),Object.assign(e.segments,_L.segments);for(let t of $M){let n=dL(t);e.actions[lL(t)]=Da(n.key,n.member),e.segments[cL(t)]={template:`{{ action "${lL(t)}" ${kL(t)(QM[t].trigger)} }}`}}}function rR(e){let{variables:t,actions:n}=sP();Object.assign(e.variables,t),Object.assign(e.actions,n)}function iR(e){let t=eR(e.globals.menuGlyph??`🍫`);rR(t);let n={...e.presets},r=[];for(let t of rS(e.presets)){let{node:i}=oS(e,t),a=XL(GL(i));r.push(a),n[t]={...aS(e.presets,t),root:a}}let i=jM(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const aR=`${TS}live`,oR=[`☐ live`,`☑ live`],sR=`${TS}done`,cR=`${TS}cancel`,lR=`${TS}rewind`,uR=`${TS}changes`,dR=`(gt .${uR} 0)`,fR=`(or ${dR} (gt .${PL} 0))`,pR={variable:aR,key:aR,member:ha};function mR(e){return`${TS}configuring.p${e}`}function hR(e){return`and ${Sa(nP)} (not ${Sa(pR)}) (ne .${mR(e)} "true")`}function gR(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${ZN} "${ya(e)}")`).join(` `)} false }}`}}function _R(e,t,n){return`{{ if ${hR(e)} }}${t}{{ else }}${n}{{ end }}`}const vR=`{{ and ${Sa(nP)} .preset.customized }}`,yR=OS;function bR(e){return new Map([...Cte(e),...SR(e)])}const xR=`${TS}addable`;function SR(e){return new Map([[xR,{members:Object.keys(e.segments).filter(e=>!yR(e)),library:{groups:WN.map(e=>({id:e,label:GN[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function CR(e,t,n){return n.segments[e]={template:t,when:rP,bg:uP},{kind:`segment`,name:e}}function wR(e,t,n){let r=`${TS}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Hv}`}) (action "${r}" "✖") }}`}function TR(e){return`{{ if ${Sa(nP)} }}${e}{{ end }}`}function ER(e,t){return e.reduce((e,t)=>`{{ if and ${Sa(nP)} ${Sa(t)} }}true{{ else }}${e}{{ end }}`,t)}function DR(e){return e.flatMap(e=>[...sb(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function OR(e,t,n){return`${eP}${e}.${t}.${n}`}function kR(e,t,n,r){let i=rb(n),a=`${TS}${e.presetIdent}`,o=tP(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=FM(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:ma},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:ZN,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=OR(e.presetIdent,i,r),l=`${eP}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Db(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=JM(KM(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};e.artifacts.segments[d]={template:f.template};let p=f.list.rows.map((t,n)=>{let r=`${d}.list.${n}`;return e.artifacts.segments[r]={template:t},{kind:`segment`,name:r}});return ba(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${gP}" }}`,ref:{variable:ZN,key:ZN,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const AR=`${TS}label:`;function jR(e){if(e.startsWith(AR)){let t=e.slice(AR.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function MR(e,t,n,r){let i=rb(e),a=NR(n,i,e,t,i),o=Object.fromEntries(Sb.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...ba(a,r.ref,r.body,`drop`,ER([r.ref],`{{ ${hR(n.presetIdent)} }}`)),...Object.keys(o).length>0&&{settings:o},drafts:Object.fromEntries(Sb.map(e=>[e,r.drafts[e]]))}}function NR(e,t,n,r,i){let a=`${AR}${t}:${n.name}`;return e.artifacts.segments[a]={template:`{{ "${ya(i)}" }}`,...r.palette!==void 0&&{palette:r.palette}},a}function PR(e,t,n,r){let i=rb(e),a=n?[LR(r,String(r.posCounter.n++),i,`before`)]:[],o=String(r.posCounter.n++),s=LR(r,o,i,`after`),c=wR(r,o,i),l=r.segments[e.name],u=kR(r,o,e,Cb(l)),d=TR(c),f=TR(u.term);return[...a.map(e=>CR(e.host,e.template,r.artifacts)),{...MR(e,l,r,u),lead:d,trail:f},{...t,when:_R(r.presetIdent,`false`,e.when??`true`),lead:d,trail:f,drafts:u.drafts},CR(s.host,s.template,r.artifacts)]}function FR(e){return s.join(s.basename(s.dirname(e)),s.basename(e))}function IR(e,t,n,r){let i=r.segments[e.name],a=rb(e);return[{kind:`segment`,name:NR(r,`${a}/${r.presetIdent}`,e,i,`${a} · ${FR(t.file)} ${t.entry}`),when:`{{ ${hR(r.presetIdent)} }}`},{...n,when:_R(r.presetIdent,`false`,e.when??`true`)}]}function LR(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${TS}${i}.insert.${t}`,s=`${TS}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:xR,anchor:n,relation:r};let c=NM(o),l=PM(s,o,void 0),u=LM(l),d=IM(l,c);return a.variables[l]={...Ea(l,ma),within:[nP]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=Da(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${Sa({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Hv}`}) $m }}{{ end }}`}}function RR(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!yR(e.name)&&e.insertedBy===void 0),i=e=>RR(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=ob(o,i);if(yR(o.name)){n.push(s);continue}let c={kind:`container`,direction:`horizontal`,children:o.insertedBy===void 0?PR(o,s,a===r,t):IR(o,o.insertedBy,s,t),unit:!0};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[c]}:c)}return{...e,children:n,...e.when!==void 0&&{when:ER(DR(n),_R(t.presetIdent,`true`,e.when))}}}function zR(e,t,n,r,i,a,o){let s=`${TS}${t}.resetLayout`,c=`${TS}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:vR},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},BR(e,o)]}}function BR(e,t){if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t]};let n=e.children.at(-1);return e.direction===`vertical`&&n!==void 0&&(n.kind===`segment`||n.when===void 0)?{...e,children:[...e.children.slice(0,-1),BR(n,t)]}:{...e,children:[...e.children,t]}}function VR(e,t,n,r,i,a){let{node:o}=oS(e,t),s={presetIdent:MM(t),rootKey:LN(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=RR(o,s);return n.variables[mR(s.presetIdent)]=gR(s.configured),zR(c,s.presetIdent,s.rootKey,n,r,i,a)}function HR(e){let t={variables:{},actions:{},segments:{}},n=cP(`${TS}help`,bP,[nP],t);t.variables[aR]=Ea(aR,ma),t.actions[aR]=Da(aR,pR.member),t.segments[aR]={template:Ca(aR,...oR),when:rP};let r={kind:`segment`,name:aR},i=n;t.variables[uR]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[sR]={do:[II,QN]},t.segments[sR]={template:`{{ if ${fR} }}{{ action "${sR}" "✓ save" }}{{ else }}{{ action "${sR}" "✓ done" }}{{ end }}`,when:rP},t.actions[lR]={rewind:!0},t.actions[cR]={do:[lR,QN]},t.segments[cR]={template:`{{ action "${cR}" "↩ cancel" }}`,when:`{{ and ${Sa(nP)} ${dR} }}`};let a=[{kind:`segment`,name:sR},{kind:`segment`,name:cR}],o={...e.presets},s=[];for(let n of rS(e.presets)){let c=VR(e,n,t,a,r,i);s.push(c),o[n]={...aS(e.presets,n),root:c}}let c=jM(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function UR(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function WR(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function GR(e,t,n){let r=ab(e,new Set(n.map(ib).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const KR=/^-?\d+$/;function qR(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function JR(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!KR.test(t))return{ok:!1,reason:`${e} must be an integer, got "${t}"`};let n=t[0]===`-`,r=(n?t.slice(1):t).replace(/^0+/,``);return r===``?{ok:!0,value:`0`}:{ok:!0,value:n?`-${r}`:r}}}function YR(e,t,n){return r=>r?KR.test(r)?{ok:!0,value:String(Math.max(e,Math.min(t,parseInt(r,10))))}:{ok:!1,reason:`${n} must be an integer, got "${r}"`}:{ok:!1,reason:`${n} value is required`}}function XR(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!KR.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i}}return{kind:`int`}}function ZR(e){return e===`config`?`set-config`:`set-state`}function QR(e,t,n){return t.kind===`int`?JR(`menu page "${e}"`):t.kind===`range`?YR(t.min,t.max,`${n} stepper "${e}"`):qR(t.allowed,`${n} "${e}"`,ZR(n))}function $R(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:XR(e,n,t)}))}function ez(e){return e.kind===`int`?`an integer`:e.kind===`range`?`an integer from ${e.min} to ${e.max}`:WM(e.allowed)}function tz(e,t,n,r){let i=new Map(Object.entries(e).map(([e,t])=>[e,t.validate])),a=new Map(Object.entries(e).map(([e,t])=>[e,t.admits])),o=new Set(n.map(e=>e.key)),s=n.filter(t=>t.spec.kind!==`allow-list`||!Object.hasOwn(e,t.key)),c=new Map,l=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of s)if(l.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let u=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...s];for(let{key:t,spec:n}of $R(u,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,QR(t,n,r)),a.set(t,ez(n)),n.kind===`range`&&c.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},verdict(e,t){if(!o.has(e))return{kind:`held`};let n=i.get(e)(t);return n.ok&&n.value===t?{kind:`held`}:{kind:`foreign`,admits:a.get(e)}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>c.get(e)??null}}function nz(e,t,n){let r=[],i=0,a=(0,X.createAtom)(`${t}.keyspace`),o=new WeakMap,s=()=>{i++,a.reportChanged()};return{register(n,i){let a={key:n,allowed:i};tz(e,[a],[],t),r.push(a),s();let o=!0;return()=>{o&&(o=!1,r.splice(r.indexOf(a),1),s())}},gateFor(s){a.reportObserved();let c=o.get(s);if(c?.epoch===i)return c.gate;let l=tz(e,r,n(s),t);return o.set(s,{epoch:i,gate:l}),l}}}function rz(){return nz({},`config`,sz)}function iz(e,t){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:mS(e.from,t).members}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[UR({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[UR({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:mS(e.insertSegmentFrom,t).members.map(t=>UR({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function az(e){let t=new Set;for(let n of Object.values(e.actions)){`reset`in n&&t.add(n.reset);let e=`persist`in n?VN(n.persist):null;e?.scope===`preset-root`&&t.add(LN(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function oz(e){let t=bR(e);return[...az(e),...Object.values(e.actions).flatMap(e=>iz(e,t))]}function sz(e){return $R(oz(e),`config`)}const cz=gy(),lz=new Set(cz),uz=new Set(Ry),dz=e=>e?lz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${cz.join(`, `)})`}:{ok:!1,reason:`theme name is required`},fz=e=>e?uz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Ry.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},pz=new Set([`1`,`true`]),mz=new Set([``,`0`,`false`]),hz={endcaps:{validate:fz,admits:WM(Ry)},theme:{validate:dz,admits:WM(cz,`themes`)},"toolbar-expanded":{validate:e=>pz.has(e)?{ok:!0,value:`1`}:mz.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false, or empty), got "${e}"`},admits:`"1" for true or "" for false`}};function gz(){return nz(hz,`state`,yz)}function _z(e,t){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:mS(e.from,t).members}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function vz(e){let t=bR(e);return Object.values(e.actions).flatMap(e=>_z(e,t))}function yz(e){return $R(vz(e))}function bz(e){let t=gz(),n=rz();for(let{key:n,allowed:r}of e.state)t.register(n,r);for(let{key:t,allowed:r}of e.config)n.register(t,r);return{state:t,config:n}}const xz=`update.dismissed`,Sz=`updateNotice`,Cz=xx.updateNotice.sessionKey;function wz(){return bz({config:[{key:Sz,allowed:[`false`]}],state:[{key:Cz,allowed:[`false`]},{key:xz,allowed:[]}]})}function Tz(e,t,n,r){let i;try{i=e.readFileSync(t)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${t}: ${e.message}`}}let a;try{a=JSON.parse(i)}catch(e){return{kind:`failed`,reason:`${t} is not JSON: ${e.message}`}}let o=r(a);return o.kind===`ok`?o:{kind:`failed`,reason:`${t} ${o.reason}`}}function Ez(e,t,n,r,i){let a=s.join(t,n);return Dz(e,a,()=>Tz(e,a,r,i))}function Dz(e,t,n){return{read:n,update:r=>{let i=n();if(i.kind===`failed`)return i;let a=r(i.value);return a!==i.value&&Cr(e,t,`${JSON.stringify(a,null,2)}\n`),{kind:`ok`,value:a}}}}function Oz(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:jz(t.segments,kz(t.segments,e.segments??{})),root:Jx(e.root??Hx,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:jz(t.presets,Az(t.presets,e.presets??{})),themeDefaults:jz(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function kz(e,t){let n=(t,n,r)=>r[n]===void 0?r:{...r,[n]:{...e[t]?.[n],...r[n]}};return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,n(e,`partials`,n(e,`settings`,t))]))}function Az(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.globals===void 0?n:{...n,globals:{...e[t]?.globals,...n.globals}}]))}function jz(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const Mz=new Map([[`gitTaculous`,{kind:`built-in`,to:`gitaculous`}],[`git`,{kind:`built-in`,to:`gitaculous`}],[`settings.menu`,{kind:`built-in`,to:`candybar.menu`}],[`ticket`,{kind:`plugin`,to:`plugins.lit.ticket`,source:`promptctl/links-issue-tracker`}],[`ceiling`,{kind:`removed`,why:`the program it showed draws it through a cc-candybar plugin of its own now — delete this reference, or place that plugin's segment`}],[`themeSwitcher`,{kind:`removed`,why:'the settings menu\'s 🎨 theme control steps themes — delete this reference, or write your own `{{ carousel "apply" "open" "label" }}`'}]]);function Nz(e){let t=Mz.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`;case`removed`:return` (the built-in segment "${e}" was removed: ${t.why})`}}function Pz(e,t,n,r){return n.cache===void 0?(e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${pb.join(`, `)})`,line:J(e.source,t.split(`.`))}),null):Lz(e,`${t}.cache`,n.cache)}function Fz(e){return{required:!0,json:Rz(),parse:(t,n,r,i)=>Pz(t,n,i,e)??void 0}}const Iz={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Bz(n)?{ttl:n}:Hb(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${Y(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return Hb(e,t,`cache.watch_file must be a path string, got ${Y(n)}`);let r=Yb(`cache.watch_file`,n);return r===null?{watch_file:n}:Hb(e,t,r)}},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:Hb(e,t,`cache.depends_on must be an array of variable-name strings, got ${Y(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:Hb(e,t,`cache.key must be a non-empty template string, got ${Y(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:Hb(e,t,`cache.never must be the literal boolean true, got ${Y(n)}`)}}};function Lz(e,t,n){return Ub(e,Iz,t,n)}function Rz(){return Qb(Iz)}const zz=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Bz(e){return zz.test(e)}const Vz=new Map([[`session.budget.amount`,{segment:`session`,setting:`budget`}],[`session.budget.warningThreshold`,{segment:`session`,setting:`warnAt`}],[`today.budget.amount`,{segment:`today`,setting:`budget`}],[`today.budget.warningThreshold`,{segment:`today`,setting:`warnAt`}],[`block.budget.heatThreshold`,{segment:`block`,setting:`warnAt`}],[`block.budget.warningThreshold`,{segment:`block`,setting:`errorAt`}],[`weekly.budget.heatThreshold`,{segment:`weekly`,setting:`warnAt`}],[`weekly.budget.warningThreshold`,{segment:`weekly`,setting:`errorAt`}],[`burn.eta.errorMinutes`,{segment:`burnrate`,setting:`errorWithin`}],[`burn.eta.warnMinutes`,{segment:`burnrate`,setting:`warnWithin`}]]);function Hz(e){return`it became the "${e.setting}" setting of each "${e.segment}" placement — set it on the placement where a row places "${e.segment}" ({ seg: "${e.segment}", settings: { ${e.setting}: <value> } }), or redeclare segments.${e.segment}.settings.${e.setting} with the default every placement should start from`}function Uz(e){let t=Vz.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${Hz(t)}`}function Wz(e){let t=Vz.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${Hz(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const Gz=new Map([[`git.timeSinceCommit`,`the payload stores the commit's date as "git.committedAt" (epoch seconds), and the bundled template variable "git.timeSinceCommit" computes its age at the draw: drop this declaration`],[`block.etaMinutes`,`the bundled template variable "block.etaMinutes" computes it at the draw: drop this declaration`],[`weekly.etaMinutes`,`the bundled template variable "weekly.etaMinutes" computes it at the draw: drop this declaration`]]),Kz=new Map([[`branch`,{read:`.git.branch`,declare:{kind:`input`,path:`git.branch`,default:``},note:`when HEAD is on no branch it reads "detached", where this kind read ""`}],[`sha`,{read:`.git.sha`,declare:{kind:`input`,path:`git.sha`,default:``}}],[`dirty`,{read:`(ne .git.status "clean")`,declare:{kind:`template`,template:`{{ ne .git.status "clean" }}`,type:`boolean`}}],...[`ahead`,`behind`,`stash`].map(e=>[e,{read:`.git.${e}`,declare:{kind:`input`,path:`git.${e}`,type:`number`,default:0}}])]);function qz(e){let t=e=>typeof e==`string`&&e.includes(`"`)&&!e.includes(`'`)?`'${e}'`:JSON.stringify(e);return`{ ${Object.entries(e).map(([e,n])=>`${e}: ${t(n)}`).join(`, `)} }`}function Jz(e){let t=`kind "git" is retired: every git fact is an input over the payload's git lane, which the bundled default already declares — drop this declaration and`,n=typeof e.field==`string`?Kz.get(e.field):void 0;if(n===void 0){let e=[...Kz.values()].map(({read:e})=>e);return`${t} read whichever of ${e.slice(0,-1).join(`, `)} or ${e.at(-1)} it stood for, where it was read`}let r=n.note===void 0?``:` (${n.note})`;return`${t} read ${n.read} where it was read${r}, or declare ${qz(n.declare)} under a name of your own`}const Yz=new Map([[`HOME`,`home`],[`USER`,`host.user`],[`LOGNAME`,`host.user`],[`HOSTNAME`,`host.name`]].map(([e,t])=>[e,{read:`.${t}`,declare:{kind:`input`,path:t,default:``}}]));function Xz(e){let t=`kind "env" is removed${typeof e.name==`string`?` (this one read $${e.name})`:``}: the renderer's environment belongs to whichever shell spawned it, not to the session it draws for, so an env variable was never a session fact — drop this declaration`,n=typeof e.name==`string`?Yz.get(e.name):void 0;return n===void 0?`${t}; a value the payload lacks is read from a file by a "file" source or computed by a "shell" source, and not by echoing the variable there, since a "shell" source runs in the renderer too`:`${t} and read ${n.read} where it was read, or declare ${qz(n.declare)} under a name of your own`}function Zz(e,t,n){if(n===void 0)return{};if(!Qy(n))return e.issues.push({path:t,message:`${t} must be an object, got ${Lb(n)}`,line:J(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=$ee(e,yB,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function Qz(){return{required:!0,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.value;if(typeof i!=`string`&&typeof i!=`number`&&typeof i!=`boolean`){e.issues.push({path:`${t}.value`,message:`literal value must be string|number|boolean, got ${Lb(i)}`,line:J(e.source,t.split(`.`))});return}return i}}}function $z(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Zee(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const eB={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:Hb(e,t,`parse.text must be the literal boolean true, got ${Y(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?tB(e,t,n):Hb(e,t,`parse.regex must be a pattern string, got ${Y(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:Hb(e,t,`parse.json must be the literal boolean true, got ${Y(n)}`)}}};function tB(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return Hb(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:Hb(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function nB(){return{required:!1,json:Qb(eB),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:J(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:Ub(e,eB,`${t}.parse`,r.parse)??void 0)}}function rB(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>Qy(r.parse)&&`json`in r.parse?iB(e,t,r.default):Pb(e,t,r,`default`)}}function iB(e,t,n){if(n!==void 0)return aB(n)?n:Hb(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${Y(n)}`)??void 0}function aB(e){return e!==null&&fw(e)}const oB={value:Qz(),default:Gb()};function sB(){let e=Jb();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:Gz.get(a);return o===void 0?a:Hb(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const cB={path:sB(),type:Xb([`string`,`number`,`boolean`]),default:$z()},lB={path:ite(),readMode:Xb([`whole`,`first-line`]),parse:nB(),cache:Fz(`file`),default:rB()},uB={command:Jb(),parse:nB(),cache:Fz(`shell`),default:rB()};function dB(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const fB={template:Jb(),type:Xb([`string`,`number`,`boolean`]),default:$z()},pB=dB(`a template variable recomputes whenever a variable it reads changes`),mB={layout:Jb(),default:Gb()},hB=dB(`a time variable reads the instant its render is drawn at`),gB={key:Jb(),default:Gb()},_B=`kind`;function vB(e,t,n={}){return{...ete(_B,e,t),parse:(r,i,a)=>{zb(r,n,i,a);let o=Bb(r,t,i,a);return o===null?null:{kind:e,...o}}}}const yB={tag:_B,noun:`source kind`,memberNoun:`variable`,arms:{literal:vB(`literal`,oB),input:vB(`input`,cB),file:vB(`file`,lB),shell:vB(`shell`,uB),template:vB(`template`,fB,pB),time:vB(`time`,mB,hB),state:vB(`state`,gB)},retired:{git:Jz,env:Xz}};function bB(){return ste(yB)}function xB(){return{type:`object`,additionalProperties:bB()}}const SB=/^[A-Za-z_][A-Za-z0-9_]*$/,CB={pattern:SB.source},wB={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},TB={type:`object`,additionalProperties:!1,required:[`label`,`domain`,`default`],properties:{label:{type:`string`,pattern:`^[^\\n\\r]+$`},domain:{anyOf:[{const:`bool`},{type:`array`,items:{type:`string`,pattern:`^[^/\\n\\r]+$`},minItems:1,uniqueItems:!0},{type:`object`,additionalProperties:!1,required:[`min`,`max`],properties:{min:{type:`integer`},max:{type:`integer`},step:{type:`integer`,minimum:1},atLeast:{type:`string`,...CB}}}]},default:wB}},EB=[`label`,`domain`,`default`],DB=[`min`,`max`,`step`,`atLeast`];function OB(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function kB(e,t,n){if(n===`bool`)return`bool`;if(Array.isArray(n)){let r=n.filter(e=>typeof e==`string`);if(n.length===0||r.length!==n.length)return OB(e,t,`a list domain must be a non-empty list of words, got ${JSON.stringify(n)}`);if(new Set(r).size!==r.length)return OB(e,t,`a list domain names each word once, got ${JSON.stringify(n)}`);let i=r.filter(e=>e===``||e.includes(`/`)||/[\n\r]/.test(e));return i.length>0?OB(e,t,`a list domain's words must be non-empty, slash-free, and newline-free — configure mode writes each on the set-state wire — got ${JSON.stringify(i)}`):r}if(Qy(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!DB.includes(e)).length===0&&Number.isInteger(r)&&Number.isInteger(i)&&r<=i&&Number.isInteger(a)&&a>=1&&(o===void 0||typeof o==`string`)?{min:r,max:i,step:a,...o!==void 0&&{atLeast:o}}:OB(e,t,`a range domain is { min, max, step?, atLeast? } with integers min ≤ max, a whole step ≥ 1, and atLeast naming another range setting, got ${JSON.stringify(n)}`)}return OB(e,t,`domain must be "bool", a list of words, or { min, max }, got ${Y(n)}`)}function AB(e,t,n){if(!Qy(n))return OB(e,t,`${t} must be { label, domain, default }, got ${Lb(n)}`);for(let r of Object.keys(n))EB.includes(r)||OB(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${EB.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||OB(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${Y(r)}`);let a=kB(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!jB(n.default)||!Eb(o,n.default)?OB(e,`${t}.default`,`default must be ${kb(o)}, got ${Y(n.default)}`):o}function jB(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const MB={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${bb}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function NB(e){return Sb.includes(e)}function PB(){return{required:!1,json:{type:`object`,propertyNames:{...CB,not:{enum:[...Sb]}},additionalProperties:TB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Qy(i))return OB(e,a,`${a} must be an object of name → { label, domain, default }, got ${Lb(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!SB.test(t)){OB(e,`${a}.${t}`,`setting name "${t}" is read as .settings.${t} in a template, so it must be an identifier (letters, digits, _; not starting with a digit)`);continue}if(NB(t)){OB(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${MB[t]}`);continue}let r=AB(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const FB=DS.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function IB(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${FB})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!OS(i)?i:OB(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${DS.map(e=>`"${e}"`).join(`, `)} namespaces, got ${Y(i)}`)}}}function LB(){return{required:!1,json:{type:`object`,propertyNames:CB,additionalProperties:wB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Qy(i))return OB(e,a,`a placement's "settings" must be an object of setting name → value, got ${Lb(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))jB(n)?o[t]=n:OB(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${Lb(n)}`);return o}}}function RB(e){return new Set(Object.keys(e.segments).filter(e=>!OS(e)))}function zB(e,t,n){if(t===void 0)return{};if(!Qy(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${Lb(t)}`,line:J(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=Rb(e,n.has(i)?YB:JB,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function BB(e,t,n,r){let i=r[n];if(typeof i==`string`)return i;if(Array.isArray(i)){let r=!0,a=[];for(let[o,s]of i.entries()){if(typeof s==`string`){a.push(s);continue}r=!1,e.issues.push({path:`${t}.${n}[${o}]`,message:`${t}.${n}[${o}] must be a string, got ${Lb(s)}`,line:J(e.source,[...t.split(`.`),n])})}return r?a.join(``):void 0}e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be a string or an array of strings, got ${Lb(i)}`,line:J(e.source,[...t.split(`.`),n])})}const VB={anyOf:[{type:`string`},{type:`array`,items:{type:`string`}}]};function HB(){return{required:!0,json:VB,parse:(e,t,n,r)=>r[n]===void 0?Hb(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own${Nz(t.slice(9))}`)??void 0:BB(e,t,n,r)}}function UB(){return{required:!1,json:VB,parse:(e,t,n,r)=>r[n]===void 0?void 0:BB(e,t,n,r)}}function WB(){return{required:!1,json:{type:`object`,additionalProperties:VB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;if(!Qy(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be an object, got ${Lb(i)}`,line:J(e.source,[...t.split(`.`),n])});return}let a=Object.create(null);for(let r of Object.keys(i)){let o=BB(e,`${t}.${n}`,r,i);o!==void 0&&(a[r]=o)}return a}}}function GB(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${Y(i)}`,line:J(e.source,[...t.split(`.`),n])})}}}}function KB(){return{required:!1,json:xB(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return Zz(e,`${t}.${n}`,i)}}}const qB={template:HB(),description:Gb(),group:Xb(UN),width:GB(),justify:Xb(Vee),truncate:Xb(Hee),bg:Gb(),fg:Gb(),when:Gb(),palette:rte(),vars:KB(),settings:PB(),missingData:Xb(_b),partials:WB()},JB={noun:`segment key`,fields:qB},YB={noun:`segment key`,fields:{...qB,template:UB()}};function XB(e,t){if(t===void 0)return{};if(!Qy(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${Lb(t)}`,line:J(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${Y(i)}`,line:J(e.source,[`helpers`,r])});continue}n[r]=i}return n}function ZB(e,t,n){if(t===void 0)return{};if(!Qy(t))return Z(e,`actions`,`actions must be an object, got ${Lb(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=QB(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function Z(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function QB(e,t,n,r){if(!Qy(n))return Z(e,t,`${t} must be an action object, got ${Lb(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let i=_S.filter(e=>e in n);return i.length===1?eV(r)[i[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${_S.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function $B(e){return e===`<default>`?{dir:null}:s.isAbsolute(e)?{dir:s.dirname(e)}:{text:e}}const eV=e=>({set:(e,t,n)=>IV(e,t,n,`set`,MV),persist:(e,t,n)=>IV(e,t,n,`persist`,NV),copy:tV(`copy`),open:tV(`open`),reset:nV,undo:iV(`undo`),redo:iV(`redo`),back:iV(`back`),rewind:iV(`rewind`),save:iV(`save`),preset:aV,themeDefault:oV,doctor:cV,slash:lV,run:fV(e),do:pV});function tV(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Nb(t,n,r,e);return i===null?null:{[e]:i}}}function nV(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=mV(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}const rV={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,back:`it steps the session's navigation history`,rewind:`it steps the session's settings history back to where edit mode opened`,save:`it saves the session's unsaved settings`};function iV(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Z(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${rV[e]}), got ${Y(r[e])}`),null)}}function aV(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${Y(r)}`),null;if(r===`save`)return{preset:`save`};let a=Nb(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function oV(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Z(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${Y(n.themeDefault)}`),null)}const sV={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function cV(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(sV,r),a=i?sV[r]:[...new Set(Object.values(sV).flat())];for(let r of Object.keys(n))a.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Z(e,`${t}.doctor`,`doctor must be ${Object.keys(sV).map(e=>`"${e}"`).join(`, `)}, got ${Y(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?Ire:eI;if(typeof o!=`string`||!s.some(e=>e.name===o))return Z(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${Y(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return FF.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${FF.map(e=>`"${e}"`).join(` or `)}, got ${Y(c)}`),null)}function lV(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=fI(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}const uV=[`run`,`env`,`refreshes`],dV=/^[A-Za-z_][A-Za-z0-9_]*$/;function fV(e){return(t,n,r)=>{for(let e of Object.keys(r))uV.includes(e)||Z(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${uV.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&Z(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${Y(a)}`);let o=r.env??{};(!Qy(o)||Object.entries(o).some(([e,t])=>!dV.test(e)||typeof t!=`string`))&&Z(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${Y(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&Z(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${Y(s)}`),`dir`in e||Z(t,`${n}.run`,`a run action runs in the directory of the file that declares it, and ${e.text} is no file`),t.issues.length>i||!(`dir`in e)?null:{run:a,env:o,refreshes:s,cwd:e.dir}}}dV.source;function pV(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${Y(r)}`),null):{do:r}}function mV(e,t,n,r,i,a){let o=Nb(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Z(e,s,i),null):o.includes(`/`)?(Z(e,s,a(o)),null):o}const hV={set:`the SessionState key to write`,persist:`the config globals field to write`};function gV(e,t,n,r){let i=hV[r],a=mV(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);return a===null?null:r===`set`&&a.startsWith(eP)?(Z(e,`${t}.set`,`set key "${a}" is a placement's draft, under "${eP}" — the setting control configure mode synthesizes is its only writer, so its read can trust what it holds. Write a key outside it`),null):{[r]:a}}function _V(e){return e===`set`?`set-state`:`set-config`}const vV={to:LV(`set`)},yV={to:LV(`persist`)},bV={from:RV(`set`)},xV={from:RV(`persist`)},SV={min:UV(),max:UV(),by:UV()},CV={int:BV()},wV={cycle:zV(`set`)},TV={cycle:zV(`persist`)},EV={removeSegment:VV(`removeSegment`)},DV={insertSegment:VV(`insertSegment`),anchor:VV(`anchor`),relation:HV()},OV={insertSegmentFrom:RV(`persist`),anchor:VV(`anchor`),relation:HV()},kV={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},AV={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function jV(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>Bb(e,t,n,r),c=Zb(t);return{detect:a,allowed:[...o,...i],label:i.join(`/`),json:{type:`object`,properties:{...Object.fromEntries(o.map(e=>[e,{type:`string`}])),...c.properties},required:[...o,...c.required??[]],additionalProperties:!1},parse:n.length?tte(s,...n):s}}const MV=[jV(`set`,vV),jV(`set`,bV),jV(`set`,SV,[kV,AV]),jV(`set`,CV),jV(`set`,wV)],NV=[jV(`persist`,yV),jV(`persist`,xV),jV(`persist`,SV,[kV,AV]),jV(`persist`,TV),jV(`persist`,EV),jV(`persist`,DV,[],[`insertSegment`]),jV(`persist`,OV,[],[`insertSegmentFrom`])];function PV(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"endcaps"/"styles", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function FV(e){let t=PV(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function IV(e,t,n,r,i){let a=gV(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${FV(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Z(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function LV(e){let t=_V(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>mV(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function RV(e){let t=_V(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${Y(o)}`)}}}function zV(e){let t=_V(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Z(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${Lb(o)}`);return}let c=o;if(c.length<2){Z(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Z(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Z(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Z(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function BV(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${Y(r[n])}`);return}return!0}}}function VV(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Nb(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Z(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Z(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function HV(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${Y(i)}`);return}return i}}}function UV(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${Y(i)}`);return}return i}}}function WV(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const GV=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),KV=`plugin.json5`,qV=/^[a-z][a-z0-9_]*$/;function JV(e,t){let n=s.basename(s.dirname(e));return qV.test(n)?{path:e,scope:t,name:n}:{path:e,scope:t,name:void 0}}function YV(e,t){return t.map(t=>{try{return{...t,read:{kind:`read`,text:e.readFileSync(t.path),dir:e.realpathSync(s.dirname(t.path))}}}catch(e){return{...t,read:{kind:`unreadable`,reason:e.message}}}})}function XV(e){return`${e}.data`}function ZV(e){return`${e}.json`}function QV(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:$V(e)}}}function $V(e){return e instanceof Ab?e.issues.map(e=>e.path===``||e.message.includes(e.path)?e.message:`${e.path}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}function eH(e,t,n,r){return e.map(e=>JV(TP(s.dirname(t),e,r),n))}function tH(e,t,n,r){let i=new Map;return e.reduce((e,{read:n,...a})=>{let o=a.path,c=a.name===void 0?void 0:CC(a),l=(t,n)=>{let r=new Map(e.rendering);return c!==void 0&&n!==e.config&&r.delete(c),{...e,config:n,rendering:r,dropped:[...e.dropped,{...a,reason:t}]}};if(s.basename(o)!==`plugin.json5`){let t=`a plugin is a folder holding its ${KV}, and the folder's name is the plugin's: move this file to <dir>/<name>/${KV} and list that`;return l(t,c===void 0?e.config:rH(nH(e.config,c),c,{...a,reason:t}))}if(a.name===void 0||c===void 0)return l(`its folder "${s.basename(s.dirname(o))}" is not a plugin name (one matching ${qV}: it prefixes every name the plugin declares)`,e.config);let u=i.get(c);if(u!==void 0)return l(`plugin "${a.name}" is already listed, from ${u}`,e.config);i.set(c,o);let d=nH(e.config,c),f=QV(()=>{if(n.kind===`unreadable`)throw Error(n.reason);let i=Oz(lH(o,a,{source:n.text,json:Na.default.parse(n.text),dir:n.dir},t),d);return wH(o,c,i),r(i,c,d!==e.config),i});if(f.ok)return{...e,config:f.value,loaded:[...e.loaded,a],rendering:new Map([...e.rendering,[c,a]])};let p={...a,reason:f.reason};return l(f.reason,rH(d,c,p))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function nH(e,t){let n=wC(t),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n(e)));return[e.variables,e.segments,e.helpers,e.actions].some(e=>Object.keys(e).some(n))?{...e,variables:r(e.variables),segments:r(e.segments),helpers:r(e.helpers),actions:r(e.actions)}:e}function rH(e,t,n){return{...e,variables:{...e.variables,[t]:{kind:`dropped`,reason:WV(n),definition:n.path}}}}function iH(e){let t=Object.entries(e.variables).flatMap(([e,t])=>t.kind===`dropped`?[{ns:e,definition:t.definition,notice:t.reason}]:[]);return e=>t.find(({ns:t})=>wC(t)(e))}function aH(e,t){let n=iH(e.config),r=[...e.rendering.keys()].map(wC),i=[...t,...e.dropped].filter(e=>e.name===void 0);return e=>{let t=EC(e);if(t===void 0)return[];let a=n(e);return a===void 0?r.some(t=>t(e))?[]:i.filter(e=>e.scope===t).map(e=>({definition:e.path,notice:WV(e)})):[{definition:a.definition,notice:a.notice}]}}function oH(e,t,n){let r=rS(e.presets).flatMap(t=>[...sb(oS(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),i=[...new Set([...r.map(e=>e.name),...n,...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),a=Object.fromEntries(i.map(({name:e,cause:t})=>[e,sH(e,t.map(e=>e.notice),r.filter(t=>t.name===e))])),o=iH(e),s=Object.values(e.variables).some(e=>e.kind===`dropped`),c=s?Object.values(e.segments).flatMap(e=>[...pH.flatMap(t=>e[t]===void 0?[]:[e[t]]),...Object.values(e.partials??{})]):[],l=s?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],u=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:o(e);return n===void 0?[]:[[e,n]]}),d=u([...c.flatMap(t=>qC(t,e.helpers).map(e=>e.name)),...l],e.actions),f=u(c.flatMap(t=>[...tw(t,e.helpers)]),e.helpers),p=Object.entries(e.actions).flatMap(([t,n])=>{if(!(`run`in n))return[];let r=new Map(u(n.refreshes,e.variables));return r.size===0?[]:[{name:t,action:{...n,refreshes:n.refreshes.filter(e=>!r.has(e))},causes:[...r.values()]}]}),m=new Set([...i.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...d,...f].map(([,e])=>e.definition),...p.flatMap(({causes:e})=>e.map(e=>e.definition))]);return{config:{...e,segments:{...e.segments,...a},actions:{...e.actions,...Object.fromEntries(p.map(({name:e,action:t})=>[e,t])),...Object.fromEntries(d.map(([e,{ns:t}])=>[e,{copy:`{{ .${t} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(f.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:m}}function sH(e,t,n){let r=`⚠ ${e}: ${t.join(`; `)}`,i=new Map;for(let e of n)for(let[t,n]of Object.entries(e.settings??{})){let e=i.get(t);i.set(t,e===void 0?[n]:[...e,n])}let a=Object.fromEntries([...i].map(([e,t])=>[e,cH(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function cH(e,t){let[n]=t,r=t.filter(e=>typeof e==`number`);return typeof n==`boolean`?{label:e,domain:`bool`,default:n}:typeof n==`number`?{label:e,domain:{min:Math.min(...r),max:Math.max(...r),step:1},default:n}:{label:e,domain:[...new Set(t.map(String))],default:n}}function lH(e,t,{source:n,json:r,dir:i},{checkout:a,home:o}){let c=CC(t),l=[],u=()=>{throw new Ab(e,l)};if(!Qy(r))return l.push({path:``,message:`a plugin definition must be an object, got ${Lb(r)}`}),u();for(let t of Object.keys(r))GV.has(t)||l.push({path:t,message:t===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${s.basename(s.dirname(e))}") — remove "plugin"`:`a plugin definition may not declare "${t}". Expected only: ${[...GV].join(`, `)}`});let d=r.data===void 0?void 0:DH(r.data,e,a,o,l),f=r.sources===void 0?{}:CH(r.sources,i,l);if(l.length>0)return u();let p={source:n,issues:l,allowedPalettes:new Set(gy()),groups:[],unplaced:[],inherited:[]},m=d===void 0?{}:Zz(p,`data`,{[XV(c)]:{kind:`file`,path:d,parse:{json:!0},cache:{watch_file:d},default:{}}}),h=Zz(p,`variables`,r.variables);for(let[e,t]of[[`variables`,Object.keys(h)],[`sources`,Object.keys(f)]])t.includes(`data`)&&l.push({path:`${e}.data`,message:`"data" names the plugin's data file (.${XV(c)}), declared by the definition's own "data" key: give this ${e===`sources`?`source`:`variable`} another name`});for(let e of Object.keys(f))Object.hasOwn(h,e)&&l.push({path:`sources.${e}`,message:`source "${e}" and variable "${e}" are one name (.${c}.${e}): give one of them another name`});let g={variables:{...m,...gH(c,f),...gH(c,Object.fromEntries(Object.entries(h).map(([e,t])=>[e,vH(c,t)])))},segments:gH(c,yH(c,zB(p,r.segments,new Set))),helpers:gH(c,XB(p,r.helpers)),actions:gH(c,bH(c,ZB(p,r.actions,{dir:i})))};l.push(...mH(g,t));let _=uH(c,g);for(let[e,t]of hH(_))try{KN.parse(t)}catch(t){l.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return l.length>0&&u(),_}function uH(e,t){let n=t=>rw(t,TC,e),r=t=>wC(`self`)(t)?`${e}${t.slice(4)}`:t,i=(e,t)=>Object.fromEntries(Object.entries(e??{}).map(([e,n])=>[e,t(n)]));return{...t,variables:i(t.variables,e=>dH(hb(e,n),r)),segments:i(t.segments,e=>({...e,...Object.fromEntries(pH.flatMap(t=>e[t]===void 0?[]:[[t,n(e[t])]])),...e.partials!==void 0&&{partials:i(e.partials,n)},...e.vars!==void 0&&{vars:i(e.vars,e=>dH(hb(e,n),r))}})),helpers:i(t.helpers,n),actions:i(t.actions,e=>fH(bS(e,n),r))}}function dH(e,t){return mb(e)&&`depends_on`in e.cache?{...e,cache:{depends_on:e.cache.depends_on.map(t)}}:e}function fH(e,t){let n=`segments.`,r={...e};`do`in e&&(r.do=e.do.map(e=>t(e,`do`)));for(let n of[`removeSegment`,`insertSegment`,`anchor`])n in e&&(r[n]=t(e[n],n));return`persist`in e&&e.persist.startsWith(n)&&(r.persist=n+t(e.persist.slice(9),`persist`)),r}const pH=[`template`,`bg`,`fg`,`when`];function mH(e,t){let n=e.helpers??{},r=SC.filter(e=>e!==t.scope).map(e=>({scope:e,ns:CC({scope:e,name:t.name})})),i=new Map,a=(e,n,a)=>{let o=r.find(({ns:e})=>wC(e)(n));if(o===void 0)return;let s=a?`.`:``;i.set(`${e}\0${n}`,{path:e,message:`${e} names ${s}${n}, this plugin under "${o.scope}", but it loads as ${CC(t)}: a plugin names itself without its scope — write ${s}${TC}${n.slice(o.ns.length)}`})},o=[...[...hH(e)].filter(([e])=>!e.startsWith(`helpers.`)),...Object.entries(n).map(([e,t])=>[`helpers.${e}`,t])];for(let[e,t]of o){for(let[r,i]of UC(t,n))i===null&&a(e,r,!0);for(let{name:r,via:i}of qC(t,n))i===null&&a(e,r,!1);for(let n of tw(t,{}))a(e,n,!1)}for(let[t,n]of Object.entries(e.actions??{}))fH(n,(e,n)=>(a(`actions.${t}.${n}`,e,!1),e));let s=[...Object.entries(e.variables??{}).map(([e,t])=>[`variables.${e}`,t]),...Object.entries(e.segments??{}).flatMap(([e,t])=>Object.entries(t.vars??{}).map(([t,n])=>[`segments.${e}.vars.${t}`,n]))];for(let[e,t]of s)if(mb(t)&&`depends_on`in t.cache)for(let n of t.cache.depends_on)a(`${e}.cache.depends_on`,n,!1);return[...i.values()]}function*hH(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of gb(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of pH){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[e,r]of Object.entries(n.partials??{}))yield[`segments.${t}.partials.${e}`,r];for(let[e,r]of Object.entries(n.vars??{}))for(let[n,i]of gb(r))yield[`segments.${t}.vars.${e}.${n}`,i]}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))for(let[e,r]of yS(n))yield[`actions.${t}.${e}`,r]}function gH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,n]))}function _H(e,t){return`${e}.${t}`}function vH(e,t){return t.kind===`state`?{...t,key:_H(e,t.key)}:t}function yH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.vars===void 0?n:{...n,vars:Object.fromEntries(Object.entries(n.vars).map(([t,n])=>[t,vH(e,n)]))}]))}function bH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:_H(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>_H(e,t))}:n]))}const xH=qV,SH={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function CH(e,t,n){if(!Qy(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${Lb(e)}`}),{};let r=s.join(t,`session`),i=JSON.stringify(SH),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!xH.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${xH}: it is the last segment of .<scope>.<plugin>.${t})`});continue}let s=EH(o,SH,e);for(let{field:e,is:t}of s)n.push({path:e,message:`${e} ${t}: what is built is a source ${i} — a session's JSON file in the plugin's managed storage, re-read when it changes`});s.length===0&&(a[t]={kind:`source`,storage:r})}return a}function wH(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=TH(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=wC(t),a=[...r].filter(([,e])=>e.length>1&&e.some(i)).map(([e,n])=>({path:`sources.${n.find(i).slice(`${t}.`.length)}`,message:`sources ${n.map(e=>`.${e}`).join(` and `)} read the same file, ${e}: a session's file is one document, read by one source`}));if(a.length>0)throw new Ab(e,a)}function TH(e){return s.join(e.storage,ZV(`<session id>`))}function EH(e,t,n){return!Qy(t)||!Qy(e)?JSON.stringify(e)===JSON.stringify(t)?[]:[{field:n,is:`is ${JSON.stringify(e)}`}]:[...new Set([...Object.keys(t),...Object.keys(e)])].flatMap(r=>{let i=`${n}.${r}`;return Object.hasOwn(t,r)?Object.hasOwn(e,r)?EH(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function DH(e,t,n,r,i){if(typeof e==`string`&&e!==``)return TP(s.dirname(t),e,r);if(Qy(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(s.isAbsolute(t)||t.startsWith(`~`)||s.normalize(t).split(s.sep)[0]===`..`){i.push({path:`data.checkout`,message:`data.checkout "${t}" must be a path inside the checkout, relative to its root (like ".lit/statusline.json"): no absolute path, "~" or ".."`});return}if(n===null){i.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return s.resolve(n.root,t)}if(Qy(e)&&`project`in e){i.push({path:`data.project`,message:`data: { project } is now data: { checkout }: the same path, relative to the root of the git checkout the session works in (a linked worktree is its own checkout)`});return}i.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { checkout: "<path>" } relative to the root of the session's checkout`})}function OH(e,t){let n=[...[...e.dataDirs].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),kH(e)];return[...n.filter((e,t)=>n.lastIndexOf(e)===t).map(e=>({dir:e,scope:`plugins`})),...t===null?[]:[{dir:s.join(t,AH),scope:`repo`}]]}function kH(e){return s.join(e.dataHome,`cc-candybar`,`plugins`)}const AH=s.join(`.cc-candybar`,`plugins`);function jH(e,t,n){let r=OH(t,n),i=new Map,a=[],o=[];for(let{dir:t,scope:n}of r){let r=MH(e,t);if(`error`in r){a.push(r);continue}for(let e of r.folders){let r=JV(s.join(t,e,KV),n),a=`${n}\0${e}`;i.delete(a),i.set(a,r)}for(let e of r.files)o.push({path:s.join(t,e),scope:n,name:void 0,reason:`a plugin is a folder holding its ${KV}: move this file to ${s.join(t,`<name>`,KV)}`})}return{roots:r.map(e=>e.dir),definitions:[...i.values()],unchecked:a,strays:o}}function MH(e,t){try{let n=e.readdirSync(t).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),r=n=>n.kind===`directory`||NH(e,t,n);return{folders:n.filter(r).map(e=>e.name),files:n.filter(e=>!r(e)).map(e=>e.name)}}catch(n){return _c(e,t)===`absent`?{folders:[],files:[]}:{path:t,error:n.message}}}function NH(e,t,n){if(n.kind!==`symlink`)return!1;try{return e.statSync(s.join(t,n.name)).kind===`directory`}catch{return!0}}const PH=[`json5`,`json`];function FH(e,t,n,r){if(r!==void 0)return[r];let i=n??process.cwd();return[...new Set([...t?PH.map(e=>s.join(t,`${IH}.${e}`)):[],...PH.map(e=>s.join(i,`${IH}.${e}`)),...PH.map(t=>`${LH(e)}.${t}`)])]}const IH=`.cc-candybar`;function LH(e){return s.join(e.configDir,`config`)}function RH(e){return{path:e,scope:`plugins`}}function zH(e,t,n,r,i,a){let o=[],c=new Map;for(let n of FH(t,r,i,a)){let r=_c(e,n);if(r===`absent`)continue;if(r!==`present`){o.push(r);continue}let i=e.realpathSync(s.dirname(n)),l=s.join(i,s.basename(n).replace(/\.(json5|json)$/,``));c.has(l)||c.set(l,{file:n,repo:a!==void 0||BH(t,n)?null:{dir:i,link:Oc(e,i)}})}let l=[...c.values()],u=IP(n,l.flatMap(e=>e.repo===null?[]:[e.repo]),VH(e,r)),d=l.filter(e=>e.repo===null||u.approved.includes(e.repo.dir)).reverse().map(e=>({path:e.file,scope:e.repo===null?`plugins`:`repo`}));if(a===void 0)return{kind:`chain`,layers:d,home:HH(t,d),unchecked:o,repos:u};let[f]=o,p=a;return d.length>0?{kind:`chain`,layers:d,home:p,unchecked:o,repos:u}:f===void 0?{kind:`missing`,path:a,home:p,repos:u}:{kind:`unreadable`,...f,home:p,repos:u}}function BH(e,t){return PH.some(n=>t===`${LH(e)}.${n}`)}function VH(e,t){if(t===void 0||_c(e,t)!==`present`)return null;let n=MH(e,s.join(t,AH)),r=e.realpathSync(t);return{dir:r,link:Oc(e,r),path:t,ships:!(`error`in n)&&n.folders.length>0}}function HH(e,t){return t.find(t=>BH(e,t.path))?.path??`${LH(e)}.${PH[0]}`}function UH(e,t,n,r,i,a,o){let s=zH(e,n,r,i,a,o),c=s.kind===`chain`?s.layers:[];return{path:s.home,above:c.filter(e=>e.path!==s.home),repo:s.repos.plugins,cwd:a??null,locs:n,disk:e,memo:t}}function WH(e){return GH(e).join(`
194
- `)||null}function GH(e){switch(e.kind){case`chain`:return e.unchecked.map(e=>`Config location could not be checked: ${e.path} — ${e.error}`);case`missing`:return[`Config file not found: ${e.path} — rendering the bundled default until it appears`];case`unreadable`:return[`Config file could not be read: ${e.path} — ${e.error} — rendering the bundled default until it can be`]}}function KH(e,t,n,r){let i=FH(t,n,r).filter(t=>_c(e,t)===`present`),a=new Map;for(let e of i){let t=s.dirname(e),n=s.basename(e).replace(/\.(json5|json)$/,``),r=s.join(t,n);a.has(r)||a.set(r,[]),a.get(r).push(e)}let o=[...a.values()].filter(e=>e.length>1);return o.length===0?null:`config-extension collision: ${o.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}const qH=`repo-configs.json`;function JH(e){return s.join(e,`repo-configs`)}function YH(e){return s.join(JH(e),qH)}function XH(e,t){return _c(e,YH(t))!==`absent`}function ZH(e,t){return Tz(e,XH(e,t)?YH(t):s.join(t,qH),{},RP)}const QH={level:`error`,glyph:`⚠`,colors:ZP},$H={level:`warning`,glyph:`⚠`,colors:QP},eU={level:`warning`,glyph:`⬆`,colors:QP},tU={level:`warning`,glyph:`🔒`,colors:QP},nU={level:`warning`,glyph:`🧪`,colors:QP};function rU(e,t){return{text:eF(e),link:t}}function iU(e,t,n,r,i,a){let o=new Set,s=(e,t)=>{let n=aU(e,t);for(let e of n)o.add(e);return n},c=[...r.flatMap(e=>s(e,QH)),...i,...a.flatMap(e=>s(e,$H))],l=oU(c);return c.map((r,i)=>o.has(r)?{...r,lines:[[rU(r.lines[0][0].text,sU(e,t,n,l[i],i+1))],...r.lines.slice(1)]}:r)}function aU({about:e,text:t,copy:n},r){let[i,...a]=t.split(/\r\n|\r|\n/).map(e=>rU(e,null)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:r,about:e,message:t,copy:n,lines:[i,...a]}]}function oU(e){return dU(e).map(e=>String(e*lU+1))}function sU(e,t,n,r,i){return fC(e,[{verb:oC,args:[t,n,r]}],`copy diagnostic ${i}`)}function cU(e){return e.length===0?null:e.some(e=>e.severity.level===`error`)?`error`:`warning`}const lU=4096;function uU(e){let t=ae(`sha256`).update(`${e.severity.level}\0${e.severity.glyph}\0${e.about}`).digest(`hex`);return Number.parseInt(t.slice(0,9),16)%2**32}function dU(e){let t=new Map;return e.map(e=>{let n=uU(e),r=t.get(n)??0;return t.set(n,r+1),n*256+Math.min(r,255)})}function fU(e,t,n){return String(dU(e)[t]*lU+n+1)}const pU={error:ZP,warning:QP};function mU(e){let t=cU(e),n=e.length,r=pU[t??`warning`];return{label:t===null?``:`⚠ ${n>9?`9+`:n}`,fg:r.fg,bg:r.bg,open:e.length===0?`0`:fU(e,0,0)}}function hU(e,t){let n=Number(e)-1,r=dU(t).indexOf(Math.floor(n/lU));return e===null||r===-1?null:{index:r+1,page:n%lU}}function gU(e,t){return Math.min(20,e??20,...t)}function _U(e,t,n,r,i,a){let{index:o}=t,s=e[o-1],c=bU(a),l=CU(s,c,[]),u=new W({bgcolor:s.severity.colors.bg,color:s.severity.colors.fg}),d=(e,t)=>xU(e,t===null?u:u.withLink(t)),f=(t,i)=>i===null?d(` `,null):d(t,yU(n,r,fU(e,i.index-1,i.page),`show diagnostic ${i.index} of ${e.length} page ${i.page+1}`)),p=(t,a)=>{let s=a>0?{index:o,page:a-1}:o>1?{index:o-1,page:0}:null,l=a<t-1?{index:o,page:a+1}:o<e.length?{index:o+1,page:0}:null,u=e.length>1||t>1,p=t>1?`[${o}/${e.length} ${a+1}/${t}]`:`[${o}/${e.length}]`;return SU([d(`✕`,yU(n,r,`0`)),...u?[f(`‹`,s)]:[],d(p,null),...u?[f(`›`,l)]:[],d(`⧉ copy`,sU(n,r,i,fU(e,o-1,0),o))],c)},m=1;for(;;){let e=Math.max(1,a.rows-m),n=Math.min(lU,Math.ceil(l.length/e)),r=Math.min(t.page,n-1),i=p(n,r);if(i.length>m){m=i.length;continue}let o=l.slice(r*e,(r+1)*e),s=l.length-(r+1)*e,u=r===n-1&&s>0?[...o.slice(0,-1),...SU([d(`… ${s+1} more rows: ⧉ copy has them all`,null)],{...c,wrap:!1})]:o;return[...i,...u]}}function vU(e,t,n,r,i){let{label:a,fg:o,bg:s,open:c}=mU(t),l=a===``?[]:[xU(a,new W({bgcolor:s,color:o}).withLink(yU(n,r,c)))];return CU(e,bU(i),l)}function yU(e,t,n,r){return fC(e,[{verb:FS,args:[t,MS,n]}],r)}function bU(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,colorCompatibility:e.colorCompatibility}}const xU=(e,t)=>new q(`${e} `,{style:t,end:``,overflow:`ignore`}),SU=(e,t)=>bF(e,t).lines.map(e=>({kind:`diagnostic`,runs:e}));function CU(e,t,n){let r=new W({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),i=e=>e===null?r:r.withLink(e),a=Tl(Math.max(2,t.width-1));return e.lines.flatMap((o,s)=>{let c=xU(s===0?e.severity.glyph:` `,r),l=o.flatMap(e=>e.text.split(` `).flatMap(e=>Al(e,a)).map(t=>xU(t,i(e.link)))),u=s===0?n:[];return SU([c,...l,...u],t)})}const wU=(e,t)=>Dz(e,YH(t),()=>ZH(e,t));function TU(e,t,n,r){let i=wU(e,t),a={superseded:[],absent:[],unchecked:[]},o=i.update(t=>{let i=Object.keys(t).filter(e=>e!==n).map(t=>({d:t,found:_c(e,t)}));return a={superseded:i.filter(({d:t,found:r})=>r===`present`&&NP({dir:t,link:Oc(e,t)})===n).map(({d:e})=>e),absent:i.filter(({found:e})=>e===`absent`).map(({d:e})=>e),unchecked:i.flatMap(({found:e})=>typeof e==`object`?[e]:[])},LP(t,n,r,a.superseded)});return o.kind===`failed`?o:F(a)}function EU(e,t,n){return{sessionId:e,action:aC,declaration:t,evaluated:n}}function DU(e,t,n){return e.awaiting.map(e=>{let r=`a cc-candybar config for ${e} — run it?`,i=MP.map(r=>rU(`[${r===`approved`?`approve`:`decline`}]`,fC(n.to,[{verb:aC,args:[t,e,r,n.signer.sign(EU(t,e,r))]}]))),a=[rU(r,null),...i];return{severity:tU,about:`repo-question\0${e}`,message:r,copy:r,lines:[a]}})}function OU(e){return Math.max(1,e-2)}function kU({names:e,helpers:t,actions:n}){let r=(e,t)=>{let i=Object.hasOwn(n,e)?n[e]:void 0;return i===void 0||t.has(e)?[]:(t.add(e),[...[...yS(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=RC(e=>{let i=ZC(e,t)?Object.keys(n):qC(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]}),a=RC(n=>i(n).flatMap(n=>[...UC(n,t).keys()].map(t=>({path:t,reaches:ow(t,e)}))));return{ofTemplate:a,calls:RC(e=>new Set(i(e).flatMap(e=>[...$C(e,t)]))),ofVariable:t=>[...gb(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...mb(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function AU(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}const jU=new WeakMap;function MU(e){let t=jU.get(e);return t===void 0&&(t=kU({names:new Set([...aw(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),jU.set(e,t)),t}function NU(e,t){let n=e.segments[t];return n?[...[n.template,n.when,n.bg,n.fg].flatMap(e=>e===void 0?[]:[e]),...Object.values(n.partials??{})]:[]}function PU(e,t){return t===e||t.startsWith(`${e}.`)}function FU(e,t){let n=[];for(let r of sb(oS(e,t).node))r.when!==void 0&&n.push(r.when),r.kind===`segment`&&(r.lead!==void 0&&n.push(r.lead),r.trail!==void 0&&n.push(r.trail));let r=lS(e,t);for(let e of xy){let t=r[e];Sy(t)&&n.push(t)}return n}const IU=e=>e.kind===`shell`||e.kind===`file`;function LU(e,t,n=[]){let r=MU(e),i=new Map(aw(e)),a=[...n,...t.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=AU(e,t);n!==void 0&&s.add(n);for(let{reaches:e}of r.ofVariable(t))a.push(...e)}return s}function RU(e,t,n){return LU(e,[...NU(e,t),...n])}function zU(e){let t=[],n=new Set;for(let r of rS(e.presets)){t.push(...FU(e,r));for(let t of sb(oS(e,r).node))t.kind===`segment`&&n.add(t.name)}for(let r of n)t.push(...NU(e,r));return LU(e,t,[...aw(e)].filter(([,e])=>IU(e)).map(([e])=>e))}function BU(e,t){return e.kind===`absent`?F(`none`):e.kind===`failed`?e:t.kind===`failed`?t:F(t.kind===`ok`?`tracked`:`gone`)}function VU(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?L(`HEAD: ${t.reason}`,t.failedAt):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const HU={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},UU={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function WU(e,t,n){return Object.hasOwn(t,n)?F(t[n]):L(`${e}: unknown state ${JSON.stringify(n)}`,`parse`)}const GU={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,tag:`tag`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function KU(e){return Object.keys(GU).flatMap(t=>{let n=e[t];return n?.kind===`failed`?[`git.${GU[t]}: ${n.reason}`]:[]})}function qU(e,t,n){return t.ok?F(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?I:L(JU(e,t),`read`)}function JU(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??YU(t.stderr)].filter(Boolean).join(`, `)}`}function YU(e){return e.trim().split(`
193
+ `).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return t.length===0?[`the config failed to load`]:t}case`loaded`:return[...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${fre[e]}`)]}}const gre={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{let t=mre(e),[n,...r]=[...hre(e),...VP(e.repos)],i=t=>[t,...HP(e.repos)].join(`; `);return n===void 0?{ok:!0,note:i(t)}:{ok:!1,reason:i(`${t}: ${n}`),more:r}}},VF="re-run `cc-candybar install`";function _re(e){if(e.kind===`failed`)return[`Launch Services could not be asked which app opens cc-candybar:// — ${e.reason}`];if(e.value===null)return[`no app is registered for cc-candybar:// — ${VF}`];let{app:t,forwarder:n}=e.value;return n?[]:[`${t} opens cc-candybar://, but it is not the forwarder app \`cc-candybar install\` builds — ${VF}`]}function vre(e){return e===null?[]:[`the daemon (${e.theirs}) is another build than this client (${e.mine}), so it may not read the link this build sends`]}const yre={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.delivery.kind===`forwarder`?{ok:!0}:{ok:!1,reason:`the link was delivered by a click request (\`cc-candybar url-handle\`), not the forwarder app — ${VF}`};case`lost`:return RF([..._re(e.opener),...e.unopened===null?[...vre(e.otherBuild),`a cc-candybar:// link was opened and did not arrive at the daemon`]:[`a cc-candybar:// link could not be opened — ${e.unopened}`]])}}};function HF({bundle:e,checkout:t},n){return{bundle:n.bundle.kind===`failed`?{kind:`unresolved`,reason:n.bundle.reason}:n.bundle.value===e?{kind:`same`}:{kind:`other`,path:n.bundle.value},source:n.client!==`native`||t===null?{kind:`uncompared`}:t.rustSource.kind===`failed`?{kind:`unreadable`,root:t.root,reason:t.rustSource.reason}:n.source===null?{kind:`unstamped`}:n.source===t.rustSource.value?{kind:`same`}:{kind:`other`,root:t.root}}}function UF(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${Qc.join(`|`)}>\``:e.checkout===null?VF:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function bre(e,t,n){let{checkout:r}=e;if(n.kind===`unreported`)return[`the bar is drawn by a statusline client too old to say what it is — ${UF(e,`native`)}`];let{bundle:i,source:a}=HF(e,n);switch(i.kind){case`unresolved`:return[`the statusline client's bundle cannot be resolved: ${i.reason}`];case`other`:return[`the statusline client runs ${i.path}, not the daemon's ${e.bundle} — ${UF(e,n.client)}`];case`same`:break}if(n.client===`node`&&(t||r!==null))return[`the bar is drawn by the Node fallback, which starts node on every render — ${UF(e,`native`)}`];switch(a.kind){case`uncompared`:case`same`:return[];case`unreadable`:return[`${a.root}/rust-client could not be read: ${a.reason}`];case`unstamped`:return["the native client carries no source stamp, so which source it was built from is unknown — run `just install-rust`"];case`other`:return[`the native client was built from other source than ${a.root}/rust-client holds — run \`just install-rust\``]}}const WF=e=>{let t=`restarted since the bar was drawn, or has served 64 newer sessions`;return e.kind===`clicked`?`this daemon holds no render of this bar (it ${t})`:`this daemon holds no render of session ${e.sessionId}'s bar (its statusLine does not run cc-candybar — a \`claude -p\` session draws none — or the daemon ${t}; unset CLAUDE_CODE_SESSION_ID to judge every bar drawn recently)`},xre={name:`install`,label:`install`,takesMark:!1,probe:({install:e,sighted:t})=>{if(e.kind===`failed`)return{ok:!1,reason:`the daemon could not be asked which clients draw the bar: ${e.reason}`};let{daemon:n,nativeShipped:r,clients:i}=e.value;return i.length===0?{ok:!1,reason:t.kind===`recent`?`no statusline client has drawn a bar for this daemon in the last ${300/60} minutes — run the doctor again once the bar has redrawn; if it never does, the statusLine command does not run cc-candybar`:`${WF(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:RF([...new Set(i.flatMap(e=>bre(n,r,e)))])}};function GF({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||Fi(e.identity,t.value.through)):[]}function KF(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const Sre={name:`daemon`,label:`daemon`,takesMark:!1,probe:({daemon:{serving:e,processes:t,read:n}})=>{let r=t.kind===`failed`?[`the process table could not be read: ${t.reason}`]:[],i=t.kind===`ok`?KF(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return RF([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=GF(e.value,n),u=RF([...l.map(e=>`the daemon ran out of memory and restarted (${e.identity}) — post-mortem: ${Object.values(e.artifacts).join(`, `)}`),...c.kind===`failed`?[`the daemon's post-mortems could not be listed: ${c.reason}`]:[],...n.kind===`failed`&&!(c.kind===`ok`&&c.value.length===0)?[`which post-mortems were read could not be read: ${n.reason}`]:[],...r,...i.map(e=>`daemon ${e.pid} (started ${e.started}, rss ${P(e.rss)} MB${e.ppid===1?``:`, child of ${e.ppid}`}) runs beside the one serving the bar (${a}) — \`kill ${e.pid}\``),...o.kind===`measured`&&o.charge.kind===`stand-in`?[`the daemon could not read what macOS charges it (${o.charge.unread}), so its memory limit judges ${o.charge.gap===0?`RSS, which counts pages macOS has reclaimed`:`RSS less the ${P(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&Ri(o.charge.bytes,s)?[`the daemon holds ${Hi(o.charge)} of its ${P(s)} MB limit — at the limit it records a post-mortem and restarts`]:[]]);if(u.ok&&o.kind===`unmeasured`)return{ok:!0,note:`the daemon has not measured its memory yet`};let d=l[0];return u.ok||d===void 0?u:{...u,fix:{kind:`post-mortems-read`,through:d.identity}}}},qF=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function Cre(e,t){let n=jF(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?rre(e.terminal):{kind:`unknown`}}function wre({identified:e,tmuxClient:t},n){let r=MF(e),i=Cre(e,n),a=jF(e)===null?qF:`${qF}, and the doctor remembers it for this terminal`,o=(()=>{switch(i.kind){case`draws`:return[];case`none`:return[`${r} draws no links (OSC 8), so nothing on the bar can be clicked — run Claude Code in a terminal that draws them: ${ire}`];case`older`:return[`${r} ${i.version} draws no links (OSC 8 came in ${i.since}) — update ${r}`];case`unsaid`:return[`${r} draws links (OSC 8) since ${i.since}, and did not say which release this is — ${a}`];case`unknown`:return[`the doctor does not know whether ${r} draws links (OSC 8) — ${a}`]}})(),s=n.kind===`failed`&&i.kind!==`draws`?[`the terminals a doctor click came back from could not be read: ${n.reason}`]:[],c=i.kind===`none`||t===null||t.features.includes(`hyperlinks`)?[]:[`tmux does not pass links through to ${r} — add \`set -as terminal-features ",${t.termname}:hyperlinks"\` to tmux.conf, then detach and reattach (tmux 3.4 or later)`];return[...o,...s,...c]}const Tre={name:`links`,label:`links`,takesMark:!1,probe:({sighted:e,terminal:t,clicked:n})=>{if(e.kind===`clicked`&&e.via===`link`)return{ok:!0};switch(t.kind){case`unreported`:return{ok:!1,reason:"the client reported no terminal — re-run `cc-candybar install` to stage a current client"};case`unasked`:return{ok:!1,reason:`tmux could not be asked which terminal is attached: ${t.reason}`};case`seen`:return RF(wre(t,n))}}},JF=e=>e.filter(e=>e.role===`statusline`),Ere={name:`effectRefresh`,label:`effect refresh`,takesMark:!1,probe:({frames:e,claudeSettings:{origin:t,elsewhere:n},sighted:r})=>{let i=[t,...n].flatMap(({sources:e,bars:t})=>Ore(e,Dre(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:YF(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:WF(r));let[o,...s]=i.flatMap(e=>e.ok?[]:[e]);if(o===void 0)return a;let c=[...new Set(s.map(e=>e.reason))].filter(e=>e!==o.reason);return c.length===0?o:{...o,more:c}}},Dre=e=>{let t=JF(e).map(e=>e.frame);return t.includes(`moves`)?{kind:`moving`,wearing:`the bar moves (an effect, a fade, an animated segment, or an open menu counting down to its close)`}:t.includes(`can-move`)?{kind:`moving`,wearing:`the bar can start moving (an open menu, which flashes and closes on its own, a globals.effect rule, placements that fade in and out, or a placement with an effect of its own that is not drawn now)`}:t.includes(`still`)?{kind:`still`}:t.includes(`drawing`)?{kind:`unknown`,unseen:`the bar's latest render has not finished`}:t.length>0?{kind:`unknown`,unseen:`the bar's recent renders failed`}:e.length>0?{kind:`unknown`,unseen:"only a `cc-candybar frames` display has drawn this bar, not Claude Code's statusline"}:{kind:`none`}},YF=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function Ore(e,t){let n=NF(e);if(n.kind===`present`&&n.refreshInterval===1)return{ok:!0,note:`statusLine.refreshInterval is 1 in ${n.from.path}`};switch(t.kind){case`none`:return null;case`still`:return{ok:!0};case`unknown`:return YF(t.unseen);case`moving`:break}let{wearing:r}=t;switch(n.kind){case`unread`:return{ok:!1,reason:`${r}, and Claude Code's settings could not be read: ${n.reason}`};case`absent`:return{ok:!1,reason:`${r}, and no settings file Claude Code reads here sets a statusLine (read: ${n.read.join(`, `)||`none`}) — the one that runs the bar comes from --settings, MDM or server-managed settings, which the doctor cannot read; set "refreshInterval": 1 beside its command there`};case`not-an-object`:return{ok:!1,reason:`${r}, and ${n.from.path} sets statusLine to ${JSON.stringify(n.value)}, not a statusLine object — ${n.from.scope===`user`?"re-run `cc-candybar install` to write one":`replace it there with the statusLine object that runs cc-candybar`}`};case`present`:{let{from:e,refreshInterval:t}=n,i=t===void 0?`its statusLine sets no refreshInterval, so Claude Code redraws it only on events`:typeof t==`number`&&t>1?`its statusLine redraws it only every ${t} s`:`its statusLine.refreshInterval is ${JSON.stringify(t)}, not a number of seconds Claude Code accepts (its minimum is 1)`;return ore(e)?{ok:!1,reason:`${r}, but ${i} (statusLine from ${e.path})`,fix:{kind:`claude-settings`,file:e,path:[`statusLine`,`refreshInterval`],value:1}}:{ok:!1,reason:`${r}, but ${i} — its statusLine is in ${e.scope===`managed`?`managed settings`:`the project's shared settings`}, ${e.path}: set "refreshInterval": 1 there`}}}}const XF=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function kre(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return MF(e);case`bundling`:case`unread`:case`configured`:return[EF(e.name),e.version].filter(e=>e!==null).join(` `)}}function Are(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return jF(e);case`bundling`:case`unread`:return EF(e.name);case`configured`:{let t=EF(e.name);return e.font.kind===`ok`?`${t} with ${e.font.value.font} (${e.font.value.from})`:`${t}, its font unread: ${e.font.reason}`}}}function ZF(e){let t=Are(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${XF(e.glyphs)}`}}const jre={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=ZF(e),r=e=>t.kind===`failed`&&n!==void 0?{ok:!1,reason:e,more:[`the mark book could not be read: ${t.reason}`]}:{ok:!1,reason:e,...n!==void 0&&{sighting:n}},i=e.terminal,a=kre(i);switch(n===void 0||t.kind===`failed`?null:t.value.nerdFont?.[n.id]??null){case`drawn`:return{ok:!0};case`boxes`:return r(`${a} draws ${XF(e.glyphs)} as boxes — set a Nerd Font as its font`);case null:break}switch(i.kind){case`unreported`:return r("the client reported no terminal — re-run `cc-candybar install` to stage a current client");case`unasked`:return r(`tmux could not be asked which terminal is attached: ${i.reason}`);case`unknown`:case`unnamed`:case`unread`:return r(`the doctor cannot read ${a}'s font`);case`bundling`:{let e=wF[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:kF(i.version,e);if(t===!0)return{ok:!0};let n=EF(i.name);return r(t===null?`${n} ships Nerd Font symbols since ${e}, and did not say which release this is`:`${a} ships no Nerd Font symbols (they came in ${e}) — update ${n}, or set a Nerd Font as its font`)}case`configured`:{if(i.font.kind===`failed`)return r(`the doctor cannot read ${a}'s font: ${i.font.reason}`);let{font:e,from:t,lacks:n}=i.font.value;return n===null?r(`${a} is set to ${e} (${t}), which is not installed — install it or set a Nerd Font`):n.length===0?{ok:!0}:r(`${a} draws with ${e} (${t}), which has no ${XF(n)} — set a Nerd Font as its font`)}}}};function QF(e){return e.join(`, `)}function $F(e){return`or set missingData: "ignore" on ${QF(e)}`}function Mre(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${QF(t)}: whether the forge CLI is ready could not be asked: ${n.reason}`];if(n.value===null)return[];let{cli:r,host:i,status:a}=n.value;return a===`ready`?[]:a===`missing`?[`${QF(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${$F(t)}`]:[`${QF(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${$F(t)}`]}function Nre(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${QF(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${QF(n)}: no session of this Claude Code has drawn a bar for this daemon in the last ${300/60} minutes, so whether it sends rate_limits is unseen — run the doctor again once the bar has redrawn`:`${QF(n)}: ${WF(t)}, so whether Claude Code sends rate_limits is unseen — run the doctor again once the bar has redrawn`]:r.value.includes(`missing`)&&!r.value.includes(`carried`)?[`${QF(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${QF(n)}`]:[]}const Pre={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>RF([...Mre(e.pullRequests),...Nre(e.rateLimits,t)])};function Fre({path:e,answered:t,read:n}){switch(n.kind){case`absent`:return t?[`the transcript ${e} does not exist, though Claude Code has answered in its session — the bar's session cost, metrics and activity read nothing`]:[];case`failed`:return[`the transcript ${e} cannot be read: ${n.reason}`];case`ok`:{let{lines:t,unparsed:r,whole:i}=n.value;return r===0?[]:[`${r} of the ${t} lines ${i?`in`:`in the last ${IF/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const eI=[gre,xre,Sre,yre,Tre,lre,ure,dre,Ere,jre,Pre,{name:`sessionData`,label:`session data`,takesMark:!1,probe:({transcripts:e,sighted:t})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.length===0?{ok:!1,reason:t.kind===`recent`?`no session has drawn a bar for this daemon in the last ${300/60} minutes, so no transcript was named — run the doctor again once the bar has redrawn`:`${WF(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:RF(e.value.flatMap(Fre))}],Ire=eI.filter(e=>e.takesMark);function tI(e){return eI.map(t=>({check:t,verdict:t.probe(e)}))}function nI(e){return eI.find(t=>t.name===e)}const Lre=`${TS}doctor.`;function rI(e){let t=`${Lre}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function Rre({target:e,repos:t}){return`configTarget=${e.source} repos=${t.awaiting.length}/${t.declined.length} unproven=${t.unproven.length}`}function zre(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?jF(e.identified):null,i=t.kind===`failed`?`unread`:r===null?`-`:t.value.includes(r)?`yes`:`no`;return`tmuxLinks=${n===null?`-`:n.features.includes(`hyperlinks`)?`yes`:`no`} clicked=${i}`}function Bre(e,t){let n=e.kind===`seen`?e.tmuxClient:null;return`cols=${t.kind===`failed`?`failed widthOf=-`:`${t.value.columns??`-`} widthOf=${t.value.of.kind}`} clientUtf8=${n===null?`-`:n.utf8?`yes`:`no`}`}function Vre(e){if(e.kind===`failed`)return`clients=unasked`;let{daemon:t,clients:n}=e.value;return`clients=${n.map(e=>{if(e.kind===`unreported`)return`unreported/-/-`;let{bundle:n,source:r}=HF(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const Hre=e=>`${e>=0?`+`:``}${P(e)}`;function Ure({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${KF(e,t.value).map(e=>e.pid).join(`,`)||`-`}`;if(e.kind===`failed`)return`${r} memory=unasked postMortems=unasked`;let{memory:i,limit:a,postMortems:o}=e.value,s=o.kind===`failed`||n.kind===`failed`?`unread`:`${GF(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Ui(i.charge)}${i.charge.kind===`stand-in`?`(${Hre(-i.charge.gap)})`:``}:${P(i.charge.bytes)}`}/${P(a)} postMortems=${s}`}function Wre(e){return`data=pr:${(()=>{if(e.pullRequests.kind===`unneeded`)return`-`;let t=e.pullRequests.fact;if(t.kind===`failed`)return`failed`;if(t.value===null)return`no-forge`;let{status:n}=t.value;return typeof n==`string`?n:`logged-out`})()},rateLimits:${(()=>{if(e.rateLimits.kind===`unneeded`)return`-`;let t=e.rateLimits.fact;if(t.kind===`failed`)return`failed`;let n=e=>t.value.filter(t=>t===e).length;return`${n(`carried`)}/${n(`missing`)}/${n(`unanswered`)}`})()}`}function Gre(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>Kre(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${z(i)}`;let a=JF(r.flatMap(e=>e.bars));return`frames=${CF.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${z(i)}`}function Kre(e){let t=NF(e);switch(t.kind){case`unread`:return`failed`;case`absent`:case`not-an-object`:return t.kind;case`present`:return`${t.from.scope}:${t.refreshInterval===void 0?`-`:JSON.stringify(t.refreshInterval)}`}}function qre(e){let t=PF(e,zF);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${z(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function Jre(e){if(e.kind===`failed`)return`transcripts=failed`;let t=t=>e.value.filter(e=>e.read.kind===t).length,n=e.value.reduce((e,t)=>e+(t.read.kind===`ok`?t.read.value.unparsed:0),0);return`transcripts=${t(`ok`)}/${t(`absent`)}/${t(`failed`)} unparsed=${n}`}function Yre(e,t){if(e.kind===`none`)return`glyphs=- terminal=- font=- mark=-`;let{glyphs:n,terminal:r}=e,i=[...n].map(e=>e.codePointAt(0).toString(16)),a=(()=>{switch(r.kind){case`unreported`:case`unasked`:return r.kind;case`unknown`:return`unknown:${JSON.stringify(r.called)}`;case`unnamed`:return`unnamed:${JSON.stringify(r.term)}`;case`bundling`:case`unread`:case`configured`:return`${r.name}@${r.version??`-`}`}})(),o=(()=>{if(r.kind!==`configured`)return`-`;if(r.font.kind===`failed`)return`failed`;let{font:e,lacks:t}=r.font.value;return`${JSON.stringify(e)}:${t===null?`not-installed`:`lacks${t.length}`}`})(),s=ZF(e),c=t.kind===`failed`?`unread`:s===void 0?`-`:t.value.nerdFont?.[s.id]??`-`;return`glyphs=${i.join(`,`)} terminal=${a} font=${o} mark=${c}`}function Xre(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function Zre(e){return e.flatMap(({check:e,verdict:t})=>{let n=rI(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:Ky},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:Xre(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?Ky:Gy},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const Qre={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function iI(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries(Qre).map(([t,n])=>[`${e}${t}`,n]))}}const aI=`armed`,oI=`disarmed`,sI=`.armed`,cI=e=>e.endsWith(sI);function lI(e,t,n){let r=[...new Set(n.map(e=>e.when))].filter(e=>e!==`true`),i=t=>r.length===0?e:`${e}.${t}`,a={};for(let e=0;e<2**r.length;e++)a[i(e)]={do:[t,...n.filter(t=>t.when===`true`||e&1<<r.indexOf(t.when)).map(e=>e.action)]};let o=(e,t)=>e===r.length?`"${i(t)}"`:`(ternary ${o(e+1,t|1<<e)} ${o(e+1,t)} (${r[e]}))`;return{link:o(0,0),actions:a}}function uI(e,t,n){let r=`${e}${sI}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${aI}")`,s=lI(e,a,n);return{template:`{{ if ${o} }}{{ action ${s.link} "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:aI},[a]:{set:r,to:oI},...s.actions},armed:o,variables:{[e]:{kind:`state`,key:r,default:oI}},disarm:a}}const dI=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function fI(e){return typeof e==`string`&&dI.test(e)?{kind:`line`,line:e}:{kind:`refused`,reason:`a slash command is "/" then its name, e.g. "/compact" or "/model opus", on one line with no control characters, got ${JSON.stringify(e)}`}}function pI(e){let t=fI(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const mI=[`/compact`,`/model`],hI=`/clear`;function gI(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=uI(`${e}clear`,{arm:hI,confirm:`${hI} ✓ confirm`},[{action:n,when:`true`}]);return{template:mI.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${Xc} }}`,actions:{...Object.fromEntries(mI.map(e=>[t(e),{slash:pI(e)}])),...r.actions,[n]:{slash:pI(hI)}},variables:r.variables,disarm:r.disarm}}const _I=Array.from({length:10},(e,t)=>(t+1)*1e5),vI=_I[0],yI=_I[_I.length-1];function bI(e){let t=Qo(e);if(t.kind!==`ok`)return t;let n=t.value.autoCompactWindow;return n===void 0?F(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=vI&&n<=yI?F(n):L(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${vI}–${yI} tokens)`,`parse`)}function xI(e,t){let n=Math.min(t??yI,yI),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:_I.filter(e=>e<r).at(-1)??0,higher:_I.find(e=>e>r&&e<=n)??0}}function SI(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${Xc} }}{{ if gt .autocompact.lower 0 }} {{ action (printf "${e}%d" .autocompact.lower) "−" }}{{ end }}{{ if gt .autocompact.higher 0 }} {{ action (printf "${e}%d" .autocompact.higher) "+" }}{{ end }}{{ if gt .autocompact.window 0 }} {{ action "${e}auto" "↺" }}{{ end }}{{ end }}{{ end }}`,bg:`{{ if ne .autocompact.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .autocompact.window 0) (ne .autocompact.error "") }}`,actions:{[`${e}auto`]:{slash:pI(`/autocompact auto`)},...Object.fromEntries(_I.map(t=>[`${e}${t}`,{slash:pI(`/autocompact ${t}`)}]))}}}const CI=e=>`{{ if ge ${e} 1000000 }}{{ printf "%.1f" (divf ${e} 1000000) }}M{{ else if ge ${e} 1000 }}{{ printf "%.1f" (divf ${e} 1000) }}K{{ else }}{{ ${e} }}{{ end }}`,wI=`${TS}edit`,TI=`${TS}toolbar`,EI=iI(TS),DI=`${TS}commands`,OI=gI(`${DI}.`),kI=`${TS}autocompact`,AI=SI(`${kI}.`,CI),jI=e=>({kind:`segment`,name:e}),MI=`${TS}tab`,NI=e=>`${MI}.${e}`,PI=e=>`${NI(e)}.toggle`,FI=e=>({variable:MI,key:MI,member:e}),II=`${TS}save`,LI=`${TS}preset.save`,RI=`${TS}preset.delete`,zI=e=>`${TS}${e}`,BI=e=>`${TS}apply.${e}`,VI=e=>`${TS}reset.${e}`,HI=`${TS}themeDefault.save`,UI=`${TS}themeDefault.differs`,WI=`${TS}themeDefault.theme`,GI={when:`{{ .${UI} }}`,template:`{{ action "${HI}" (printf "⤓ default for %s" .${WI}) }} {{ swatch "${BI(`theme`)}" .${WI} }}`},KI=`${TS}resetAll`,qI=`${OS}.toggle`,JI=`${TS}undo`,YI=`${TS}back`,XI=`${YI}.step`,ZI=`${TS}navigation.back`,QI=YI,$I={template:`{{ if gt .${ZI} 0 }}{{ action "${YI}" "◁" }}{{ else }}{{ fg (${CP}) "◁" }}{{ end }}`},eL=`${TS}redo`,tL=`${TS}doctor`,nL=`${tL}.run`,rL=e=>`${tL}.fix.${e}`,iL=(e,t)=>`${tL}.mark.${e}.${t}`,aL=e=>`${tL}.${e}`,oL={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},sL=FM(`${TS}pickers`),cL=e=>`${TS}${e}`,lL=e=>`${cL(e)}.toggle`,uL=e=>tN(e)?FM(`${TS}${e}Pickers`):sL,dL=e=>{let t=uL(eN[QM[e].beside]);return{variable:t,key:t,member:e}},fL={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${RI}" (printf "🚮 delete %s" .${bx.preset.effectiveVar}) }}`}},pL=(e,t)=>`${TS}list.${e}.${t}`,mL=e=>`${TS}resettable.${e}`,hL=e=>e.length===0?`false`:`(or ${e.map(e=>`(and (${e.shown}) .${mL(e.name)})`).join(` `)})`,gL=Qc.map(e=>[Zc[e].switch.setting,e]),_L={variables:{},actions:{},segments:{}},vL=Object.fromEntries(gL.map(([e,t])=>[e,cP(`${TS}help.${e}`,xP[t],[],_L)])),yL=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],bL=e=>{let t=t=>`.${rl(e,t)}`,n=yL.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if eq .${bx[Zc[e].switch.setting].effectiveVar} ${JSON.stringify(Zc[e].switch.on)} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},xL=`{{ if .diagnostics.label }} {{ bg .diagnostics.bg (fg .diagnostics.fg (action "${jS}" .diagnostics.label .diagnostics.open)) }}{{ end }}`,SL=`${TS}fps`,CL=`{{ if eq .${tl(`by`)} "feed" }}{{ printf "%3s" (printf "≤%d" (int .${tl(`fps`)})) }} fps{{ else }}${`polled`.padStart(7)}{{ end }}`,wL=Object.fromEntries(gL.map(([e,t])=>[e,bL(t)])),TL=e=>$M.filter(t=>QM[t].beside===e),EL=Object.keys(bx).map(e=>{let t=bx[e],n=eN[e];return{...t,name:e,place:n,control:JM({label:t.label,domain:cN(t.configKey)},t.sessionKey,t.effectiveVar,BI(e),uL(n)),beneath:t.previews.map(e=>fL[e]),help:[vL[e]].filter(e=>e!==void 0),submenus:TL(e)}}),DL=e=>EL.filter(t=>t.place===e),OL=e=>EL.filter(t=>nN(t.place,e)),kL=e=>t=>`(print ${Ta(t)} (ternary ${Ta(` •`)} "" ${hL(OL(e))}))`,AL=e=>DL(e).flatMap(e=>[HL(e),...e.help,...e.submenus.map(e=>ba(cL(e),dL(e),YL(e),`drop`))].map(t=>({...t,when:`{{ ${e.shown} }}`})));new Set(EL.flatMap(e=>[e.sessionKey,e.configKey]));const jL=uI(KI,{arm:`⟲`,confirm:`⟲ reset all?`},EL.map(e=>({action:VI(e.name),when:e.shown}))),ML=[`unsaved`,`history.undo`,`history.redo`],NL=e=>`${TS}${e}`,PL=NL(`unsaved`),FL=(e,t)=>({body:t,shown:`(gt .${NL(e)} 0)`}),IL=[FL(`unsaved`,`{{ action "${II}" (printf "💾 save %d" .${PL}) }}`),FL(`history.undo`,`{{ action "${JI}" "↶" }}`),FL(`history.redo`,`{{ action "${eL}" "↷" }}`),{body:jL.template,shown:`(or ${hL(EL)} ${jL.armed})`}],LL={when:`{{ or ${IL.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+IL.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},RL=[{step:jL,place:`door`},{step:OI,place:`session`}],zL=e=>e.map(e=>e.step.disarm),BL=zL(RL),VL=zL(RL.filter(e=>e.place!==`door`));function HL(e){let t=zI(e.name);return e.control.kind===`inline`?jI(t):ba(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>jI(pL(e.name,n)))},`drop`)}function UL(e){return e===OS}function WL(e){let t=jI(OS);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[WL(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[t,e]};if(e.when===void 0)return{...e,children:[t,...e.children]};let{when:n,children:r,...i}=e;return{...i,children:[t,{kind:`container`,direction:i.direction,when:n,children:r}]}}function GL(e){return KL(e)>0?e:WL(e)}function KL(e){let t=0;for(let n of ob(e))n.kind===`segment`&&UL(n.name)&&(t+=1);return t}function qL(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&UL(e.name)||e.opens!==void 0&&qL(e.opens.body,!0):e.children.some(e=>qL(e,n))}const JL={door:{direction:`horizontal`,content:[jI(QI)],after:[jI(wI),jI(II)]},session:{direction:`vertical`,content:[jI(TI),{kind:`container`,direction:`horizontal`,children:[jI(DI),jI(kI)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[jI(LI)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[jI(tL),...eI.map(e=>jI(aL(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[jI(HI)]},toggles:{direction:`horizontal`,content:[],after:[]}};function YL(e){let{direction:t,content:n,after:r}=JL[e];return{kind:`container`,direction:t,children:[...n,...AL(e),...r]}}function XL(e){return e.kind===`segment`?UL(e.name)?{kind:`container`,direction:`horizontal`,children:[ba(e.name,AS,QL,`above`),jI(SL)]}:e:$L(e)}function ZL(){return{kind:`container`,direction:`vertical`,children:[YL(`door`),{kind:`container`,direction:`horizontal`,children:XM.map(({member:e})=>ba(NI(e),FI(e),YL(e),`drop`))}]}}const QL=ZL();function $L(e){return{...e,children:e.children.map(e=>XL(e))}}function eR(e){let t={variables:{[OS]:Ea(OS,ma),[jS]:{kind:`state`,key:jS,default:`0`}},actions:{[qI]:Da(OS,kS),[jS]:{set:jS,int:!0},[OS]:{do:[qI,...BL]},[nL]:{doctor:`run`},...EI.actions,...OI.actions,...AI.actions,[II]:{save:!0},[JI]:{undo:!0},[XI]:{back:!0},[YI]:{do:[XI,...BL]},[eL]:{redo:!0},[LI]:{preset:`save`},[HI]:{themeDefault:`save`},[RI]:{preset:`delete`,name:`{{ .${bx.preset.effectiveVar} }}`}},segments:{[OS]:{template:`{{ $door := ${wa(OS,Ta(e),Ta(`✖`))} }}{{ if ${Sa(AS)} }}{{ fg (roleTextOn "error" (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+xL},[SL]:{template:CL},[TI]:{template:EI.template},[DI]:{template:OI.template,when:OI.when},[kI]:{template:AI.template,bg:AI.bg,when:AI.when},[QI]:$I,[II]:LL,[HI]:GI,[LI]:{template:`{{ action "${LI}" "+ preset" }}`},[tL]:{template:`{{ action "${nL}" "🩺 doctor" }}`},[wI]:{template:`{{ action "${QN}" "✎ arrange" "✎ done" }}`}}};t.variables[UI]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[WI]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[ZI]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of ML)t.variables[NL(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[MI]=Ea(MI,ma);for(let{member:e,label:n}of XM){t.actions[PI(e)]=Da(MI,e),t.actions[NI(e)]={do:[PI(e),...VL]};let r=kL(e);t.segments[NI(e)]={template:`{{ ${wa(NI(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,OI.variables,jL.variables),nR(t),tR(t),t}function tR(e){for(let t of eI){let n=rI(t.name),r=rL(t.name);for(let t of Object.values(n))e.variables[t]={kind:`state`,key:t,default:``};e.actions[r]={doctor:`fix`,check:t.name};let i=t.takesMark?FF:[];for(let n of i)e.actions[iL(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${iL(t.name,e)}" "${oL[e]}" }}`).join(``);e.segments[aL(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ if ne .${n.reason} "" }} — {{ .${n.reason} }}{{ end }}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${Gy}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function nR(e){for(let t of EL){Object.assign(e.actions,t.control.actions);let n=VI(t.name);e.actions[n]={reset:t.configKey},e.variables[mL(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${mL(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[zI(t.name)]={template:`${t.control.template}${wL[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[pL(t.name,r)]=n})}Object.assign(e.actions,jL.actions),Object.assign(e.variables,_L.variables),Object.assign(e.actions,_L.actions),Object.assign(e.segments,_L.segments);for(let t of $M){let n=dL(t);e.actions[lL(t)]=Da(n.key,n.member),e.segments[cL(t)]={template:`{{ action "${lL(t)}" ${kL(t)(QM[t].trigger)} }}`}}}function rR(e){let{variables:t,actions:n}=sP();Object.assign(e.variables,t),Object.assign(e.actions,n)}function iR(e){let t=eR(e.globals.menuGlyph??`🍫`);rR(t);let n={...e.presets},r=[];for(let t of nS(e.presets)){let{node:i}=aS(e,t),a=XL(GL(i));r.push(a),n[t]={...iS(e.presets,t),root:a}}let i=jM(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const aR=`${wS}live`,oR=[`☐ live`,`☑ live`],sR=`${wS}done`,cR=`${wS}cancel`,lR=`${wS}rewind`,uR=`${wS}changes`,dR=`(gt .${uR} 0)`,fR=`(or ${dR} (gt .${PL} 0))`,pR={variable:aR,key:aR,member:ha};function mR(e){return`${wS}configuring.p${e}`}function hR(e){return`and ${Sa(nP)} (not ${Sa(pR)}) (ne .${mR(e)} "true")`}function gR(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${ZN} "${ya(e)}")`).join(` `)} false }}`}}function _R(e,t,n){return`{{ if ${hR(e)} }}${t}{{ else }}${n}{{ end }}`}const vR=`{{ and ${Sa(nP)} .preset.customized }}`,yR=DS;function bR(e){return new Map([...wte(e),...SR(e)])}const xR=`${wS}addable`;function SR(e){return new Map([[xR,{members:Object.keys(e.segments).filter(e=>!yR(e)),library:{groups:WN.map(e=>({id:e,label:GN[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function CR(e,t,n){return n.segments[e]={template:t,when:rP,bg:uP},{kind:`segment`,name:e}}function wR(e,t,n){let r=`${wS}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Hv}`}) (action "${r}" "✖") }}`}function TR(e){return`{{ if ${Sa(nP)} }}${e}{{ end }}`}function ER(e,t){return e.reduce((e,t)=>`{{ if and ${Sa(nP)} ${Sa(t)} }}true{{ else }}${e}{{ end }}`,t)}function DR(e){return e.flatMap(e=>[...ob(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function OR(e,t,n){return`${eP}${e}.${t}.${n}`}function kR(e,t,n,r){let i=nb(n),a=`${wS}${e.presetIdent}`,o=tP(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=FM(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:ma},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:ZN,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=OR(e.presetIdent,i,r),l=`${eP}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Eb(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=JM(KM(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};e.artifacts.segments[d]={template:f.template};let p=f.list.rows.map((t,n)=>{let r=`${d}.list.${n}`;return e.artifacts.segments[r]={template:t},{kind:`segment`,name:r}});return ba(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${gP}" }}`,ref:{variable:ZN,key:ZN,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const AR=`${wS}label:`;function jR(e){if(e.startsWith(AR)){let t=e.slice(AR.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function MR(e,t,n,r){let i=nb(e),a=NR(n,i,e,t,i),o=Object.fromEntries(xb.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...ba(a,r.ref,r.body,`drop`,ER([r.ref],`{{ ${hR(n.presetIdent)} }}`)),...Object.keys(o).length>0&&{settings:o},drafts:Object.fromEntries(xb.map(e=>[e,r.drafts[e]]))}}function NR(e,t,n,r,i){let a=`${AR}${t}:${n.name}`;return e.artifacts.segments[a]={template:`{{ "${ya(i)}" }}`,...r.palette!==void 0&&{palette:r.palette}},a}function PR(e,t,n,r){let i=nb(e),a=n?[LR(r,String(r.posCounter.n++),i,`before`)]:[],o=String(r.posCounter.n++),s=LR(r,o,i,`after`),c=wR(r,o,i),l=r.segments[e.name],u=kR(r,o,e,Sb(l)),d=TR(c),f=TR(u.term);return[...a.map(e=>CR(e.host,e.template,r.artifacts)),{...MR(e,l,r,u),lead:d,trail:f},{...t,when:_R(r.presetIdent,`false`,e.when??`true`),lead:d,trail:f,drafts:u.drafts},CR(s.host,s.template,r.artifacts)]}function FR(e){return s.join(s.basename(s.dirname(e)),s.basename(e))}function IR(e,t,n,r){let i=r.segments[e.name],a=nb(e);return[{kind:`segment`,name:NR(r,`${a}/${r.presetIdent}`,e,i,`${a} · ${FR(t.file)} ${t.entry}`),when:`{{ ${hR(r.presetIdent)} }}`},{...n,when:_R(r.presetIdent,`false`,e.when??`true`)}]}function LR(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${wS}${i}.insert.${t}`,s=`${wS}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:xR,anchor:n,relation:r};let c=NM(o),l=PM(s,o,void 0),u=LM(l),d=IM(l,c);return a.variables[l]={...Ea(l,ma),within:[nP]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=Da(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${Sa({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Hv}`}) $m }}{{ end }}`}}function RR(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!yR(e.name)&&e.insertedBy===void 0),i=e=>RR(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=ab(o,i);if(yR(o.name)){n.push(s);continue}let c={kind:`container`,direction:`horizontal`,children:o.insertedBy===void 0?PR(o,s,a===r,t):IR(o,o.insertedBy,s,t),unit:!0};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[c]}:c)}return{...e,children:n,...e.when!==void 0&&{when:ER(DR(n),_R(t.presetIdent,`true`,e.when))}}}function zR(e,t,n,r,i,a,o){let s=`${wS}${t}.resetLayout`,c=`${wS}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:vR},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},BR(e,o)]}}function BR(e,t){if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t]};let n=e.children.at(-1);return e.direction===`vertical`&&n!==void 0&&(n.kind===`segment`||n.when===void 0)?{...e,children:[...e.children.slice(0,-1),BR(n,t)]}:{...e,children:[...e.children,t]}}function VR(e,t,n,r,i,a){let{node:o}=aS(e,t),s={presetIdent:MM(t),rootKey:LN(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=RR(o,s);return n.variables[mR(s.presetIdent)]=gR(s.configured),zR(c,s.presetIdent,s.rootKey,n,r,i,a)}function HR(e){let t={variables:{},actions:{},segments:{}},n=cP(`${wS}help`,bP,[nP],t);t.variables[aR]=Ea(aR,ma),t.actions[aR]=Da(aR,pR.member),t.segments[aR]={template:Ca(aR,...oR),when:rP};let r={kind:`segment`,name:aR},i=n;t.variables[uR]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[sR]={do:[II,QN]},t.segments[sR]={template:`{{ if ${fR} }}{{ action "${sR}" "✓ save" }}{{ else }}{{ action "${sR}" "✓ done" }}{{ end }}`,when:rP},t.actions[lR]={rewind:!0},t.actions[cR]={do:[lR,QN]},t.segments[cR]={template:`{{ action "${cR}" "↩ cancel" }}`,when:`{{ and ${Sa(nP)} ${dR} }}`};let a=[{kind:`segment`,name:sR},{kind:`segment`,name:cR}],o={...e.presets},s=[];for(let n of nS(e.presets)){let c=VR(e,n,t,a,r,i);s.push(c),o[n]={...iS(e.presets,n),root:c}}let c=jM(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function UR(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function WR(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function GR(e,t,n){let r=ib(e,new Set(n.map(rb).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const KR=/^-?\d+$/;function qR(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function JR(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!KR.test(t))return{ok:!1,reason:`${e} must be an integer, got "${t}"`};let n=t[0]===`-`,r=(n?t.slice(1):t).replace(/^0+/,``);return r===``?{ok:!0,value:`0`}:{ok:!0,value:n?`-${r}`:r}}}function YR(e,t,n){return r=>r?KR.test(r)?{ok:!0,value:String(Math.max(e,Math.min(t,parseInt(r,10))))}:{ok:!1,reason:`${n} must be an integer, got "${r}"`}:{ok:!1,reason:`${n} value is required`}}function XR(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!KR.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i}}return{kind:`int`}}function ZR(e){return e===`config`?`set-config`:`set-state`}function QR(e,t,n){return t.kind===`int`?JR(`menu page "${e}"`):t.kind===`range`?YR(t.min,t.max,`${n} stepper "${e}"`):qR(t.allowed,`${n} "${e}"`,ZR(n))}function $R(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:XR(e,n,t)}))}function ez(e){return e.kind===`int`?`an integer`:e.kind===`range`?`an integer from ${e.min} to ${e.max}`:WM(e.allowed)}function tz(e,t,n,r){let i=new Map(Object.entries(e).map(([e,t])=>[e,t.validate])),a=new Map(Object.entries(e).map(([e,t])=>[e,t.admits])),o=new Set(n.map(e=>e.key)),s=n.filter(t=>t.spec.kind!==`allow-list`||!Object.hasOwn(e,t.key)),c=new Map,l=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of s)if(l.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let u=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...s];for(let{key:t,spec:n}of $R(u,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,QR(t,n,r)),a.set(t,ez(n)),n.kind===`range`&&c.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},verdict(e,t){if(!o.has(e))return{kind:`held`};let n=i.get(e)(t);return n.ok&&n.value===t?{kind:`held`}:{kind:`foreign`,admits:a.get(e)}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>c.get(e)??null}}function nz(e,t,n){let r=[],i=0,a=(0,X.createAtom)(`${t}.keyspace`),o=new WeakMap,s=()=>{i++,a.reportChanged()};return{register(n,i){let a={key:n,allowed:i};tz(e,[a],[],t),r.push(a),s();let o=!0;return()=>{o&&(o=!1,r.splice(r.indexOf(a),1),s())}},gateFor(s){a.reportObserved();let c=o.get(s);if(c?.epoch===i)return c.gate;let l=tz(e,r,n(s),t);return o.set(s,{epoch:i,gate:l}),l}}}function rz(){return nz({},`config`,sz)}function iz(e,t){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:pS(e.from,t).members}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[UR({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[UR({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:pS(e.insertSegmentFrom,t).members.map(t=>UR({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function az(e){let t=new Set;for(let n of Object.values(e.actions)){`reset`in n&&t.add(n.reset);let e=`persist`in n?VN(n.persist):null;e?.scope===`preset-root`&&t.add(LN(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function oz(e){let t=bR(e);return[...az(e),...Object.values(e.actions).flatMap(e=>iz(e,t))]}function sz(e){return $R(oz(e),`config`)}const cz=gy(),lz=new Set(cz),uz=new Set(Ry),dz=e=>e?lz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${cz.join(`, `)})`}:{ok:!1,reason:`theme name is required`},fz=e=>e?uz.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Ry.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},pz=new Set([`1`,`true`]),mz=new Set([``,`0`,`false`]),hz={endcaps:{validate:fz,admits:WM(Ry)},theme:{validate:dz,admits:WM(cz,`themes`)},"toolbar-expanded":{validate:e=>pz.has(e)?{ok:!0,value:`1`}:mz.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false, or empty), got "${e}"`},admits:`"1" for true or "" for false`}};function gz(){return nz(hz,`state`,yz)}function _z(e,t){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:pS(e.from,t).members}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function vz(e){let t=bR(e);return Object.values(e.actions).flatMap(e=>_z(e,t))}function yz(e){return $R(vz(e))}function bz(e){let t=gz(),n=rz();for(let{key:n,allowed:r}of e.state)t.register(n,r);for(let{key:t,allowed:r}of e.config)n.register(t,r);return{state:t,config:n}}const xz=`update.dismissed`,Sz=`updateNotice`,Cz=bx.updateNotice.sessionKey;function wz(){return bz({config:[{key:Sz,allowed:[`false`]}],state:[{key:Cz,allowed:[`false`]},{key:xz,allowed:[]}]})}function Tz(e,t,n,r){let i;try{i=e.readFileSync(t)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${t}: ${e.message}`}}let a;try{a=JSON.parse(i)}catch(e){return{kind:`failed`,reason:`${t} is not JSON: ${e.message}`}}let o=r(a);return o.kind===`ok`?o:{kind:`failed`,reason:`${t} ${o.reason}`}}function Ez(e,t,n,r,i){let a=s.join(t,n);return Dz(e,a,()=>Tz(e,a,r,i))}function Dz(e,t,n){return{read:n,update:r=>{let i=n();if(i.kind===`failed`)return i;let a=r(i.value);return a!==i.value&&Cr(e,t,`${JSON.stringify(a,null,2)}\n`),{kind:`ok`,value:a}}}}function Oz(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:jz(t.segments,kz(t.segments,e.segments??{})),root:qx(e.root??Vx,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:jz(t.presets,Az(t.presets,e.presets??{})),themeDefaults:jz(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function kz(e,t){let n=(t,n,r)=>r[n]===void 0?r:{...r,[n]:{...e[t]?.[n],...r[n]}};return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,n(e,`partials`,n(e,`settings`,t))]))}function Az(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.globals===void 0?n:{...n,globals:{...e[t]?.globals,...n.globals}}]))}function jz(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const Mz=new Map([[`gitTaculous`,{kind:`built-in`,to:`gitaculous`}],[`git`,{kind:`built-in`,to:`gitaculous`}],[`settings.menu`,{kind:`built-in`,to:`candybar.menu`}],[`ticket`,{kind:`plugin`,to:`plugins.lit.ticket`,source:`promptctl/links-issue-tracker`}],[`ceiling`,{kind:`removed`,why:`the program it showed draws it through a cc-candybar plugin of its own now — delete this reference, or place that plugin's segment`}],[`themeSwitcher`,{kind:`removed`,why:'the settings menu\'s 🎨 theme control steps themes — delete this reference, or write your own `{{ carousel "apply" "open" "label" }}`'}]]);function Nz(e){let t=Mz.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`;case`removed`:return` (the built-in segment "${e}" was removed: ${t.why})`}}function Pz(e,t,n,r){return n.cache===void 0?(e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${fb.join(`, `)})`,line:J(e.source,t.split(`.`))}),null):Lz(e,`${t}.cache`,n.cache)}function Fz(e){return{required:!0,json:Rz(),parse:(t,n,r,i)=>Pz(t,n,i,e)??void 0}}const Iz={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Bz(n)?{ttl:n}:Vb(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${Y(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return Vb(e,t,`cache.watch_file must be a path string, got ${Y(n)}`);let r=Jb(`cache.watch_file`,n);return r===null?{watch_file:n}:Vb(e,t,r)}},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:Vb(e,t,`cache.depends_on must be an array of variable-name strings, got ${Y(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:Vb(e,t,`cache.key must be a non-empty template string, got ${Y(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:Vb(e,t,`cache.never must be the literal boolean true, got ${Y(n)}`)}}};function Lz(e,t,n){return Hb(e,Iz,t,n)}function Rz(){return Zb(Iz)}const zz=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Bz(e){return zz.test(e)}const Vz=new Map([[`session.budget.amount`,{segment:`session`,setting:`budget`}],[`session.budget.warningThreshold`,{segment:`session`,setting:`warnAt`}],[`today.budget.amount`,{segment:`today`,setting:`budget`}],[`today.budget.warningThreshold`,{segment:`today`,setting:`warnAt`}],[`block.budget.heatThreshold`,{segment:`block`,setting:`warnAt`}],[`block.budget.warningThreshold`,{segment:`block`,setting:`errorAt`}],[`weekly.budget.heatThreshold`,{segment:`weekly`,setting:`warnAt`}],[`weekly.budget.warningThreshold`,{segment:`weekly`,setting:`errorAt`}],[`burn.eta.errorMinutes`,{segment:`burnrate`,setting:`errorWithin`}],[`burn.eta.warnMinutes`,{segment:`burnrate`,setting:`warnWithin`}]]);function Hz(e){return`it became the "${e.setting}" setting of each "${e.segment}" placement — set it on the placement where a row places "${e.segment}" ({ seg: "${e.segment}", settings: { ${e.setting}: <value> } }), or redeclare segments.${e.segment}.settings.${e.setting} with the default every placement should start from`}function Uz(e){let t=Vz.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${Hz(t)}`}function Wz(e){let t=Vz.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${Hz(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const Gz=new Map([[`git.timeSinceCommit`,`the payload stores the commit's date as "git.committedAt" (epoch seconds), and the bundled template variable "git.timeSinceCommit" computes its age at the draw: drop this declaration`],[`block.etaMinutes`,`the bundled template variable "block.etaMinutes" computes it at the draw: drop this declaration`],[`weekly.etaMinutes`,`the bundled template variable "weekly.etaMinutes" computes it at the draw: drop this declaration`]]),Kz=new Map([[`branch`,{read:`.git.branch`,declare:{kind:`input`,path:`git.branch`,default:``},note:`when HEAD is on no branch it reads "detached", where this kind read ""`}],[`sha`,{read:`.git.sha`,declare:{kind:`input`,path:`git.sha`,default:``}}],[`dirty`,{read:`(ne .git.status "clean")`,declare:{kind:`template`,template:`{{ ne .git.status "clean" }}`,type:`boolean`}}],...[`ahead`,`behind`,`stash`].map(e=>[e,{read:`.git.${e}`,declare:{kind:`input`,path:`git.${e}`,type:`number`,default:0}}])]);function qz(e){let t=e=>typeof e==`string`&&e.includes(`"`)&&!e.includes(`'`)?`'${e}'`:JSON.stringify(e);return`{ ${Object.entries(e).map(([e,n])=>`${e}: ${t(n)}`).join(`, `)} }`}function Jz(e){let t=`kind "git" is retired: every git fact is an input over the payload's git lane, which the bundled default already declares — drop this declaration and`,n=typeof e.field==`string`?Kz.get(e.field):void 0;if(n===void 0){let e=[...Kz.values()].map(({read:e})=>e);return`${t} read whichever of ${e.slice(0,-1).join(`, `)} or ${e.at(-1)} it stood for, where it was read`}let r=n.note===void 0?``:` (${n.note})`;return`${t} read ${n.read} where it was read${r}, or declare ${qz(n.declare)} under a name of your own`}const Yz=new Map([[`HOME`,`home`],[`USER`,`host.user`],[`LOGNAME`,`host.user`],[`HOSTNAME`,`host.name`]].map(([e,t])=>[e,{read:`.${t}`,declare:{kind:`input`,path:t,default:``}}]));function Xz(e){let t=`kind "env" is removed${typeof e.name==`string`?` (this one read $${e.name})`:``}: the renderer's environment belongs to whichever shell spawned it, not to the session it draws for, so an env variable was never a session fact — drop this declaration`,n=typeof e.name==`string`?Yz.get(e.name):void 0;return n===void 0?`${t}; a value the payload lacks is read from a file by a "file" source or computed by a "shell" source, and not by echoing the variable there, since a "shell" source runs in the renderer too`:`${t} and read ${n.read} where it was read, or declare ${qz(n.declare)} under a name of your own`}function Zz(e,t,n){if(n===void 0)return{};if(!Zy(n))return e.issues.push({path:t,message:`${t} must be an object, got ${Ib(n)}`,line:J(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=ete(e,yB,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function Qz(){return{required:!0,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.value;if(typeof i!=`string`&&typeof i!=`number`&&typeof i!=`boolean`){e.issues.push({path:`${t}.value`,message:`literal value must be string|number|boolean, got ${Ib(i)}`,line:J(e.source,t.split(`.`))});return}return i}}}function $z(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Qee(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const eB={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:Vb(e,t,`parse.text must be the literal boolean true, got ${Y(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?tB(e,t,n):Vb(e,t,`parse.regex must be a pattern string, got ${Y(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:Vb(e,t,`parse.json must be the literal boolean true, got ${Y(n)}`)}}};function tB(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return Vb(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:Vb(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function nB(){return{required:!1,json:Zb(eB),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:J(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:Hb(e,eB,`${t}.parse`,r.parse)??void 0)}}function rB(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>Zy(r.parse)&&`json`in r.parse?iB(e,t,r.default):Nb(e,t,r,`default`)}}function iB(e,t,n){if(n!==void 0)return aB(n)?n:Vb(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${Y(n)}`)??void 0}function aB(e){return e!==null&&dw(e)}const oB={value:Qz(),default:Wb()};function sB(){let e=qb();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:Gz.get(a);return o===void 0?a:Vb(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const cB={path:sB(),type:Yb([`string`,`number`,`boolean`]),default:$z()},lB={path:ate(),readMode:Yb([`whole`,`first-line`]),parse:nB(),cache:Fz(`file`),default:rB()},uB={command:qb(),parse:nB(),cache:Fz(`shell`),default:rB()};function dB(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const fB={template:qb(),type:Yb([`string`,`number`,`boolean`]),default:$z()},pB=dB(`a template variable recomputes whenever a variable it reads changes`),mB={layout:qb(),default:Wb()},hB=dB(`a time variable reads the instant its render is drawn at`),gB={key:qb(),default:Wb()},_B=`kind`;function vB(e,t,n={}){return{...tte(_B,e,t),parse:(r,i,a)=>{Rb(r,n,i,a);let o=zb(r,t,i,a);return o===null?null:{kind:e,...o}}}}const yB={tag:_B,noun:`source kind`,memberNoun:`variable`,arms:{literal:vB(`literal`,oB),input:vB(`input`,cB),file:vB(`file`,lB),shell:vB(`shell`,uB),template:vB(`template`,fB,pB),time:vB(`time`,mB,hB),state:vB(`state`,gB)},retired:{git:Jz,env:Xz}};function bB(){return cte(yB)}function xB(){return{type:`object`,additionalProperties:bB()}}const SB=/^[A-Za-z_][A-Za-z0-9_]*$/,CB={pattern:SB.source},wB={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},TB={type:`object`,additionalProperties:!1,required:[`label`,`domain`,`default`],properties:{label:{type:`string`,pattern:`^[^\\n\\r]+$`},domain:{anyOf:[{const:`bool`},{type:`array`,items:{type:`string`,pattern:`^[^/\\n\\r]+$`},minItems:1,uniqueItems:!0},{type:`object`,additionalProperties:!1,required:[`min`,`max`],properties:{min:{type:`integer`},max:{type:`integer`},step:{type:`integer`,minimum:1},atLeast:{type:`string`,...CB}}}]},default:wB}},EB=[`label`,`domain`,`default`],DB=[`min`,`max`,`step`,`atLeast`];function OB(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function kB(e,t,n){if(n===`bool`)return`bool`;if(Array.isArray(n)){let r=n.filter(e=>typeof e==`string`);if(n.length===0||r.length!==n.length)return OB(e,t,`a list domain must be a non-empty list of words, got ${JSON.stringify(n)}`);if(new Set(r).size!==r.length)return OB(e,t,`a list domain names each word once, got ${JSON.stringify(n)}`);let i=r.filter(e=>e===``||e.includes(`/`)||/[\n\r]/.test(e));return i.length>0?OB(e,t,`a list domain's words must be non-empty, slash-free, and newline-free — configure mode writes each on the set-state wire — got ${JSON.stringify(i)}`):r}if(Zy(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!DB.includes(e)).length===0&&Number.isInteger(r)&&Number.isInteger(i)&&r<=i&&Number.isInteger(a)&&a>=1&&(o===void 0||typeof o==`string`)?{min:r,max:i,step:a,...o!==void 0&&{atLeast:o}}:OB(e,t,`a range domain is { min, max, step?, atLeast? } with integers min ≤ max, a whole step ≥ 1, and atLeast naming another range setting, got ${JSON.stringify(n)}`)}return OB(e,t,`domain must be "bool", a list of words, or { min, max }, got ${Y(n)}`)}function AB(e,t,n){if(!Zy(n))return OB(e,t,`${t} must be { label, domain, default }, got ${Ib(n)}`);for(let r of Object.keys(n))EB.includes(r)||OB(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${EB.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||OB(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${Y(r)}`);let a=kB(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!jB(n.default)||!Tb(o,n.default)?OB(e,`${t}.default`,`default must be ${Ob(o)}, got ${Y(n.default)}`):o}function jB(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const MB={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${yb}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function NB(e){return xb.includes(e)}function PB(){return{required:!1,json:{type:`object`,propertyNames:{...CB,not:{enum:[...xb]}},additionalProperties:TB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Zy(i))return OB(e,a,`${a} must be an object of name → { label, domain, default }, got ${Ib(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!SB.test(t)){OB(e,`${a}.${t}`,`setting name "${t}" is read as .settings.${t} in a template, so it must be an identifier (letters, digits, _; not starting with a digit)`);continue}if(NB(t)){OB(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${MB[t]}`);continue}let r=AB(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const FB=ES.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function IB(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${FB})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!DS(i)?i:OB(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${ES.map(e=>`"${e}"`).join(`, `)} namespaces, got ${Y(i)}`)}}}function LB(){return{required:!1,json:{type:`object`,propertyNames:CB,additionalProperties:wB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Zy(i))return OB(e,a,`a placement's "settings" must be an object of setting name → value, got ${Ib(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))jB(n)?o[t]=n:OB(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${Ib(n)}`);return o}}}function RB(e){return new Set(Object.keys(e.segments).filter(e=>!DS(e)))}function zB(e,t,n){if(t===void 0)return{};if(!Zy(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${Ib(t)}`,line:J(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=Lb(e,n.has(i)?YB:JB,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function BB(e,t,n,r){let i=r[n];if(typeof i==`string`)return i;if(Array.isArray(i)){let r=!0,a=[];for(let[o,s]of i.entries()){if(typeof s==`string`){a.push(s);continue}r=!1,e.issues.push({path:`${t}.${n}[${o}]`,message:`${t}.${n}[${o}] must be a string, got ${Ib(s)}`,line:J(e.source,[...t.split(`.`),n])})}return r?a.join(``):void 0}e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be a string or an array of strings, got ${Ib(i)}`,line:J(e.source,[...t.split(`.`),n])})}const VB={anyOf:[{type:`string`},{type:`array`,items:{type:`string`}}]};function HB(){return{required:!0,json:VB,parse:(e,t,n,r)=>r[n]===void 0?Vb(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own${Nz(t.slice(9))}`)??void 0:BB(e,t,n,r)}}function UB(){return{required:!1,json:VB,parse:(e,t,n,r)=>r[n]===void 0?void 0:BB(e,t,n,r)}}function WB(){return{required:!1,json:{type:`object`,additionalProperties:VB},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;if(!Zy(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be an object, got ${Ib(i)}`,line:J(e.source,[...t.split(`.`),n])});return}let a=Object.create(null);for(let r of Object.keys(i)){let o=BB(e,`${t}.${n}`,r,i);o!==void 0&&(a[r]=o)}return a}}}function GB(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${Y(i)}`,line:J(e.source,[...t.split(`.`),n])})}}}}function KB(){return{required:!1,json:xB(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return Zz(e,`${t}.${n}`,i)}}}const qB={template:HB(),description:Wb(),group:Yb(UN),width:GB(),justify:Yb(Hee),truncate:Yb(Uee),bg:Wb(),fg:Wb(),when:Wb(),palette:ite(),vars:KB(),settings:PB(),missingData:Yb(gb),partials:WB()},JB={noun:`segment key`,fields:qB},YB={noun:`segment key`,fields:{...qB,template:UB()}};function XB(e,t){if(t===void 0)return{};if(!Zy(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${Ib(t)}`,line:J(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${Y(i)}`,line:J(e.source,[`helpers`,r])});continue}n[r]=i}return n}function ZB(e,t,n){if(t===void 0)return{};if(!Zy(t))return Z(e,`actions`,`actions must be an object, got ${Ib(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=QB(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function Z(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function QB(e,t,n,r){if(!Zy(n))return Z(e,t,`${t} must be an action object, got ${Ib(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let i=gS.filter(e=>e in n);return i.length===1?eV(r)[i[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${gS.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function $B(e){return e===`<default>`?{dir:null}:s.isAbsolute(e)?{dir:s.dirname(e)}:{text:e}}const eV=e=>({set:(e,t,n)=>IV(e,t,n,`set`,MV),persist:(e,t,n)=>IV(e,t,n,`persist`,NV),copy:tV(`copy`),open:tV(`open`),reset:nV,undo:iV(`undo`),redo:iV(`redo`),back:iV(`back`),rewind:iV(`rewind`),save:iV(`save`),preset:aV,themeDefault:oV,doctor:cV,slash:lV,run:fV(e),do:pV});function tV(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Mb(t,n,r,e);return i===null?null:{[e]:i}}}function nV(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=mV(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}const rV={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,back:`it steps the session's navigation history`,rewind:`it steps the session's settings history back to where edit mode opened`,save:`it saves the session's unsaved settings`};function iV(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Z(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${rV[e]}), got ${Y(r[e])}`),null)}}function aV(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${Y(r)}`),null;if(r===`save`)return{preset:`save`};let a=Mb(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function oV(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Z(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${Y(n.themeDefault)}`),null)}const sV={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function cV(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(sV,r),a=i?sV[r]:[...new Set(Object.values(sV).flat())];for(let r of Object.keys(n))a.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Z(e,`${t}.doctor`,`doctor must be ${Object.keys(sV).map(e=>`"${e}"`).join(`, `)}, got ${Y(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?Ire:eI;if(typeof o!=`string`||!s.some(e=>e.name===o))return Z(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${Y(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return FF.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${FF.map(e=>`"${e}"`).join(` or `)}, got ${Y(c)}`),null)}function lV(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=fI(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}const uV=[`run`,`env`,`refreshes`],dV=/^[A-Za-z_][A-Za-z0-9_]*$/;function fV(e){return(t,n,r)=>{for(let e of Object.keys(r))uV.includes(e)||Z(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${uV.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&Z(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${Y(a)}`);let o=r.env??{};(!Zy(o)||Object.entries(o).some(([e,t])=>!dV.test(e)||typeof t!=`string`))&&Z(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${Y(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&Z(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${Y(s)}`),`dir`in e||Z(t,`${n}.run`,`a run action runs in the directory of the file that declares it, and ${e.text} is no file`),t.issues.length>i||!(`dir`in e)?null:{run:a,env:o,refreshes:s,cwd:e.dir}}}dV.source;function pV(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${Y(r)}`),null):{do:r}}function mV(e,t,n,r,i,a){let o=Mb(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Z(e,s,i),null):o.includes(`/`)?(Z(e,s,a(o)),null):o}const hV={set:`the SessionState key to write`,persist:`the config globals field to write`};function gV(e,t,n,r){let i=hV[r],a=mV(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);return a===null?null:r===`set`&&a.startsWith(eP)?(Z(e,`${t}.set`,`set key "${a}" is a placement's draft, under "${eP}" — the setting control configure mode synthesizes is its only writer, so its read can trust what it holds. Write a key outside it`),null):{[r]:a}}function _V(e){return e===`set`?`set-state`:`set-config`}const vV={to:LV(`set`)},yV={to:LV(`persist`)},bV={from:RV(`set`)},xV={from:RV(`persist`)},SV={min:UV(),max:UV(),by:UV()},CV={int:BV()},wV={cycle:zV(`set`)},TV={cycle:zV(`persist`)},EV={removeSegment:VV(`removeSegment`)},DV={insertSegment:VV(`insertSegment`),anchor:VV(`anchor`),relation:HV()},OV={insertSegmentFrom:RV(`persist`),anchor:VV(`anchor`),relation:HV()},kV={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},AV={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function jV(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>zb(e,t,n,r),c=Xb(t);return{detect:a,allowed:[...o,...i],label:i.join(`/`),json:{type:`object`,properties:{...Object.fromEntries(o.map(e=>[e,{type:`string`}])),...c.properties},required:[...o,...c.required??[]],additionalProperties:!1},parse:n.length?nte(s,...n):s}}const MV=[jV(`set`,vV),jV(`set`,bV),jV(`set`,SV,[kV,AV]),jV(`set`,CV),jV(`set`,wV)],NV=[jV(`persist`,yV),jV(`persist`,xV),jV(`persist`,SV,[kV,AV]),jV(`persist`,TV),jV(`persist`,EV),jV(`persist`,DV,[],[`insertSegment`]),jV(`persist`,OV,[],[`insertSegmentFrom`])];function PV(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"endcaps"/"styles", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function FV(e){let t=PV(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function IV(e,t,n,r,i){let a=gV(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${FV(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Z(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function LV(e){let t=_V(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>mV(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function RV(e){let t=_V(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${Y(o)}`)}}}function zV(e){let t=_V(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Z(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${Ib(o)}`);return}let c=o;if(c.length<2){Z(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Z(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Z(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Z(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function BV(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${Y(r[n])}`);return}return!0}}}function VV(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Mb(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Z(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Z(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function HV(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${Y(i)}`);return}return i}}}function UV(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${Y(i)}`);return}return i}}}function WV(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const GV=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),KV=`plugin.json5`,qV=/^[a-z][a-z0-9_]*$/;function JV(e,t){let n=s.basename(s.dirname(e));return qV.test(n)?{path:e,scope:t,name:n}:{path:e,scope:t,name:void 0}}function YV(e,t){return t.map(t=>{try{return{...t,read:{kind:`read`,text:e.readFileSync(t.path),dir:e.realpathSync(s.dirname(t.path))}}}catch(e){return{...t,read:{kind:`unreadable`,reason:e.message}}}})}function XV(e){return`${e}.data`}function ZV(e){return`${e}.json`}function QV(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:$V(e)}}}function $V(e){return e instanceof kb?e.issues.map(e=>e.path===``||e.message.includes(e.path)?e.message:`${e.path}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}function eH(e,t,n,r){return e.map(e=>JV(TP(s.dirname(t),e,r),n))}function tH(e,t,n,r){let i=new Map;return e.reduce((e,{read:n,...a})=>{let o=a.path,c=a.name===void 0?void 0:SC(a),l=(t,n)=>{let r=new Map(e.rendering);return c!==void 0&&n!==e.config&&r.delete(c),{...e,config:n,rendering:r,dropped:[...e.dropped,{...a,reason:t}]}};if(s.basename(o)!==`plugin.json5`){let t=`a plugin is a folder holding its ${KV}, and the folder's name is the plugin's: move this file to <dir>/<name>/${KV} and list that`;return l(t,c===void 0?e.config:rH(nH(e.config,c),c,{...a,reason:t}))}if(a.name===void 0||c===void 0)return l(`its folder "${s.basename(s.dirname(o))}" is not a plugin name (one matching ${qV}: it prefixes every name the plugin declares)`,e.config);let u=i.get(c);if(u!==void 0)return l(`plugin "${a.name}" is already listed, from ${u}`,e.config);i.set(c,o);let d=nH(e.config,c),f=QV(()=>{if(n.kind===`unreadable`)throw Error(n.reason);let i=Oz(lH(o,a,{source:n.text,json:Na.default.parse(n.text),dir:n.dir},t),d);return wH(o,c,i),r(i,c,d!==e.config),i});if(f.ok)return{...e,config:f.value,loaded:[...e.loaded,a],rendering:new Map([...e.rendering,[c,a]])};let p={...a,reason:f.reason};return l(f.reason,rH(d,c,p))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function nH(e,t){let n=CC(t),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n(e)));return[e.variables,e.segments,e.helpers,e.actions].some(e=>Object.keys(e).some(n))?{...e,variables:r(e.variables),segments:r(e.segments),helpers:r(e.helpers),actions:r(e.actions)}:e}function rH(e,t,n){return{...e,variables:{...e.variables,[t]:{kind:`dropped`,reason:WV(n),definition:n.path}}}}function iH(e){let t=Object.entries(e.variables).flatMap(([e,t])=>t.kind===`dropped`?[{ns:e,definition:t.definition,notice:t.reason}]:[]);return e=>t.find(({ns:t})=>CC(t)(e))}function aH(e,t){let n=iH(e.config),r=[...e.rendering.keys()].map(CC),i=[...t,...e.dropped].filter(e=>e.name===void 0);return e=>{let t=TC(e);if(t===void 0)return[];let a=n(e);return a===void 0?r.some(t=>t(e))?[]:i.filter(e=>e.scope===t).map(e=>({definition:e.path,notice:WV(e)})):[{definition:a.definition,notice:a.notice}]}}function oH(e,t,n){let r=nS(e.presets).flatMap(t=>[...ob(aS(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),i=[...new Set([...r.map(e=>e.name),...n,...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),a=Object.fromEntries(i.map(({name:e,cause:t})=>[e,sH(e,t.map(e=>e.notice),r.filter(t=>t.name===e))])),o=iH(e),s=Object.values(e.variables).some(e=>e.kind===`dropped`),c=s?Object.values(e.segments).flatMap(e=>[...pH.flatMap(t=>e[t]===void 0?[]:[e[t]]),...Object.values(e.partials??{})]):[],l=s?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],u=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:o(e);return n===void 0?[]:[[e,n]]}),d=u([...c.flatMap(t=>KC(t,e.helpers).map(e=>e.name)),...l],e.actions),f=u(c.flatMap(t=>[...ew(t,e.helpers)]),e.helpers),p=Object.entries(e.actions).flatMap(([t,n])=>{if(!(`run`in n))return[];let r=new Map(u(n.refreshes,e.variables));return r.size===0?[]:[{name:t,action:{...n,refreshes:n.refreshes.filter(e=>!r.has(e))},causes:[...r.values()]}]}),m=new Set([...i.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...d,...f].map(([,e])=>e.definition),...p.flatMap(({causes:e})=>e.map(e=>e.definition))]);return{config:{...e,segments:{...e.segments,...a},actions:{...e.actions,...Object.fromEntries(p.map(({name:e,action:t})=>[e,t])),...Object.fromEntries(d.map(([e,{ns:t}])=>[e,{copy:`{{ .${t} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(f.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:m}}function sH(e,t,n){let r=`⚠ ${e}: ${t.join(`; `)}`,i=new Map;for(let e of n)for(let[t,n]of Object.entries(e.settings??{})){let e=i.get(t);i.set(t,e===void 0?[n]:[...e,n])}let a=Object.fromEntries([...i].map(([e,t])=>[e,cH(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function cH(e,t){let[n]=t,r=t.filter(e=>typeof e==`number`);return typeof n==`boolean`?{label:e,domain:`bool`,default:n}:typeof n==`number`?{label:e,domain:{min:Math.min(...r),max:Math.max(...r),step:1},default:n}:{label:e,domain:[...new Set(t.map(String))],default:n}}function lH(e,t,{source:n,json:r,dir:i},{checkout:a,home:o}){let c=SC(t),l=[],u=()=>{throw new kb(e,l)};if(!Zy(r))return l.push({path:``,message:`a plugin definition must be an object, got ${Ib(r)}`}),u();for(let t of Object.keys(r))GV.has(t)||l.push({path:t,message:t===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${s.basename(s.dirname(e))}") — remove "plugin"`:`a plugin definition may not declare "${t}". Expected only: ${[...GV].join(`, `)}`});let d=r.data===void 0?void 0:DH(r.data,e,a,o,l),f=r.sources===void 0?{}:CH(r.sources,i,l);if(l.length>0)return u();let p={source:n,issues:l,allowedPalettes:new Set(gy()),groups:[],unplaced:[],inherited:[]},m=d===void 0?{}:Zz(p,`data`,{[XV(c)]:{kind:`file`,path:d,parse:{json:!0},cache:{watch_file:d},default:{}}}),h=Zz(p,`variables`,r.variables);for(let[e,t]of[[`variables`,Object.keys(h)],[`sources`,Object.keys(f)]])t.includes(`data`)&&l.push({path:`${e}.data`,message:`"data" names the plugin's data file (.${XV(c)}), declared by the definition's own "data" key: give this ${e===`sources`?`source`:`variable`} another name`});for(let e of Object.keys(f))Object.hasOwn(h,e)&&l.push({path:`sources.${e}`,message:`source "${e}" and variable "${e}" are one name (.${c}.${e}): give one of them another name`});let g={variables:{...m,...gH(c,f),...gH(c,Object.fromEntries(Object.entries(h).map(([e,t])=>[e,vH(c,t)])))},segments:gH(c,yH(c,zB(p,r.segments,new Set))),helpers:gH(c,XB(p,r.helpers)),actions:gH(c,bH(c,ZB(p,r.actions,{dir:i})))};l.push(...mH(g,t));let _=uH(c,g);for(let[e,t]of hH(_))try{KN.parse(t)}catch(t){l.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return l.length>0&&u(),_}function uH(e,t){let n=t=>nw(t,wC,e),r=t=>CC(`self`)(t)?`${e}${t.slice(4)}`:t,i=(e,t)=>Object.fromEntries(Object.entries(e??{}).map(([e,n])=>[e,t(n)]));return{...t,variables:i(t.variables,e=>dH(mb(e,n),r)),segments:i(t.segments,e=>({...e,...Object.fromEntries(pH.flatMap(t=>e[t]===void 0?[]:[[t,n(e[t])]])),...e.partials!==void 0&&{partials:i(e.partials,n)},...e.vars!==void 0&&{vars:i(e.vars,e=>dH(mb(e,n),r))}})),helpers:i(t.helpers,n),actions:i(t.actions,e=>fH(yS(e,n),r))}}function dH(e,t){return pb(e)&&`depends_on`in e.cache?{...e,cache:{depends_on:e.cache.depends_on.map(t)}}:e}function fH(e,t){let n=`segments.`,r={...e};`do`in e&&(r.do=e.do.map(e=>t(e,`do`)));for(let n of[`removeSegment`,`insertSegment`,`anchor`])n in e&&(r[n]=t(e[n],n));return`persist`in e&&e.persist.startsWith(n)&&(r.persist=n+t(e.persist.slice(9),`persist`)),r}const pH=[`template`,`bg`,`fg`,`when`];function mH(e,t){let n=e.helpers??{},r=xC.filter(e=>e!==t.scope).map(e=>({scope:e,ns:SC({scope:e,name:t.name})})),i=new Map,a=(e,n,a)=>{let o=r.find(({ns:e})=>CC(e)(n));if(o===void 0)return;let s=a?`.`:``;i.set(`${e}\0${n}`,{path:e,message:`${e} names ${s}${n}, this plugin under "${o.scope}", but it loads as ${SC(t)}: a plugin names itself without its scope — write ${s}${wC}${n.slice(o.ns.length)}`})},o=[...[...hH(e)].filter(([e])=>!e.startsWith(`helpers.`)),...Object.entries(n).map(([e,t])=>[`helpers.${e}`,t])];for(let[e,t]of o){for(let[r,i]of HC(t,n))i===null&&a(e,r,!0);for(let{name:r,via:i}of KC(t,n))i===null&&a(e,r,!1);for(let n of ew(t,{}))a(e,n,!1)}for(let[t,n]of Object.entries(e.actions??{}))fH(n,(e,n)=>(a(`actions.${t}.${n}`,e,!1),e));let s=[...Object.entries(e.variables??{}).map(([e,t])=>[`variables.${e}`,t]),...Object.entries(e.segments??{}).flatMap(([e,t])=>Object.entries(t.vars??{}).map(([t,n])=>[`segments.${e}.vars.${t}`,n]))];for(let[e,t]of s)if(pb(t)&&`depends_on`in t.cache)for(let n of t.cache.depends_on)a(`${e}.cache.depends_on`,n,!1);return[...i.values()]}function*hH(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of hb(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of pH){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[e,r]of Object.entries(n.partials??{}))yield[`segments.${t}.partials.${e}`,r];for(let[e,r]of Object.entries(n.vars??{}))for(let[n,i]of hb(r))yield[`segments.${t}.vars.${e}.${n}`,i]}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))for(let[e,r]of vS(n))yield[`actions.${t}.${e}`,r]}function gH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,n]))}function _H(e,t){return`${e}.${t}`}function vH(e,t){return t.kind===`state`?{...t,key:_H(e,t.key)}:t}function yH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.vars===void 0?n:{...n,vars:Object.fromEntries(Object.entries(n.vars).map(([t,n])=>[t,vH(e,n)]))}]))}function bH(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:_H(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>_H(e,t))}:n]))}const xH=qV,SH={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function CH(e,t,n){if(!Zy(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${Ib(e)}`}),{};let r=s.join(t,`session`),i=JSON.stringify(SH),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!xH.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${xH}: it is the last segment of .<scope>.<plugin>.${t})`});continue}let s=EH(o,SH,e);for(let{field:e,is:t}of s)n.push({path:e,message:`${e} ${t}: what is built is a source ${i} — a session's JSON file in the plugin's managed storage, re-read when it changes`});s.length===0&&(a[t]={kind:`source`,storage:r})}return a}function wH(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=TH(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=CC(t),a=[...r].filter(([,e])=>e.length>1&&e.some(i)).map(([e,n])=>({path:`sources.${n.find(i).slice(`${t}.`.length)}`,message:`sources ${n.map(e=>`.${e}`).join(` and `)} read the same file, ${e}: a session's file is one document, read by one source`}));if(a.length>0)throw new kb(e,a)}function TH(e){return s.join(e.storage,ZV(`<session id>`))}function EH(e,t,n){return!Zy(t)||!Zy(e)?JSON.stringify(e)===JSON.stringify(t)?[]:[{field:n,is:`is ${JSON.stringify(e)}`}]:[...new Set([...Object.keys(t),...Object.keys(e)])].flatMap(r=>{let i=`${n}.${r}`;return Object.hasOwn(t,r)?Object.hasOwn(e,r)?EH(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function DH(e,t,n,r,i){if(typeof e==`string`&&e!==``)return TP(s.dirname(t),e,r);if(Zy(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(s.isAbsolute(t)||t.startsWith(`~`)||s.normalize(t).split(s.sep)[0]===`..`){i.push({path:`data.checkout`,message:`data.checkout "${t}" must be a path inside the checkout, relative to its root (like ".lit/statusline.json"): no absolute path, "~" or ".."`});return}if(n===null){i.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return s.resolve(n.root,t)}if(Zy(e)&&`project`in e){i.push({path:`data.project`,message:`data: { project } is now data: { checkout }: the same path, relative to the root of the git checkout the session works in (a linked worktree is its own checkout)`});return}i.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { checkout: "<path>" } relative to the root of the session's checkout`})}function OH(e,t){let n=[...[...e.dataDirs].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),kH(e)];return[...n.filter((e,t)=>n.lastIndexOf(e)===t).map(e=>({dir:e,scope:`plugins`})),...t===null?[]:[{dir:s.join(t,AH),scope:`repo`}]]}function kH(e){return s.join(e.dataHome,`cc-candybar`,`plugins`)}const AH=s.join(`.cc-candybar`,`plugins`);function jH(e,t,n){let r=OH(t,n),i=new Map,a=[],o=[];for(let{dir:t,scope:n}of r){let r=MH(e,t);if(`error`in r){a.push(r);continue}for(let e of r.folders){let r=JV(s.join(t,e,KV),n),a=`${n}\0${e}`;i.delete(a),i.set(a,r)}for(let e of r.files)o.push({path:s.join(t,e),scope:n,name:void 0,reason:`a plugin is a folder holding its ${KV}: move this file to ${s.join(t,`<name>`,KV)}`})}return{roots:r.map(e=>e.dir),definitions:[...i.values()],unchecked:a,strays:o}}function MH(e,t){try{let n=e.readdirSync(t).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),r=n=>n.kind===`directory`||NH(e,t,n);return{folders:n.filter(r).map(e=>e.name),files:n.filter(e=>!r(e)).map(e=>e.name)}}catch(n){return _c(e,t)===`absent`?{folders:[],files:[]}:{path:t,error:n.message}}}function NH(e,t,n){if(n.kind!==`symlink`)return!1;try{return e.statSync(s.join(t,n.name)).kind===`directory`}catch{return!0}}const PH=[`json5`,`json`];function FH(e,t,n,r){if(r!==void 0)return[r];let i=n??process.cwd();return[...new Set([...t?PH.map(e=>s.join(t,`${IH}.${e}`)):[],...PH.map(e=>s.join(i,`${IH}.${e}`)),...PH.map(t=>`${LH(e)}.${t}`)])]}const IH=`.cc-candybar`;function LH(e){return s.join(e.configDir,`config`)}function RH(e){return{path:e,scope:`plugins`}}function zH(e,t,n,r,i,a){let o=[],c=new Map;for(let n of FH(t,r,i,a)){let r=_c(e,n);if(r===`absent`)continue;if(r!==`present`){o.push(r);continue}let i=e.realpathSync(s.dirname(n)),l=s.join(i,s.basename(n).replace(/\.(json5|json)$/,``));c.has(l)||c.set(l,{file:n,repo:a!==void 0||BH(t,n)?null:{dir:i,link:Oc(e,i)}})}let l=[...c.values()],u=IP(n,l.flatMap(e=>e.repo===null?[]:[e.repo]),VH(e,r)),d=l.filter(e=>e.repo===null||u.approved.includes(e.repo.dir)).reverse().map(e=>({path:e.file,scope:e.repo===null?`plugins`:`repo`}));if(a===void 0)return{kind:`chain`,layers:d,home:HH(t,d),unchecked:o,repos:u};let[f]=o,p=a;return d.length>0?{kind:`chain`,layers:d,home:p,unchecked:o,repos:u}:f===void 0?{kind:`missing`,path:a,home:p,repos:u}:{kind:`unreadable`,...f,home:p,repos:u}}function BH(e,t){return PH.some(n=>t===`${LH(e)}.${n}`)}function VH(e,t){if(t===void 0||_c(e,t)!==`present`)return null;let n=MH(e,s.join(t,AH)),r=e.realpathSync(t);return{dir:r,link:Oc(e,r),path:t,ships:!(`error`in n)&&n.folders.length>0}}function HH(e,t){return t.find(t=>BH(e,t.path))?.path??`${LH(e)}.${PH[0]}`}function UH(e,t,n,r,i,a,o){let s=zH(e,n,r,i,a,o),c=s.kind===`chain`?s.layers:[];return{path:s.home,above:c.filter(e=>e.path!==s.home),repo:s.repos.plugins,cwd:a??null,locs:n,disk:e,memo:t}}function WH(e){return GH(e).join(`
194
+ `)||null}function GH(e){switch(e.kind){case`chain`:return e.unchecked.map(e=>`Config location could not be checked: ${e.path} — ${e.error}`);case`missing`:return[`Config file not found: ${e.path} — rendering the bundled default until it appears`];case`unreadable`:return[`Config file could not be read: ${e.path} — ${e.error} — rendering the bundled default until it can be`]}}function KH(e,t,n,r){let i=FH(t,n,r).filter(t=>_c(e,t)===`present`),a=new Map;for(let e of i){let t=s.dirname(e),n=s.basename(e).replace(/\.(json5|json)$/,``),r=s.join(t,n);a.has(r)||a.set(r,[]),a.get(r).push(e)}let o=[...a.values()].filter(e=>e.length>1);return o.length===0?null:`config-extension collision: ${o.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}const qH=`repo-configs.json`;function JH(e){return s.join(e,`repo-configs`)}function YH(e){return s.join(JH(e),qH)}function XH(e,t){return _c(e,YH(t))!==`absent`}function ZH(e,t){return Tz(e,XH(e,t)?YH(t):s.join(t,qH),{},RP)}const QH={level:`error`,glyph:`⚠`,colors:ZP},$H={level:`warning`,glyph:`⚠`,colors:QP},eU={level:`warning`,glyph:`⬆`,colors:QP},tU={level:`warning`,glyph:`🔒`,colors:QP},nU={level:`warning`,glyph:`🧪`,colors:QP};function rU(e,t){return{text:eF(e),link:t}}function iU(e,t,n,r,i,a){let o=new Set,s=(e,t)=>{let n=aU(e,t);for(let e of n)o.add(e);return n},c=[...r.flatMap(e=>s(e,QH)),...i,...a.flatMap(e=>s(e,$H))],l=oU(c);return c.map((r,i)=>o.has(r)?{...r,lines:[[rU(r.lines[0][0].text,sU(e,t,n,l[i],i+1))],...r.lines.slice(1)]}:r)}function aU({about:e,text:t,copy:n},r){let[i,...a]=t.split(/\r\n|\r|\n/).map(e=>rU(e,null)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:r,about:e,message:t,copy:n,lines:[i,...a]}]}function oU(e){return dU(e).map(e=>String(e*lU+1))}function sU(e,t,n,r,i){return dC(e,[{verb:aC,args:[t,n,r]}],`copy diagnostic ${i}`)}function cU(e){return e.length===0?null:e.some(e=>e.severity.level===`error`)?`error`:`warning`}const lU=4096;function uU(e){let t=ae(`sha256`).update(`${e.severity.level}\0${e.severity.glyph}\0${e.about}`).digest(`hex`);return Number.parseInt(t.slice(0,9),16)%2**32}function dU(e){let t=new Map;return e.map(e=>{let n=uU(e),r=t.get(n)??0;return t.set(n,r+1),n*256+Math.min(r,255)})}function fU(e,t,n){return String(dU(e)[t]*lU+n+1)}const pU={error:ZP,warning:QP};function mU(e){let t=cU(e),n=e.length,r=pU[t??`warning`];return{label:t===null?``:`⚠ ${n>9?`9+`:n}`,fg:r.fg,bg:r.bg,open:e.length===0?`0`:fU(e,0,0)}}function hU(e,t){let n=Number(e)-1,r=dU(t).indexOf(Math.floor(n/lU));return e===null||r===-1?null:{index:r+1,page:n%lU}}function gU(e,t){return Math.min(20,e??20,...t)}function _U(e,t,n,r,i,a){let{index:o}=t,s=e[o-1],c=bU(a),l=CU(s,c,[]),u=new W({bgcolor:s.severity.colors.bg,color:s.severity.colors.fg}),d=(e,t)=>xU(e,t===null?u:u.withLink(t)),f=(t,i)=>i===null?d(` `,null):d(t,yU(n,r,fU(e,i.index-1,i.page),`show diagnostic ${i.index} of ${e.length} page ${i.page+1}`)),p=(t,a)=>{let s=a>0?{index:o,page:a-1}:o>1?{index:o-1,page:0}:null,l=a<t-1?{index:o,page:a+1}:o<e.length?{index:o+1,page:0}:null,u=e.length>1||t>1,p=t>1?`[${o}/${e.length} ${a+1}/${t}]`:`[${o}/${e.length}]`;return SU([d(`✕`,yU(n,r,`0`)),...u?[f(`‹`,s)]:[],d(p,null),...u?[f(`›`,l)]:[],d(`⧉ copy`,sU(n,r,i,fU(e,o-1,0),o))],c)},m=1;for(;;){let e=Math.max(1,a.rows-m),n=Math.min(lU,Math.ceil(l.length/e)),r=Math.min(t.page,n-1),i=p(n,r);if(i.length>m){m=i.length;continue}let o=l.slice(r*e,(r+1)*e),s=l.length-(r+1)*e,u=r===n-1&&s>0?[...o.slice(0,-1),...SU([d(`… ${s+1} more rows: ⧉ copy has them all`,null)],{...c,wrap:!1})]:o;return[...i,...u]}}function vU(e,t,n,r,i){let{label:a,fg:o,bg:s,open:c}=mU(t),l=a===``?[]:[xU(a,new W({bgcolor:s,color:o}).withLink(yU(n,r,c)))];return CU(e,bU(i),l)}function yU(e,t,n,r){return dC(e,[{verb:PS,args:[t,jS,n]}],r)}function bU(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,colorCompatibility:e.colorCompatibility}}const xU=(e,t)=>new q(`${e} `,{style:t,end:``,overflow:`ignore`}),SU=(e,t)=>bF(e,t).lines.map(e=>({kind:`diagnostic`,runs:e}));function CU(e,t,n){let r=new W({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),i=e=>e===null?r:r.withLink(e),a=Tl(Math.max(2,t.width-1));return e.lines.flatMap((o,s)=>{let c=xU(s===0?e.severity.glyph:` `,r),l=o.flatMap(e=>e.text.split(` `).flatMap(e=>Al(e,a)).map(t=>xU(t,i(e.link)))),u=s===0?n:[];return SU([c,...l,...u],t)})}const wU=(e,t)=>Dz(e,YH(t),()=>ZH(e,t));function TU(e,t,n,r){let i=wU(e,t),a={superseded:[],absent:[],unchecked:[]},o=i.update(t=>{let i=Object.keys(t).filter(e=>e!==n).map(t=>({d:t,found:_c(e,t)}));return a={superseded:i.filter(({d:t,found:r})=>r===`present`&&NP({dir:t,link:Oc(e,t)})===n).map(({d:e})=>e),absent:i.filter(({found:e})=>e===`absent`).map(({d:e})=>e),unchecked:i.flatMap(({found:e})=>typeof e==`object`?[e]:[])},LP(t,n,r,a.superseded)});return o.kind===`failed`?o:F(a)}function EU(e,t,n){return{sessionId:e,action:iC,declaration:t,evaluated:n}}function DU(e,t,n){return e.awaiting.map(e=>{let r=`a cc-candybar config for ${e} — run it?`,i=MP.map(r=>rU(`[${r===`approved`?`approve`:`decline`}]`,dC(n.to,[{verb:iC,args:[t,e,r,n.signer.sign(EU(t,e,r))]}]))),a=[rU(r,null),...i];return{severity:tU,about:`repo-question\0${e}`,message:r,copy:r,lines:[a]}})}function OU(e){return Math.max(1,e-2)}function kU({names:e,helpers:t,actions:n}){let r=(e,t)=>{let i=Object.hasOwn(n,e)?n[e]:void 0;return i===void 0||t.has(e)?[]:(t.add(e),[...[...vS(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=LC(e=>{let i=XC(e,t)?Object.keys(n):KC(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]}),a=LC(n=>i(n).flatMap(n=>[...HC(n,t).keys()].map(t=>({path:t,reaches:aw(t,e)}))));return{ofTemplate:a,calls:LC(e=>new Set(i(e).flatMap(e=>[...QC(e,t)]))),ofVariable:t=>[...hb(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...pb(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function AU(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}const jU=new WeakMap;function MU(e){let t=jU.get(e);return t===void 0&&(t=kU({names:new Set([...iw(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),jU.set(e,t)),t}function NU(e,t){let n=e.segments[t];return n?[...[n.template,n.when,n.bg,n.fg].flatMap(e=>e===void 0?[]:[e]),...Object.values(n.partials??{})]:[]}function PU(e,t){return t===e||t.startsWith(`${e}.`)}function FU(e,t){let n=[];for(let r of ob(aS(e,t).node))r.when!==void 0&&n.push(r.when),r.kind===`segment`&&(r.lead!==void 0&&n.push(r.lead),r.trail!==void 0&&n.push(r.trail));let r=cS(e,t);for(let e of xy){let t=r[e];Sy(t)&&n.push(t)}return n}const IU=e=>e.kind===`shell`||e.kind===`file`;function LU(e,t,n=[]){let r=MU(e),i=new Map(iw(e)),a=[...n,...t.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=AU(e,t);n!==void 0&&s.add(n);for(let{reaches:e}of r.ofVariable(t))a.push(...e)}return s}function RU(e,t,n){return LU(e,[...NU(e,t),...n])}function zU(e){let t=[],n=new Set;for(let r of nS(e.presets)){t.push(...FU(e,r));for(let t of ob(aS(e,r).node))t.kind===`segment`&&n.add(t.name)}for(let r of n)t.push(...NU(e,r));return LU(e,t,[...iw(e)].filter(([,e])=>IU(e)).map(([e])=>e))}function BU(e,t){return e.kind===`absent`?F(`none`):e.kind===`failed`?e:t.kind===`failed`?t:F(t.kind===`ok`?`tracked`:`gone`)}function VU(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?L(`HEAD: ${t.reason}`,t.failedAt):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const HU={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},UU={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function WU(e,t,n){return Object.hasOwn(t,n)?F(t[n]):L(`${e}: unknown state ${JSON.stringify(n)}`,`parse`)}const GU={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,tag:`tag`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function KU(e){return Object.keys(GU).flatMap(t=>{let n=e[t];return n?.kind===`failed`?[`git.${GU[t]}: ${n.reason}`]:[]})}function qU(e,t,n){return t.ok?F(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?I:L(JU(e,t),`read`)}function JU(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??YU(t.stderr)].filter(Boolean).join(`, `)}`}function YU(e){return e.trim().split(`
195
195
  `,1)[0]??``}function XU(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?I:F(n)}function ZU(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?F(t):I}const QU={github:`gh`,gitlab:`glab`};function $U(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const eW=/^[A-Za-z]:[\\/]/;function tW(e){let t=e.trim();if(eW.test(t))return null;let n=t.match(/^(?:[^@/]+@)?(\[[^\]]+\]):(.*)$/)??t.match(/^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.*)$/),r=n?`ssh://${n[1]}/${n[2].replace(/^\/+/,``)}`:t,i;try{i=new URL(r)}catch{return null}return{scheme:i.protocol.replace(/:$/,``),host:i.hostname.toLowerCase(),port:i.port,path:i.pathname.replace(/^\/+/,``).replace(/\/+$/,``)}}function nW(e){return tW(e)?.host||null}function rW(e){let t=nW(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const iW=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function aW(e){let t=qU(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?oW(t.value):[]}}function oW(e){let t=new Map;for(let n of e.split(`
196
196
  `)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function sW(e){return e.urls.find(e=>fW(e)!==null)??e.urls[0]??null}function cW(e){return e.find(e=>e.name===`origin`)??e[0]??null}function lW(e){let t=cW(e);return t?sW(t):null}function uW(e){let t=cW(e);return t?t.urls.find(e=>rW(e)!==null)??sW(t):null}function dW(e){let t=(tW(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function fW(e){let t=tW(e);if(!t)return null;let n=t.scheme===`https`?{scheme:`https`,port:t.port}:t.scheme===`http`?{scheme:`http`,port:t.port}:t.scheme===`ssh`||t.scheme===`git`?{scheme:`https`,port:``}:null;if(!n||!t.host)return null;let r=t.path.replace(/\.git$/,``);if(!r)return null;let i=n.port?`${t.host}:${n.port}`:t.host;return`${n.scheme}://${i}/${r}`}function pW(e){let t=lW(e);return t===null?null:fW(t)}function mW(e,t,n,r){return t.ok?r(t.stdout):$U(t)||t.reason===`non-zero`&&n.test(t.stderr)?I:L(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??YU(t.stderr)].filter(Boolean).join(`, `)}`,`read`)}function hW(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gW(e){let t=`detached`,n=I,r=I,i=I,a=0,o=0,s=0,c=0;for(let l of e.split(`
197
197
  `)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?I:F(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=F(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=F({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function _W(e){let t;try{t=JSON.parse(e)}catch(e){return L(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`,`parse`)}if(!hW(t))return L(`gh pr view: JSON is not an object`,`parse`);let{number:n,state:r,url:i,headRefOid:a}=t;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return L(`gh pr view: missing number/state/url/headRefOid`,`parse`);let o=WU(`gh pr view`,HU,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function vW(e){let t;try{t=JSON.parse(e)}catch(e){return L(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`,`parse`)}if(!hW(t))return L(`glab mr view: JSON is not an object`,`parse`);let n=t.iid,r=t.state,i=t.web_url,a=t.sha;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return L(`glab mr view: missing iid/state/web_url/sha`,`parse`);let o=WU(`glab mr view`,UU,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function yW(e){try{let t=m.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var bW=class{constructor(e,t){this.launcher=e,this.filesystem=t}isGitRepo(e){return vc(this.filesystem,e)}async execGitAsync(e,t){return this.launcher.launch({bin:`git`,args:[...e],cwd:t.cwd,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}resolveEffectiveGitDir(e,t){return this.isWorktree(e)?F(e):t&&this.isGitRepo(t)?F(t):this.isGitRepo(e)?F(e):this.findGitRoot(e)}findGitRoot(e){let t=yc(this.filesystem,e);return t===void 0?I:F(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return L(`git: ${e instanceof Error?e.message:String(e)}`,`read`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=this.findGitRoot(e);if(t.kind!==`ok`)return t;r=t.value}let a=await this.getCoreAsync(r);if(a.kind!==`ok`)return a;let o={branch:a.value.branch,status:a.value.status,aheadBehind:a.value.aheadBehind,head:a.value.oid};t.showWorkingTree&&(o.workingTree=a.value.workingTree),t.showSha&&(o.sha=XU(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showCommittedAt&&(o.committedAt=await this.committedAt(r,a.value.oid)),t.showStashCount&&(o.stashCount=this.getStashCount(r));let s=t.showRepoName||t.showRepoUrl?await this.getRemotesAsync(r):void 0;return s!==void 0&&t.showRepoName&&(o.repoName=XU(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=XU(s,pW)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),F(o)}resolveGitDir(e){return bo(wc(this.filesystem,e),s.join(e,`.git`))}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return m.existsSync(s.join(t,`MERGE_HEAD`))?F(`MERGE`):m.existsSync(s.join(t,`CHERRY_PICK_HEAD`))?F(`CHERRY-PICK`):m.existsSync(s.join(t,`REVERT_HEAD`))?F(`REVERT`):m.existsSync(s.join(t,`BISECT_LOG`))?F(`BISECT`):m.existsSync(s.join(t,`rebase-merge`))||m.existsSync(s.join(t,`rebase-apply`))?F(`REBASE`):I}catch(e){return L(`git operation probe: ${e instanceof Error?e.message:String(e)}`,`read`)}}async getNearestTagAsync(e){return ZU(qU(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestamp(e,t.value):t}commitTimes=new Map;async commitTimestamp(e,t){let n=this.commitTimes.get(t);if(n!==void 0)return this.commitTimes.delete(t),this.commitTimes.set(t,n),n;let r=this.readCommitTimestamp(e,t);for(this.commitTimes.set(t,r),r.then(e=>{e.kind!==`ok`&&this.commitTimes.get(t)===r&&this.commitTimes.delete(t)},()=>{this.commitTimes.get(t)===r&&this.commitTimes.delete(t)});this.commitTimes.size>256;){let e=this.commitTimes.keys().next().value;if(e===void 0)break;this.commitTimes.delete(e)}return r}async readCommitTimestamp(e,t){let n=ZU(qU(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10);return Number.isNaN(r)?L(`git log -1: unparseable timestamp "${n.value}"`,`parse`):F(r)}resolveCommonGitDir(e){return bo(Tc(this.filesystem,e),e)}getStashCount(e){let t=s.join(this.resolveCommonGitDir(this.resolveGitDir(e)),`logs`,`refs`,`stash`),n;try{n=m.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?F(0):L(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`,`read`)}let r=n.trim();return F(r?r.split(`
198
- `).length:0)}async getRemotesAsync(e){let t=yW(s.join(this.resolveCommonGitDir(this.resolveGitDir(e)),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){return aW(await this.execGitAsync(iW,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=lW(e);return(n===null?null:dW(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=uW(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return this.launcher.launch({bin:e,args:[...t],cwd:n.cwd,timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=rW(t);return n===`github`?mW(`gh pr view`,await this.execForgeAsync(QU.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,_W):n===`gitlab`?mW(`glab mr view`,await this.execForgeAsync(QU.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,vW):I}isWorktree(e){try{let t=s.join(e,`.git`);return!!(m.existsSync(t)&&m.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){Pe(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=qU(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F(gW(t.value)):t}};const xW=`#/definitions/LayoutNode`,SW={kind:`container`,direction:`vertical`,children:[]};function CW(e){return{required:!0,json:{const:e},parse:()=>e}}function wW(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${Y(i)}`,line:J(e.source,[`root`])}),``)}}}function TW(){return{required:!0,json:{enum:[...tb]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&tb.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${tb.join(`, `)} (got ${JSON.stringify(i)})`,line:J(e.source,[`root`])}),`vertical`)}}}function EW(e){return{required:!0,json:{type:`array`,items:{$ref:xW}},parse:(t,n,r,i)=>{let a=i[r];return Array.isArray(a)?a.map((i,a)=>e(t,`${n}.${r}[${a}]`,i)):(t.issues.push({path:`${n}.${r}`,message:`a container must have a "children" array of layout nodes, got ${Lb(a)}`,line:J(t.source,[`root`])}),[])}}}const DW={noun:`layout-node key`,fields:{kind:CW(`segment`),name:wW(),when:Gb(),id:IB(),settings:LB()}},OW=()=>Xb(wv),kW={noun:`layout-node key`,fields:{kind:CW(`container`),direction:TW(),children:EW(Wb(()=>PW)),when:Gb(),distribution:OW()}};function AW(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${Y(i)}`,line:J(e.source,[...t.split(`.`),n])}),``)}}}const jW={noun:`layout-node key`,fields:{seg:AW(),when:Gb(),id:IB(),settings:LB()}},MW={noun:`layout-node key`,fields:{h:EW(Wb(()=>PW)),when:Gb(),distribution:OW()}},NW={noun:`layout-node key`,fields:{v:EW(Wb(()=>PW)),when:Gb(),distribution:OW()}},PW=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:J(e.source,[`root`])}),SW):{kind:`segment`,name:n};if(!Qy(n))return e.issues.push({path:t,message:`a layout node must be a string (segment name) or an object with "kind" / "seg" / "h" / "v", got ${Lb(n)}`,line:J(e.source,[`root`])}),SW;if(n.kind===`container`)return Rb(e,kW,t,n)??SW;if(n.kind===`segment`)return Rb(e,DW,t,n)??SW;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
198
+ `).length:0)}async getRemotesAsync(e){let t=yW(s.join(this.resolveCommonGitDir(this.resolveGitDir(e)),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){return aW(await this.execGitAsync(iW,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=lW(e);return(n===null?null:dW(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=uW(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return this.launcher.launch({bin:e,args:[...t],cwd:n.cwd,timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=rW(t);return n===`github`?mW(`gh pr view`,await this.execForgeAsync(QU.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,_W):n===`gitlab`?mW(`glab mr view`,await this.execForgeAsync(QU.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,vW):I}isWorktree(e){try{let t=s.join(e,`.git`);return!!(m.existsSync(t)&&m.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){Pe(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=qU(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F(gW(t.value)):t}};const xW=`#/definitions/LayoutNode`,SW={kind:`container`,direction:`vertical`,children:[]};function CW(e){return{required:!0,json:{const:e},parse:()=>e}}function wW(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${Y(i)}`,line:J(e.source,[`root`])}),``)}}}function TW(){return{required:!0,json:{enum:[...eb]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&eb.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${eb.join(`, `)} (got ${JSON.stringify(i)})`,line:J(e.source,[`root`])}),`vertical`)}}}function EW(e){return{required:!0,json:{type:`array`,items:{$ref:xW}},parse:(t,n,r,i)=>{let a=i[r];return Array.isArray(a)?a.map((i,a)=>e(t,`${n}.${r}[${a}]`,i)):(t.issues.push({path:`${n}.${r}`,message:`a container must have a "children" array of layout nodes, got ${Ib(a)}`,line:J(t.source,[`root`])}),[])}}}const DW={noun:`layout-node key`,fields:{kind:CW(`segment`),name:wW(),when:Wb(),id:IB(),settings:LB()}},OW=()=>Yb(wv),kW={noun:`layout-node key`,fields:{kind:CW(`container`),direction:TW(),children:EW(Ub(()=>PW)),when:Wb(),distribution:OW()}};function AW(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${Y(i)}`,line:J(e.source,[...t.split(`.`),n])}),``)}}}const jW={noun:`layout-node key`,fields:{seg:AW(),when:Wb(),id:IB(),settings:LB()}},MW={noun:`layout-node key`,fields:{h:EW(Ub(()=>PW)),when:Wb(),distribution:OW()}},NW={noun:`layout-node key`,fields:{v:EW(Ub(()=>PW)),when:Wb(),distribution:OW()}},PW=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:J(e.source,[`root`])}),SW):{kind:`segment`,name:n};if(!Zy(n))return e.issues.push({path:t,message:`a layout node must be a string (segment name) or an object with "kind" / "seg" / "h" / "v", got ${Ib(n)}`,line:J(e.source,[`root`])}),SW;if(n.kind===`container`)return Lb(e,kW,t,n)??SW;if(n.kind===`segment`)return Lb(e,DW,t,n)??SW;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
199
199
  Old: { kind: "cells", segments: ["seg1", "seg2"] }
200
- New: { h: ["seg1", "seg2"] }`,line:J(e.source,[`root`])}),SW;if(n.kind===`group`){let r=Rb(e,UW,t,n);return r===null?SW:(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}),GW(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`])}),SW}if(a){let r=Rb(e,jW,t,n);return r===null?SW:{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=Rb(e,MW,t,n);return r===null?SW:{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=Rb(e,NW,t,n);return r===null?SW:{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`])}),SW};function FW(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Bx.source},additionalProperties:{$ref:xW}},parse:(e,t,n,r)=>{let i=r[n];if(!Qy(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${Lb(i)}`,line:J(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!Bx.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]=PW(e,`${t}.${n}.${r}`,o)}return a}}}const IW={noun:`root key`,fields:{rows:FW(),when:Gb(),distribution:OW()}};function LW(e,t,n){return Qy(n)&&`rows`in n?Rb(e,IW,t,n)??{rows:{}}:PW(e,t,n)}const RW={noun:`insert key`,fields:{seg:AW(),id:IB(),before:Gb(),after:Gb()}};function zW(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=Rb(e,RW,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(OS(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 OS(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 ${Lb(t)}`,line:J(e.source,[`insert`])}),[])}function BW(){return{required:!0,json:{type:`string`,pattern:Bx.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Bx.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 "${ma}", got ${Y(i)}`,line:J(e.source,[`root`])});return}return i}}}function VW(){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 ${Y(i)}`,line:J(e.source,[`root`])});return}return i}}}}function HW(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Nb(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 UW={noun:`layout-node key`,fields:{kind:CW(`group`),name:BW(),label:HW(),open:Kb(),direction:Xb(tb),key:VW(),bg:Gb(),fg:Gb(),when:Gb(),distribution:OW(),children:EW(Wb(()=>PW))}};function WW(e){return e.key??`groups.`+e.name}function GW(e){let t=SS+e.name;return ba(t,{variable:t,key:WW(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function KW(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function qW(e,t){JN(e,t,SS,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&KW(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}.`)&&WW(t)===WW(r)&&KW(e,t.path,`group "${t.name}" shares key "${WW(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=WW(t);if(i.has(n)||i.set(n,ma),t.open===!0){let r=i.get(n);r!==`closed`&&KW(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=SS+e.name,r=WW(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=Ea(r,i.get(r)),o[t]=Da(r,e.name),s[t]={template:Ca(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 JW=`menu`,YW=`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`,XW=e=>e.kind===`call`&&e.name===`dict`,ZW=e=>e.kind===`literal`&&typeof e.value!=`object`,QW=e=>_a(``,e,2)===void 0;function $W(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&&XW(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(XW))return t(`whose options (dict …) is not its last argument — ${YW}`);if(i!==void 0&&a===void 0&&!ZW(i)&&QW(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=_a(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${YW}`);let c=a===void 0?{}:MD(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=VM(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=qN(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 "${FM(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 eG(e){let t=iE({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===JW).map($W)}catch{return`parse-failed`}}function tG(e,t){let n=eG(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:PM(t,e.apply,e.options.key),member:NM(e.apply)}]:[])}function nG(e){let t=iE({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(JW)}catch{return!1}}function rG(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function iG(e,t){JN(e,t,CS,`{{ menu }} helpers`),JN(e,t,wS,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))nG(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`&&nG(i)&&rG(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??{}))nG(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 sb(Kx(t.root)))typeof n.when==`string`&&nG(n.when)&&rG(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||!nG(r))continue;let n=eG(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:aG(r.apply);n!==void 0&&rG(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function aG(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(NM(e)===`closed`)return`whose apply action is named "${ma}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function oG(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 rS(e.presets)){let a=new Map,s=new Map;for(let c of sb(oS(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,eG(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=rb(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||aG(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=NM(i),f=PM(u,i,l.key),p=LM(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=IM(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]=Da(f,d),n[f]=Ea(f,ma),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 sG(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const cG={noun:`style key`,fields:{hueShift:qb(),chromaScale:qb({min:0}),lightnessScale:qb(),lightnessShift:qb()}};function lG(e,t){if(!Qy(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${Lb(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(By(r)){e.issues.push({path:`styles.${r}`,message:sG(`styles.${r}`,r,`globals.endcaps`),line:J(e.source,[`styles`,r])});continue}let t=Rb(e,cG,`styles.${r}`,i);t!==null&&(n[r]={...Ru,...t})}return n}const uG={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:LW(e,`${t}.${n}`,r[n])},globals:{required:!1,json:TN(),parse:(e,t,n,r)=>r[n]===void 0?void 0:wN(e,`${t}.${n}`,r[n])}}};function dG(e,t){if(!Qy(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${Lb(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=Rb(e,uG,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function fG(e,t){let n=[...t].map(([e,t])=>[wC(e),t]);return t=>{if(UL(t)||Object.hasOwn(e,t))return{kind:`declared`};let r=n.find(([e])=>e(t));if(r!==void 0)return{kind:`plugin`,definition:r[1]};let i=EC(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function pG(e){return e.kind===`plugin`||e.kind===`missing`}function mG(e,t,n){let r=new Map,i=(e,t)=>{r.set(e,[...r.get(e)??[],t])},a=e=>Ux(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 sb(e))t.kind===`segment`&&i(rb(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 hG(e){let t=0,n=fG(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)?[ob(e,i)]:[],o=e=>a(e)[0]??gG,s=e=>({...e,rows:Object.fromEntries(Object.entries(e.rows).map(([e,t])=>[e,o(t)]))}),c=e=>Ux(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 gG={kind:`container`,direction:`horizontal`,children:[]};function _G(e,t){for(let n of t.reads.calls(e))if(t.clock.has(n))return`calls "${n}"`;for(let{reaches:n}of t.reads.ofTemplate(e))for(let e of n){let n=t.projections.get(e);if(n!==void 0)return`reads "${e}", which ${n}`}return null}const vG=new WeakMap;function yG(e){let t=vG.get(e);return t===void 0&&(t=xG(e),vG.set(e,t)),t}function bG(e){return yG(e).projections}function xG(e){let t=new Map(aw(e)),n=new Map,r={reads:MU(e),projections:n,clock:$A};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=AU(e,r),i=t===void 0?null:DM(t);i&&n.set(e,`reads the draw's "${i}" (${EM[i]})`)}let i=CG(e),a=new Map;for(let e=!0;e;){e=!1;for(let[i,a]of t){if(a.kind!==`template`||n.has(i))continue;let t=_G(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of xy)if(!a.has(t))for(let n of i[t]){let i=_G(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=AU(r,i);if(t===void 0||n.has(r))continue;let o=kM(t),s=o===void 0?void 0:a.get(o);s!==void 0&&(n.set(r,`reads the ${o} rule, which ${s}`),e=!0)}}return r}function SG(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>xy.flatMap(n=>{let r=t[n];return Sy(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function CG(e){let t=SG(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function wG(e,t){return _G(e,yG(t))}function TG(e){return t=>_G(t,e)!==null}const EG={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 DG(e,t){let n=new Map;for(let e of Object.keys(t)){let t=MM(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 OG(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 qx(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const kG=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${CC(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${AG(CC(r.definition),n)}${jG(t,n)}`:`${e} entry "${t}" does not match any declared segment${jG(t,n)}`;function AG(e,t){let n=Object.keys(t).filter(wC(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 jG(e,t){return Nz(e)+DC(e,e=>Object.hasOwn(t,e))}function MG(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||Sy(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:By(r)?sG(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`])}),DG(e,t.presets);let a=cw(t);for(let t of a.names)t!==`settings`&&!t.startsWith(FG)||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)=>{KL(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${kS}" ${KL(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:i}),qL(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${kS}" 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:EG[a](n),line:i});let o=new Map;for(let e of sb(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=rb(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=ab(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`||nb[e.direction]===`cell`);return nb[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:nb[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,cb(t,n)]):e.opens===void 0?[]:[[e.opens.body,lb(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=Kx(n),s=Ux(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:EG[t](n),line:J(e.source,n.split(`.`))});for(let[o,s]of qx(n,i)){let n=J(e.source,s.split(`.`));if(o.when!==void 0&&(ZG(e,`${s}.when`,o.when,a,{line:n}),YG(e,`${s}.when`,o.when,n),XG(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if(UL(o.name)){(o.id!==void 0||o.settings!==void 0)&&e.issues.push({path:s,message:`${i} gives the global settings menu anchor "${kS}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${kS}"`,line:n});continue}let c=r(o.name);pG(c)&&(d.add(o.name),e.unplaced.push({path:s,message:kG(i,o.name,t.segments,c),line:n})),UG(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`,Gx(t.root)]]);for(let e of rS(t.presets)){let{node:n,path:r}=oS(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 ub(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);pG(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:kG(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:J(e.source,n.split(`.`))}))}aK(e,t,a,()=>!0)}const NG=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function PG(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=J(e.source,[`actions`,n,r]);if(!rS(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${rS(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(`, `)})${Nz(i)}`,line:c})},p=new Set(ib(oS(t,a).node)),m=(r,i)=>{!Mz.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${Nz(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 FG=`settings.`;function IG(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>FG+e)])}}function LG(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=BG(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of Tb(n,zG(n)))i(e,`the defaults do not stand together: ${t}`)}function RG(e){return BG(e).length>0||Tb(e,zG(e)).length>0}function zG(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function BG(e){let t=t=>wb(VG(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||wb(VG(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${HG(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 VG(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function HG(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&wb(n)!==void 0).map(([e])=>e)}function UG(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=Cb(a),s=`${r}: placement "${rb(n)}" of segment "${n.name}"`;for(let[t,a]of Object.entries(n.settings??{})){let c=Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0,l=c===void 0?`sets "${t}", which segment "${n.name}" does not declare (it has: ${Object.keys(o).join(`, `)})`:Eb(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?py(a):``}, but it must be ${kb(c)}`;l!==void 0&&e.issues.push({path:r,message:`${s} ${l}`,line:i})}let c=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,n.settings?.[e]??t.default]));if(!(!Object.entries(c).every(([e,t])=>Eb(o[e],t))||RG(o)))for(let{message:t}of Tb(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function WG(e,t,n,r,i){for(let[a,o]of gb(n))ZG(e,`${t}.${a}`,o,r,{segCtx:i})}function GG(e,t,n,r,i){if(!(!mb(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 KG=`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 qG(e,t,n,r){if(!mb(n))return;let i=n=>J(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=wG(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${KG}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=bG(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}: ${KG}`,line:i(`depends_on`)})})}}function JG(e,t){let n=new Map(aw(t)),r=MU(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=xy.find(e=>PU(n,OM[e]));if(e!==void 0)return`reads "${OM[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=AU(e,a),s=o===void 0?void 0:kM(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 SG(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 YG(e,t,n,r){try{KN.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function XG(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 qC(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){$G(e,u,`Template references unknown action "${c}"${r}`,QG(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function ZG(e,t,n,r,i){let a=(n,r)=>{if(r!==null){$G(e,r,n,QG(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 UC(n,r.helpers)){if(sw(e,r))continue;if(e.startsWith(FG)){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&&sw(n,r)?` (segment-local vars are namespaced — write ".${n}")`:Wz(e)}`,t)}for(let{literal:e,problem:t,via:i}of JC(n,r.helpers))a(`Template spells a link ${t}: "${e}". Bind an action instead ({{ action "name" … }}): the bar draws its link`,i)}function QG(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function $G(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 eK(e,t,n,r,i){let a=n.set,o=cN(xx[r].configKey),s=`${a} takes ${GM(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=rK(n,i);if(c===nK){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=>!UM(o,e.value,i));if(l.length!==0){if(a===xx.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>By(e.value)))){let r=xx.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:sG(`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<=tK?r.join(`, `):`${r.slice(0,tK).join(`, `)} and ${r.length-tK} 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 tK=3,nK=Symbol(`any integer`);function rK(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?mS(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)}]:nK}function iK(e,t){return Object.entries(e).filter(([e])=>t(e))}function aK(e,t,n,r){let i=bR(t),a=pS(i);for(let[n,o]of iK(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 ${gS(r,i)}`,line:J(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;Tx.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=kx.get(o.set);s!==void 0&&eK(e,n,o,s,i)}for(let[n,i]of iK(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&&xS(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 iK(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 iK(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=VN(r);if(o===null){let t=kN(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${AN().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=NG.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`){PG(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!rS(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: ${rS(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${py(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(`, `)})${Nz(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 iK(t.variables,r)){WG(e,`variables.${i}`,a,n);let t=Uz(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:J(e.source,[`variables`,i])})}for(let[i,a]of iK(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))WG(e,`segments.${i}.vars.${t}`,r,n,i);let r=Cb(a);if(LG(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=IG({...n,helpers:o},r);for(let n of pH){let c=a[n];typeof c==`string`&&(ZG(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),XG(e,t,`segments.${i}.${n}`,c,J(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of iK(t.variables,r))GG(e,`variables.${i}`,a,n),qG(e,`variables.${i}`,a,t);JG(e,t);for(let[i,a]of iK(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))GG(e,`segments.${i}.vars.${r}`,o,n,i),qG(e,`segments.${i}.vars.${r}`,o,t)}function oK(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=sK(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 sK(e){let t=new Map,n=new Map,r=MU(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 cK(e,t,n){let r=new Map([...iw(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 lK(e){return{...gK,config:Oz(gK.raw,e)}}function uK(e,t,n,r,i){let a=CK(e,t,i,(t,a)=>{let o=tH(YV(r.reads,eH(t,e,r.scope,r.home)),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>mK(t,n,r,e,i)),s=aH(o,r.beneath.dropped);return{inherited:new Set([...RB(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=oH(Oz(a.raw,o.config),s,(a.raw.insert??[]).map(e=>e.seg));return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(WV)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}var dK=class{#e=new WeakMap;layer(e,t,n,r){let i=$y({palettes:[...r??[]].sort(),definitions:e.map(e=>({path:e.path,scope:e.scope,read:e.read}))}),a=this.#e.get(n)??new Map;this.#e.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=tH(e,t,{config:n,rendering:new Map},(e,t,n)=>mK(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}};function fK(e,t,n,r,i){return tH(YV(e,t),{repo:null,checkout:r,home:i},{config:n,rendering:new Map},(e,t,n)=>mK(e,t,n,`<plugin install>`,void 0)).dropped}function pK(e,t,n,r,i,a,o,s){let c={repo:o.repo,checkout:o.cwd===null?null:bc(e,o.cwd),home:n.homeDir},l=jH(e,n,c.repo),u=t.layer(YV(e,l.definitions),c,i,s),d={...u,dropped:[...u.dropped,...l.strays]};a.warned(l.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let f=d.config,p=[];for(let{path:t,scope:n}of r){let r=p.at(-1)?.plugins,i=uK(t,e.readFileSync(t),p.at(-1)?.config??f,{...c,reads:e,scope:n,beneath:{dropped:[...d.dropped,...p.flatMap(e=>e.plugins.dropped)],rendering:r?.rendering??d.rendering}},s);a.warned(i.warnings),p.push({...i,path:t})}let m=new Set(p.flatMap(e=>[...e.plugins.reached])),h=e=>m.has(e.path),g=d.dropped.filter(h),_=d.dropped.filter(e=>!h(e));a.warned(g.map(WV));let v=p.at(-1)?.plugins.rendering??d.rendering,y={checkout:c.checkout,roots:l.roots,loaded:d.loaded,dropped:g,unreached:_,reached:m,rendering:v},b=p.at(-1),x=({warnings:e,...t})=>(a.warned(e),t);if(b===void 0)return{layers:p,base:f,installed:y,...x(_K(lK(f),v,`<default>`,s))};try{return{layers:p,base:f,installed:y,...x(_K(b,v,b.path,s,p.slice(0,-1).reverse()))}}catch(e){for(let[e,t]of p.slice(0,-1).entries())_K(t,t.plugins.rendering,t.path,s,p.slice(0,e).reverse());throw e}}function mK(e,t,n,r,i){if(n){_K(hK(e),new Map,r,i);return}let a=wC(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[],unplaced:[],inherited:[]};if(aK(s,e,cw(e),a),oK(s,e,a),cK(s,e,{checked:a,authored:a}),o.length>0)throw new Ab(r,o)}function hK(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const gK={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function _K(e,t,n=`<config>`,r=new Set(gy()),i=[]){let a=fG(e.config.segments,t),o=yK({...e,path:n},i,a),s=(t,s)=>{let c=sS(e.config,t,o.authored);return vK(e,n,r,i,c.config,a,o.dropped,[...c.notices,...s])};try{return s(o.cells,[])}catch(e){if(!(e instanceof Ab)||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 Ab))throw r;let i=r.issues.filter(e=>!n.has(e.message)).map(e=>e.message).join(`; `);return{...e,refused:[...e.refused,cS(t,`${t.relation} "${t.anchor}", but the bar refuses it there: ${i}`)]}}},{taken:[],refused:[]});return s(r,i)}}function vK({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 Ab(n,[...l,...u.unplaced,...u.inherited],c)};MG(u,a,e,o),oK(u,a),d();let f=xK(n,a.segments,u,o,i,s),p=oG(hG(a),l);d();let m=HR(iR(p)),h=new Set([...iw({variables:e.variables??{},segments:e.segments??{}})].map(([e])=>e));return cK(u,m,{checked:()=>!0,authored:e=>h.has(e)}),d(),{config:m,dropped:f,placed:a,warnings:c}}function yK(e,t,n){let r=[...t].reverse().concat(e),i=mG(e.config,r.flatMap(e=>e.raw.insert??[]),n),a=e=>!i(e.anchor),o=e=>n(e.seg).kind===`declared`,s=e=>pG(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=jb(t.source);return(t.raw.insert??[]).filter(s).map(i=>({file:t.path,issue:{path:i.by.entry,message:kG(i.by.entry,i.seg,e.config.segments,n(i.seg)),line:r(i.by.entry.split(`.`))}}))})}}function bK(e){if(e.length>0)throw new Wee(e)}function xK(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=OG(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:kG(n.layoutKey,a,t,r(a)),line:J(n.layer.source,n.path.split(`.`))})}return[...o].map(([e,t])=>new Uee(e,t))}function SK(e,t,n=new Set(gy()),r=wK){return CK(e,t,n,()=>({inherited:r,layer:null})).raw}function CK(e,t,n,r){let i=TK(e,t),a=Yee(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(gy()),groups:[],unplaced:[],inherited:[]};if(!Qy(i))throw new Ab(e,[{path:``,message:`Config root must be an object, got ${Lb(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:OK({...c,issues:[]},i.plugins)??[],Qy(i.segments)?Object.keys(i.segments):[]),d=EK(c,i,l,$B(e),e);if(s.length>0)throw new Ab(e,s,o);return{raw:d,warnings:o,layer:u}}const wK=new Set;function TK(e,t){try{return Na.default.parse(t)}catch(t){let n=t;throw new Ab(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function EK(e,t,n,r,i){for(let n of Object.keys(t))DK.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...DK].join(`, `)}`,line:J(e.source,[n])});let a={};return t.globals!==void 0&&(a.globals=CN(e,`globals`,t.globals)),t.variables!==void 0&&(a.variables=Zz(e,`variables`,t.variables)),t.segments!==void 0&&(a.segments=zB(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.
200
+ New: { h: ["seg1", "seg2"] }`,line:J(e.source,[`root`])}),SW;if(n.kind===`group`){let r=Lb(e,UW,t,n);return r===null?SW:(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}),GW(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`])}),SW}if(a){let r=Lb(e,jW,t,n);return r===null?SW:{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=Lb(e,MW,t,n);return r===null?SW:{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=Lb(e,NW,t,n);return r===null?SW:{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`])}),SW};function FW(){return{required:!0,json:{type:`object`,propertyNames:{pattern:zx.source},additionalProperties:{$ref:xW}},parse:(e,t,n,r)=>{let i=r[n];if(!Zy(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${Ib(i)}`,line:J(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!zx.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:J(e.source,[...t.split(`.`),n,r])});continue}a[r]=PW(e,`${t}.${n}.${r}`,o)}return a}}}const IW={noun:`root key`,fields:{rows:FW(),when:Wb(),distribution:OW()}};function LW(e,t,n){return Zy(n)&&`rows`in n?Lb(e,IW,t,n)??{rows:{}}:PW(e,t,n)}const RW={noun:`insert key`,fields:{seg:AW(),id:IB(),before:Wb(),after:Wb()}};function zW(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=Lb(e,RW,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(DS(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 DS(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 ${Ib(t)}`,line:J(e.source,[`insert`])}),[])}function BW(){return{required:!0,json:{type:`string`,pattern:zx.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!zx.test(i)||i===`closed`){e.issues.push({path:`${t}.${n}`,message:`a group "name" must be an identifier (letters, digits, _; not starting with a digit) and not the reserved "${ma}", got ${Y(i)}`,line:J(e.source,[`root`])});return}return i}}}function VW(){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 ${Y(i)}`,line:J(e.source,[`root`])});return}return i}}}}function HW(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Mb(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 UW={noun:`layout-node key`,fields:{kind:CW(`group`),name:BW(),label:HW(),open:Gb(),direction:Yb(eb),key:VW(),bg:Wb(),fg:Wb(),when:Wb(),distribution:OW(),children:EW(Ub(()=>PW))}};function WW(e){return e.key??`groups.`+e.name}function GW(e){let t=xS+e.name;return ba(t,{variable:t,key:WW(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function KW(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function qW(e,t){JN(e,t,xS,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&KW(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}.`)&&WW(t)===WW(r)&&KW(e,t.path,`group "${t.name}" shares key "${WW(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=WW(t);if(i.has(n)||i.set(n,ma),t.open===!0){let r=i.get(n);r!==`closed`&&KW(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=xS+e.name,r=WW(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=Ea(r,i.get(r)),o[t]=Da(r,e.name),s[t]={template:Ca(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 JW=`menu`,YW=`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`,XW=e=>e.kind===`call`&&e.name===`dict`,ZW=e=>e.kind===`literal`&&typeof e.value!=`object`,QW=e=>_a(``,e,2)===void 0;function $W(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&&XW(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(XW))return t(`whose options (dict …) is not its last argument — ${YW}`);if(i!==void 0&&a===void 0&&!ZW(i)&&QW(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=_a(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${YW}`);let c=a===void 0?{}:MD(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=VM(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=qN(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 "${FM(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 eG(e){let t=rE({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===JW).map($W)}catch{return`parse-failed`}}function tG(e,t){let n=eG(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:PM(t,e.apply,e.options.key),member:NM(e.apply)}]:[])}function nG(e){let t=rE({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(JW)}catch{return!1}}function rG(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function iG(e,t){JN(e,t,SS,`{{ menu }} helpers`),JN(e,t,CS,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))nG(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`&&nG(i)&&rG(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??{}))nG(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 ob(Gx(t.root)))typeof n.when==`string`&&nG(n.when)&&rG(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||!nG(r))continue;let n=eG(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:aG(r.apply);n!==void 0&&rG(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function aG(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(NM(e)===`closed`)return`whose apply action is named "${ma}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function oG(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 nS(e.presets)){let a=new Map,s=new Map;for(let c of ob(aS(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,eG(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=nb(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||aG(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=NM(i),f=PM(u,i,l.key),p=LM(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=IM(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]=Da(f,d),n[f]=Ea(f,ma),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 sG(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const cG={noun:`style key`,fields:{hueShift:Kb(),chromaScale:Kb({min:0}),lightnessScale:Kb(),lightnessShift:Kb()}};function lG(e,t){if(!Zy(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${Ib(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(zy(r)){e.issues.push({path:`styles.${r}`,message:sG(`styles.${r}`,r,`globals.endcaps`),line:J(e.source,[`styles`,r])});continue}let t=Lb(e,cG,`styles.${r}`,i);t!==null&&(n[r]={...Ru,...t})}return n}const uG={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:LW(e,`${t}.${n}`,r[n])},globals:{required:!1,json:TN(),parse:(e,t,n,r)=>r[n]===void 0?void 0:wN(e,`${t}.${n}`,r[n])}}};function dG(e,t){if(!Zy(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${Ib(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=Lb(e,uG,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function fG(e,t){let n=[...t].map(([e,t])=>[CC(e),t]);return t=>{if(UL(t)||Object.hasOwn(e,t))return{kind:`declared`};let r=n.find(([e])=>e(t));if(r!==void 0)return{kind:`plugin`,definition:r[1]};let i=TC(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function pG(e){return e.kind===`plugin`||e.kind===`missing`}function mG(e,t,n){let r=new Map,i=(e,t)=>{r.set(e,[...r.get(e)??[],t])},a=e=>Hx(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 ob(e))t.kind===`segment`&&i(nb(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 hG(e){let t=0,n=fG(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)?[ab(e,i)]:[],o=e=>a(e)[0]??gG,s=e=>({...e,rows:Object.fromEntries(Object.entries(e.rows).map(([e,t])=>[e,o(t)]))}),c=e=>Hx(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 gG={kind:`container`,direction:`horizontal`,children:[]};function _G(e,t){for(let n of t.reads.calls(e))if(t.clock.has(n))return`calls "${n}"`;for(let{reaches:n}of t.reads.ofTemplate(e))for(let e of n){let n=t.projections.get(e);if(n!==void 0)return`reads "${e}", which ${n}`}return null}const vG=new WeakMap;function yG(e){let t=vG.get(e);return t===void 0&&(t=xG(e),vG.set(e,t)),t}function bG(e){return yG(e).projections}function xG(e){let t=new Map(iw(e)),n=new Map,r={reads:MU(e),projections:n,clock:$A};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=AU(e,r),i=t===void 0?null:DM(t);i&&n.set(e,`reads the draw's "${i}" (${EM[i]})`)}let i=CG(e),a=new Map;for(let e=!0;e;){e=!1;for(let[i,a]of t){if(a.kind!==`template`||n.has(i))continue;let t=_G(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of xy)if(!a.has(t))for(let n of i[t]){let i=_G(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=AU(r,i);if(t===void 0||n.has(r))continue;let o=kM(t),s=o===void 0?void 0:a.get(o);s!==void 0&&(n.set(r,`reads the ${o} rule, which ${s}`),e=!0)}}return r}function SG(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>xy.flatMap(n=>{let r=t[n];return Sy(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function CG(e){let t=SG(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function wG(e,t){return _G(e,yG(t))}function TG(e){return t=>_G(t,e)!==null}const EG={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 DG(e,t){let n=new Map;for(let e of Object.keys(t)){let t=MM(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 OG(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 Kx(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const kG=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${SC(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${AG(SC(r.definition),n)}${jG(t,n)}`:`${e} entry "${t}" does not match any declared segment${jG(t,n)}`;function AG(e,t){let n=Object.keys(t).filter(CC(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 jG(e,t){return Nz(e)+EC(e,e=>Object.hasOwn(t,e))}function MG(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||Sy(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:zy(r)?sG(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`])}),DG(e,t.presets);let a=sw(t);for(let t of a.names)t!==`settings`&&!t.startsWith(FG)||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)=>{KL(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${OS}" ${KL(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:i}),qL(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${OS}" 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:EG[a](n),line:i});let o=new Map;for(let e of ob(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=nb(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=ib(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`||tb[e.direction]===`cell`);return tb[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:tb[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,sb(t,n)]):e.opens===void 0?[]:[[e.opens.body,cb(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=Gx(n),s=Hx(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:EG[t](n),line:J(e.source,n.split(`.`))});for(let[o,s]of Kx(n,i)){let n=J(e.source,s.split(`.`));if(o.when!==void 0&&(ZG(e,`${s}.when`,o.when,a,{line:n}),YG(e,`${s}.when`,o.when,n),XG(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if(UL(o.name)){(o.id!==void 0||o.settings!==void 0)&&e.issues.push({path:s,message:`${i} gives the global settings menu anchor "${OS}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${OS}"`,line:n});continue}let c=r(o.name);pG(c)&&(d.add(o.name),e.unplaced.push({path:s,message:kG(i,o.name,t.segments,c),line:n})),UG(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`,Wx(t.root)]]);for(let e of nS(t.presets)){let{node:n,path:r}=aS(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 lb(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);pG(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:kG(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:J(e.source,n.split(`.`))}))}aK(e,t,a,()=>!0)}const NG=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function PG(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=J(e.source,[`actions`,n,r]);if(!nS(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${nS(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(`, `)})${Nz(i)}`,line:c})},p=new Set(rb(aS(t,a).node)),m=(r,i)=>{!Mz.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${Nz(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 FG=`settings.`;function IG(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>FG+e)])}}function LG(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=BG(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of wb(n,zG(n)))i(e,`the defaults do not stand together: ${t}`)}function RG(e){return BG(e).length>0||wb(e,zG(e)).length>0}function zG(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function BG(e){let t=t=>Cb(VG(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||Cb(VG(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${HG(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 VG(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function HG(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&Cb(n)!==void 0).map(([e])=>e)}function UG(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=Sb(a),s=`${r}: placement "${nb(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(`, `)})`:Tb(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?py(a):``}, but it must be ${Ob(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])=>Tb(o[e],t))||RG(o)))for(let{message:t}of wb(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function WG(e,t,n,r,i){for(let[a,o]of hb(n))ZG(e,`${t}.${a}`,o,r,{segCtx:i})}function GG(e,t,n,r,i){if(!(!pb(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 KG=`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 qG(e,t,n,r){if(!pb(n))return;let i=n=>J(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=wG(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${KG}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=bG(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}: ${KG}`,line:i(`depends_on`)})})}}function JG(e,t){let n=new Map(iw(t)),r=MU(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=xy.find(e=>PU(n,OM[e]));if(e!==void 0)return`reads "${OM[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=AU(e,a),s=o===void 0?void 0:kM(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 SG(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 YG(e,t,n,r){try{KN.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function XG(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 KC(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){$G(e,u,`Template references unknown action "${c}"${r}`,QG(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function ZG(e,t,n,r,i){let a=(n,r)=>{if(r!==null){$G(e,r,n,QG(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 HC(n,r.helpers)){if(ow(e,r))continue;if(e.startsWith(FG)){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&&ow(n,r)?` (segment-local vars are namespaced — write ".${n}")`:Wz(e)}`,t)}for(let{literal:e,problem:t,via:i}of qC(n,r.helpers))a(`Template spells a link ${t}: "${e}". Bind an action instead ({{ action "name" … }}): the bar draws its link`,i)}function QG(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function $G(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 eK(e,t,n,r,i){let a=n.set,o=cN(bx[r].configKey),s=`${a} takes ${GM(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=rK(n,i);if(c===nK){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=>!UM(o,e.value,i));if(l.length!==0){if(a===bx.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>zy(e.value)))){let r=bx.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:sG(`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<=tK?r.join(`, `):`${r.slice(0,tK).join(`, `)} and ${r.length-tK} 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 tK=3,nK=Symbol(`any integer`);function rK(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?pS(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)}]:nK}function iK(e,t){return Object.entries(e).filter(([e])=>t(e))}function aK(e,t,n,r){let i=bR(t),a=fS(i);for(let[n,o]of iK(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 ${hS(r,i)}`,line:J(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;wx.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=Ox.get(o.set);s!==void 0&&eK(e,n,o,s,i)}for(let[n,i]of iK(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&&bS(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 iK(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 iK(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=VN(r);if(o===null){let t=kN(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${AN().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=NG.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`){PG(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!nS(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: ${nS(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${py(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(`, `)})${Nz(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 iK(t.variables,r)){WG(e,`variables.${i}`,a,n);let t=Uz(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:J(e.source,[`variables`,i])})}for(let[i,a]of iK(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))WG(e,`segments.${i}.vars.${t}`,r,n,i);let r=Sb(a);if(LG(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=IG({...n,helpers:o},r);for(let n of pH){let c=a[n];typeof c==`string`&&(ZG(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),XG(e,t,`segments.${i}.${n}`,c,J(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of iK(t.variables,r))GG(e,`variables.${i}`,a,n),qG(e,`variables.${i}`,a,t);JG(e,t);for(let[i,a]of iK(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))GG(e,`segments.${i}.vars.${r}`,o,n,i),qG(e,`segments.${i}.vars.${r}`,o,t)}function oK(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=sK(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 sK(e){let t=new Map,n=new Map,r=MU(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 cK(e,t,n){let r=new Map([...rw(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 lK(e){return{...gK,config:Oz(gK.raw,e)}}function uK(e,t,n,r,i){let a=CK(e,t,i,(t,a)=>{let o=tH(YV(r.reads,eH(t,e,r.scope,r.home)),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>mK(t,n,r,e,i)),s=aH(o,r.beneath.dropped);return{inherited:new Set([...RB(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=oH(Oz(a.raw,o.config),s,(a.raw.insert??[]).map(e=>e.seg));return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(WV)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}var dK=class{#e=new WeakMap;layer(e,t,n,r){let i=Qy({palettes:[...r??[]].sort(),definitions:e.map(e=>({path:e.path,scope:e.scope,read:e.read}))}),a=this.#e.get(n)??new Map;this.#e.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=tH(e,t,{config:n,rendering:new Map},(e,t,n)=>mK(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}};function fK(e,t,n,r,i){return tH(YV(e,t),{repo:null,checkout:r,home:i},{config:n,rendering:new Map},(e,t,n)=>mK(e,t,n,`<plugin install>`,void 0)).dropped}function pK(e,t,n,r,i,a,o,s){let c={repo:o.repo,checkout:o.cwd===null?null:bc(e,o.cwd),home:n.homeDir},l=jH(e,n,c.repo),u=t.layer(YV(e,l.definitions),c,i,s),d={...u,dropped:[...u.dropped,...l.strays]};a.warned(l.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let f=d.config,p=[];for(let{path:t,scope:n}of r){let r=p.at(-1)?.plugins,i=uK(t,e.readFileSync(t),p.at(-1)?.config??f,{...c,reads:e,scope:n,beneath:{dropped:[...d.dropped,...p.flatMap(e=>e.plugins.dropped)],rendering:r?.rendering??d.rendering}},s);a.warned(i.warnings),p.push({...i,path:t})}let m=new Set(p.flatMap(e=>[...e.plugins.reached])),h=e=>m.has(e.path),g=d.dropped.filter(h),_=d.dropped.filter(e=>!h(e));a.warned(g.map(WV));let v=p.at(-1)?.plugins.rendering??d.rendering,y={checkout:c.checkout,roots:l.roots,loaded:d.loaded,dropped:g,unreached:_,reached:m,rendering:v},b=p.at(-1),x=({warnings:e,...t})=>(a.warned(e),t);if(b===void 0)return{layers:p,base:f,installed:y,...x(_K(lK(f),v,`<default>`,s))};try{return{layers:p,base:f,installed:y,...x(_K(b,v,b.path,s,p.slice(0,-1).reverse()))}}catch(e){for(let[e,t]of p.slice(0,-1).entries())_K(t,t.plugins.rendering,t.path,s,p.slice(0,e).reverse());throw e}}function mK(e,t,n,r,i){if(n){_K(hK(e),new Map,r,i);return}let a=CC(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[],unplaced:[],inherited:[]};if(aK(s,e,sw(e),a),oK(s,e,a),cK(s,e,{checked:a,authored:a}),o.length>0)throw new kb(r,o)}function hK(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const gK={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function _K(e,t,n=`<config>`,r=new Set(gy()),i=[]){let a=fG(e.config.segments,t),o=yK({...e,path:n},i,a),s=(t,s)=>{let c=oS(e.config,t,o.authored);return vK(e,n,r,i,c.config,a,o.dropped,[...c.notices,...s])};try{return s(o.cells,[])}catch(e){if(!(e instanceof kb)||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 kb))throw r;let i=r.issues.filter(e=>!n.has(e.message)).map(e=>e.message).join(`; `);return{...e,refused:[...e.refused,sS(t,`${t.relation} "${t.anchor}", but the bar refuses it there: ${i}`)]}}},{taken:[],refused:[]});return s(r,i)}}function vK({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 kb(n,[...l,...u.unplaced,...u.inherited],c)};MG(u,a,e,o),oK(u,a),d();let f=xK(n,a.segments,u,o,i,s),p=oG(hG(a),l);d();let m=HR(iR(p)),h=new Set([...rw({variables:e.variables??{},segments:e.segments??{}})].map(([e])=>e));return cK(u,m,{checked:()=>!0,authored:e=>h.has(e)}),d(),{config:m,dropped:f,placed:a,warnings:c}}function yK(e,t,n){let r=[...t].reverse().concat(e),i=mG(e.config,r.flatMap(e=>e.raw.insert??[]),n),a=e=>!i(e.anchor),o=e=>n(e.seg).kind===`declared`,s=e=>pG(n(e.seg)),c=e=>(e.raw.insert??[]).filter(a);return{cells:r.flatMap(e=>c(e).filter(o)),authored:{root:r.some(e=>e.raw.root!==void 0),presets:new Set(r.flatMap(e=>Object.keys(e.raw.presets??{})))},dropped:r.flatMap(t=>{let r=Ab(t.source);return(t.raw.insert??[]).filter(s).map(i=>({file:t.path,issue:{path:i.by.entry,message:kG(i.by.entry,i.seg,e.config.segments,n(i.seg)),line:r(i.by.entry.split(`.`))}}))})}}function bK(e){if(e.length>0)throw new Gee(e)}function xK(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=OG(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:kG(n.layoutKey,a,t,r(a)),line:J(n.layer.source,n.path.split(`.`))})}return[...o].map(([e,t])=>new Wee(e,t))}function SK(e,t,n=new Set(gy()),r=wK){return CK(e,t,n,()=>({inherited:r,layer:null})).raw}function CK(e,t,n,r){let i=TK(e,t),a=Xee(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(gy()),groups:[],unplaced:[],inherited:[]};if(!Zy(i))throw new kb(e,[{path:``,message:`Config root must be an object, got ${Ib(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:OK({...c,issues:[]},i.plugins)??[],Zy(i.segments)?Object.keys(i.segments):[]),d=EK(c,i,l,$B(e),e);if(s.length>0)throw new kb(e,s,o);return{raw:d,warnings:o,layer:u}}const wK=new Set;function TK(e,t){try{return Na.default.parse(t)}catch(t){let n=t;throw new kb(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function EK(e,t,n,r,i){for(let n of Object.keys(t))DK.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...DK].join(`, `)}`,line:J(e.source,[n])});let a={};return t.globals!==void 0&&(a.globals=CN(e,`globals`,t.globals)),t.variables!==void 0&&(a.variables=Zz(e,`variables`,t.variables)),t.segments!==void 0&&(a.segments=zB(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.
201
201
  Replace: layout: [["seg1", "seg2"], ["seg3"]]
202
202
  With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
203
- Single-row example: root: { h: ["seg1", "seg2"] }`,line:J(e.source,[`layout`])}),t.root!==void 0&&(a.root=LW(e,`root`,t.root)),t.insert!==void 0&&(a.insert=zW(e,t.insert,i)),t.actions!==void 0&&(a.actions=ZB(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=lG(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=SN(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=dG(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=EN(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=XB(e,t.helpers)),t.plugins!==void 0&&(a.plugins=OK(e,t.plugins)),qW(e,a),iG(e,a),oP(e,a),JN(e,a,ES,`the global settings menu`),YN(e,a,n),a}const DK=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function OK(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 ${Lb(t)}`,line:J(e.source,[`plugins`])})}const kK={},AK=gI(`commands.`),jK=SI(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),MK=uI(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),NK=`{{ ${CP} }}`,PK={min:0,max:100,step:5},FK={warnAt:{label:`warning at %`,domain:PK,default:50},errorAt:{label:`error at %`,domain:{...PK,atLeast:`warnAt`},default:80}};function IK(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:PK,default:80}}}const LK={globals:{palette:`tokyo-night`},variables:{...AK.variables,...TM,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:`⊫`},...MK.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:NK},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 ${MK.armed} }}{{ if ne .git.branch "" }} {{ end }}${MK.template}{{ end }}`,fg:NK,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if eq .git.prState "open" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (eq .git.prState "open") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:iI(``).template},commands:{group:`session-tools`,description:`Type /compact, /model or /clear into this session; /clear asks for a second click. Hidden when not inside tmux.`,template:AK.template,when:AK.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:IK(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:IK(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:FK,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:FK,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) ${Hv} }}`,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:jK.template,bg:jK.bg,when:jK.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...iI(``).actions,...AK.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...MK.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...jK.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:kK,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 ${Hv} }}{{ \$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 (${CP}) 2 (readableOn (color "accent") (bgOf) ${Hv})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Hv}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ $age := .git.timeSinceCommit }}{{ if and .settings.age (gt $age 0) }} ◷ {{ template "formatTimeSince" $age }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:CI(`.`),formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatToolTally:`{{ $names := splitList "," . }}{{ range $i, $pair := $names }}{{ if lt $i 2 }}{{ if $i }} {{ end }}{{ $kv := splitList ":" $pair }}{{ index $kv 0 }}{{ if ne (index $kv 1) "1" }}×{{ index $kv 1 }}{{ end }}{{ end }}{{ end }}{{ if gt (len $names) 2 }} +{{ sub (len $names) 2 }}{{ end }}`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},RK=new Set([LK.globals.palette,...Object.keys(LK.themeDefaults),...Object.values(LK.segments).map(e=>e.palette)].filter(e=>e!==void 0)),zK=Oz(SK(`<default>`,JSON.stringify(LK),RK),LK),BK=rS(zK.presets);function VK(e){return BK.includes(e)}function HK(e){return e.input+e.output+e.cacheCreation+e.cacheRead}const UK={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0};function WK(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function GK(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function KK(e,t,n){return{[GK(ot(e))]:{...UK,cost:t,input:n}}}function qK(e,t){let n=GK(ot(t)),r=e.sums[n],i=e.own[n];if(r===void 0&&i===void 0)return I;let a={...UK};return r!==void 0&&WK(a,r),i!==void 0&&WK(a,i),F({cost:a.cost,tokens:HK(a),tokenBreakdown:{input:a.input,output:a.output,cacheCreation:a.cacheCreation,cacheRead:a.cacheRead},date:n})}function JK(e,t,n){return wn({dir:e.project_dir,env:n===void 0?[]:[[Go,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}const YK=[`session`,`today`,`speed`,`context`,`metrics`,`activity`,`cache`,`autocompact`,`git`,`pr`,`tmux`,`hostName`,`hostUser`];function XK(e){let t=new Set(e);return t.has(`pr`)&&t.add(`git`),new Set(YK.filter(e=>t.has(e)))}function ZK(e,t){return e.builtins[t]??Co(t)}function QK(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function $K(e){return{...Object.fromEntries(px.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:VK(e.preset)}}}const eq={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function tq(e){if(Eo(e))return`pending`;if(wo(e))return`undeclared`;let{prState:t,prError:n,prEarlier:r}=e??{};return Eo(t)?`pending`:wo(t)?`undeclared`:t===void 0?n===void 0?r===void 0?`-`:`earlier-${String(r)}`:`failed`:t}const nq=10*1e3;function rq(e,t){if(!(t<60))return e*3600/t}function iq(e,t,n,r){let i=r-t;if(i<50||i>nq)return;let a=n-e;if(!(a<=0))return a*1e3/i}function aq(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=iq(t.input,t.atMs,n.input,n.atMs),i=iq(t.output,t.atMs,n.output,n.atMs),a=iq(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function oq(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>nq)continue;let o=iq(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function sq(e){return OU(e.termCols??120)}function cq(e,t){return Jo(qo(e.claudeConfigDir,t))}function lq(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}function uq(e){return Object.entries(e)}function dq(e){return e.kind===`pending`&&e.why===`unread`?e.landed:null}function fq(e){return{current:()=>e.current(),refresh:null,landing:()=>dq(e.current()),fault:()=>null}}const pq=e=>fq(Fj(e));function mq(e,t){return{current:()=>{let n=e.current();return n.kind===`ok`?F(t(n.value)):n}}}function hq({owners:e,facts:t},n,r,i){let a=t.hookData.session_id,o=()=>e.faults.of(a,n);return{current:()=>{let t=o();if(t!==void 0)return t;try{return r()}catch(t){return e.log(`error`,`${n} read threw: ${O(t)}`),L(`${n}: ${String(t)}`,`read`)}},refresh:{lane:n,run:i},landing:()=>null,fault:()=>{let e=o();return e===void 0?null:{lane:n,reason:e.reason}}}}function gq(e){switch(e.kind){case`pending`:case`failed`:return e;case`absent`:return I;case`ok`:return e.value.pullRequest??So(`unread`)}}function _q({pullRequest:e,...t}){return t}const vq={session:e=>hq(e,`session`,()=>e.owners.usageStore.usageOf(e.facts.hookData.session_id,e.facts.hookData),t=>t.usage().usage(e.facts.hookData)),today:e=>{let t=e.owners.usageStore.declareToday(e.holds,e.facts.hints.claudeConfigDir);return hq(e,`today`,()=>Tq(t,e.owners.usageStore,e.facts.hookData.session_id),e=>e.usage().today())},speed:e=>hq(e,`speed`,()=>e.owners.usageStore.speedOf(e.facts.hookData.session_id),e=>e.usage().speed(ot(e.at).getTime())),context:e=>hq(e,`context`,()=>e.owners.contextProvider.contextOf(e.facts.hookData),()=>e.owners.contextProvider.getContextInfo(e.facts.hookData)),metrics:e=>hq(e,`metrics`,()=>e.owners.metricsProvider.metricsOf(e.facts.hookData.session_id,e.facts.hookData),()=>e.owners.metricsProvider.getMetricsInfo(e.facts.hookData.session_id,e.facts.hookData)),activity:e=>hq(e,`activity`,()=>e.owners.activityProvider.activityOf(e.facts.hookData.session_id),()=>e.owners.activityProvider.getActivityInfo(e.facts.hookData.session_id,e.facts.hookData)),cache:e=>hq(e,`cache`,()=>e.owners.cacheExpiry.expiryOf(e.facts.hookData.session_id),()=>e.owners.cacheExpiry.refresh(e.facts.hookData.session_id,e.facts.hookData.transcript_path)),autocompact:e=>{let t=()=>cq(e.facts.hints,e.owners.home);return hq(e,`autocompact`,()=>e.owners.autoCompact.stored(t()),async()=>e.owners.autoCompact.window(t()))},git:e=>fq(mq(e.repo(),_q)),pr:e=>{let t=e.repo();return{current:()=>gq(t.current()),refresh:null,landing:()=>null,fault:()=>null}},tmux:e=>{let t=e.facts.hints.tmux??null;return t===null?pq(I):fq(mq(e.owners.tmuxService.declare(e.holds,t),e=>({session:e})))},hostName:e=>fq(e.owners.hostService.declareName(e.holds)),hostUser:e=>fq(e.owners.hostService.declareUser(e.holds))};async function yq(e,t,n){let{hookData:r,deps:i}=e,a=r.session_id,o,s={at:t,usage:()=>o??=i.usageStore.request(a,r.transcript_path)},c=async({lane:e,run:t})=>{let r=i.clock.monotonic();n.set(e,null);let o=null;try{await t(s)}catch(t){i.log(`error`,`${e} lane threw: ${O(t)}`),o=`${e}: ${String(t)}`}n.set(e,Qe(i.clock,r)),i.faults.refreshed(a,e,o)};await Promise.all(uq(i.lanes().builtins).flatMap(([,e])=>e.refresh===null?[]:[c(e.refresh)]))}function bq(e,{builtins:t,sources:n}){return{builtins:Object.fromEntries([...t].map(t=>[t,pq(e)])),sources:new Map([...n.keys()].map(t=>[t,Fj(e)]))}}const xq={showSha:!0,showWorkingTree:!0,showStashCount:!0,showUpstream:!0,showRepoName:!0,showRepoUrl:!0,showOperation:!0,showCommittedAt:!0};function Sq({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,{...xq,showPullRequest:n.has(`pr`)},t.workspace?.project_dir]}function Cq(e,t,n,{builtins:r,sources:i}){let a=[],o=(e,t,n)=>{try{return t()}catch(t){return a.push(`${e}: ${O(t)}`),n(L(`${e}: ${String(t)}`,`read`))}},s,c={owners:e,holds:t,facts:n,repo:()=>s??=o(`git`,()=>e.gitProvider.declare(t,...Sq(n,r)),Fj)};return{lanes:{builtins:Object.fromEntries([...r].map(e=>[e,o(e,()=>vq[e](c),pq)])),sources:new Map([...i].map(([r,i])=>[r,o(r,()=>e.managedStorage.declare(t,i,n.sessionId),Fj)]))},faults:a}}function wq({deps:e}){let{builtins:t,sources:n}=e.lanes(),r=uq(t);return{builtins:Object.fromEntries(r.map(([e,t])=>[e,t.current()])),sources:new Map([...n].map(([e,t])=>[e,t.current()])),faults:r.flatMap(([,e])=>e.fault()??[])}}function Tq(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:F({sums:r.value.sums,own:i.kind===`ok`?i.value:{}})}function Eq(e){return[...uq(e.builtins).map(([,e])=>e.landing()),...[...e.sources.values()].map(e=>dq(e.current()))].flatMap(e=>e===null?[]:[e])}const Dq=e=>{switch(e.kind){case`pending`:return e;case`absent`:return I;case`ok`:return F(e.value);case`failed`:return L(e.reason,e.failedAt)}};function Oq(e,t){switch(e.kind){case`pending`:return So(e.why);case`failed`:case`absent`:return;case`ok`:return t(e.value)}}const kq=e=>e.kind===`ok`?e.value:void 0;function Aq(...e){let t=e.find(e=>e.kind===`pending`);return t?.kind===`pending`?So(t.why):void 0}const jq=(e,t,n={})=>({phase:`turn`,facts:e,parts:n,compose:t}),Mq={session:jq([`session`],({session:e})=>Oq(e,e=>$q({cost:e.session.cost,tokens:e.session.tokens}))),burn:jq([`session`,`metrics`],({session:e,metrics:t})=>Aq(e,t)??Kq(kq(e)?.session.cost,kq(t)?.sessionDuration)),speed:jq([`speed`],({speed:e})=>Oq(e,qq)),cache:jq([`cache`],({cache:e})=>Oq(e,e=>({expiresAt:e}))),context:jq([`context`],({context:e})=>Oq(e,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage}))),metrics:jq([`metrics`],({metrics:e})=>Oq(e,e=>$q({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved}))),activity:jq([`activity`],({activity:e})=>Oq(e,Zq)),autocompact:jq([`autocompact`,`context`],({autocompact:e,context:t})=>Aq(t)??Xq(e,kq(t)?.maxTokens)),git:jq([`git`],({git:e,pr:t})=>e.kind===`pending`?So(e.why):e.kind===`ok`?tJ(e.value,t):void 0,{pr:Object.keys(eq)}),"tmux.session":jq([`tmux`],({tmux:e})=>e.kind===`pending`?So(e.why):kq(e)?.session),"host.name":jq([`hostName`],({hostName:e})=>e.kind===`pending`?So(e.why):kq(e)),"host.user":jq([`hostUser`],({hostUser:e})=>e.kind===`pending`?So(e.why):kq(e)),today:((e,t)=>({phase:`draw`,facts:e,parts:{},project:t}))([`today`],({today:e},t)=>Jq(e,t))},Nq=Mq,Pq=Mq,Fq=Object.entries({...Nq,...Pq});function Iq(e,t){let n={};for(let r of t.facts){let t=ZK(e,r);if(t.kind===`undeclared`)return t;n[r]=Dq(t)}for(let r of Object.keys(t.parts)){let t=ZK(e,r);n[r]=t.kind===`undeclared`?t:Dq(t)}return n}function Lq(e,t){let n=Iq(e,Nq[t]);return wo(n)?n:Nq[t].compose(n)}function Rq(e,t,n){let r=Iq(e,Pq[t]);return wo(r)?r:Pq[t].project(r,n)}function zq(e,t){return{today:Rq(e,`today`,t)}}function Bq(e){let t=new Set;for(let n of e)for(let[e,r]of Fq)if(!(!PU(e,n)&&!PU(n,e))){for(let e of r.facts)t.add(e);for(let[i,a]of Object.entries(r.parts))(PU(n,e)||a.some(t=>PU(`${e}.${t}`,n)))&&t.add(i)}return XK(t)}function Vq(e,t,n){let{hookData:r,hints:i}=t,{effective:a,configFacts:o}=n,{configPath:s,...c}=o,l=t=>Lq(e,t),u=i.tmux??null,d=l(`tmux.session`),f=l(`host.name`),p=l(`host.user`),m=l(`git`),h=l(`session`),g=l(`burn`),_=l(`speed`),v=l(`cache`),y=l(`context`),b=l(`metrics`),x=l(`activity`),S=l(`autocompact`),C=r.rate_limits?.five_hour,w=r.rate_limits?.seven_day,T=eJ(t.home),E=r.workspace?{...r.workspace,current_dir:eJ(r.workspace.current_dir)??``,project_dir:eJ(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>eJ(e)??e)}:r.workspace,ee=r.session_id;return{...r,...E!==void 0&&{workspace:E},...T!==void 0&&{home:T},...m!==void 0&&{git:m},...r.location!==void 0&&{location:{...r.location,main:eJ(r.location.main)??``}},...u!==null&&{tmux:{pane:u.pane,...d!==void 0&&{session:d}}},host:{...f!==void 0&&{name:f},...p!==void 0&&{user:p},...i.ssh!==void 0&&{ssh:i.ssh}},...$K(a),history:n.history,navigation:{back:n.back},term:{cols:sq(i)},...c,...s!==null&&{configPath:s},resumeCommand:JK(E,ee,i.claudeConfigDir),...h!==void 0&&{session:h},...g!==void 0&&{burn:g},..._!==void 0&&{speed:_},...C!==void 0&&{block:{nativeUtilization:C.used_percentage,resetsAt:C.resets_at}},...w!==void 0&&{weekly:{percentage:w.used_percentage,resetsAt:w.resets_at}},...v!==void 0&&{cache:v},...y!==void 0&&{context:y},...b!==void 0&&{metrics:b},...x!==void 0&&{activity:x},...S!==void 0&&{autocompact:S},...Gq(Object.keys(e.sources),t=>{let n=Dq(e.sources[t]);return n.kind===`pending`?So(n.why):n})}}function Hq(e){return[...e].join(`,`)||`-`}function Uq(e){let t=Object.entries(e);return{sources:String(t.length),sourcesPending:t.flatMap(([e,t])=>t.kind===`pending`?[`${e}:${t.why}`]:[]).join(`,`)||`-`}}function Wq(e){let t=Object.entries(e);return{runs:String(t.length),runsPending:t.flatMap(([e,{reading:t}])=>t.kind===`pending`?[`${Ln(e)}:${t.why}`]:[]).join(`,`)||`-`}}function Gq(e,t){let n=Object.fromEntries(SC.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 Kq(e,t){let n=e!=null&&t!=null?rq(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function qq(e){let t=aq(e),n=oq(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function Jq(e,t){if(e.kind===`pending`)return So(e.why);if(e.kind!==`ok`)return;let n=qK(e.value,t);return n.kind===`ok`?{cost:n.value.cost,tokens:n.value.tokens}:void 0}async function Yq(e,t,n){await yq(e,t,n),await Mj(()=>{let t=Eq(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function Xq(e,t){switch(e.kind){case`pending`:return So(e.why);case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return xI(e.value,t)}}function Zq(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=Qq(e.running),i=Qq(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 Qq(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function $q(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 eJ(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function tJ(e,t){let n=e=>e?.kind===`ok`?e.value:void 0,r=n(e.aheadBehind),i=n(e.sha),a=n(e.operation),o=n(e.committedAt),s=n(e.stashCount),c=n(e.upstream),l=e.upstream===void 0?void 0:n(BU(e.upstream,e.aheadBehind)),u=n(e.repoName),d=n(e.repoUrl),f=To(t)?t:VU(t,e.head),p={};switch(f.kind){case`pending`:case`undeclared`:{let e=f.kind===`pending`?So(f.why):f;p={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:p={prNumber:f.value.number,prState:f.value.state,prUrl:f.value.url};break;case`failed`:p={prError:f.reason};break;case`earlier`:p={prEarlier:f.value.state};break;case`absent`:break}return{branch:e.branch,status:e.status,...r!==void 0&&{ahead:r.ahead,behind:r.behind},...e.workingTree!==void 0&&{staged:e.workingTree.staged,unstaged:e.workingTree.unstaged,untracked:e.workingTree.untracked,conflicts:e.workingTree.conflicts},...i!==void 0&&{sha:i},...a!==void 0&&{operation:a},...o!==void 0&&{committedAt:o},...s!==void 0&&{stash:s},...c!==void 0&&{upstream:c},...l!==void 0&&{tracking:l},...u!==void 0&&{repoName:u},...d!==void 0&&{repoUrl:d},...p}}const nJ=Object.freeze({});function rJ(e,t){return e.kind===`decided`?t[e.name]??nJ:nJ}function iJ(e,t){return{...e,...Object.fromEntries(mx.map(n=>[n,e[n]??t[n]]))}}const aJ=(e,t)=>il(n=>{let{setting:r,on:i,inTmux:a}=Zc[n].switch;return e[r]===i&&(t||!a)});function oJ(e,t,n,r){let i=gx(e);return hy(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function sJ(e,t){return iS(t(`preset`),e.globals.preset,e.presets)}function cJ(e,t,n){let r=sJ(e,t),i=lS(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Rx(a.palette,t(`theme`),i.palette),s=iJ(i,rJ(o,e.themeDefaults));return{...Object.fromEntries(px.map(e=>[e,oJ(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:Dy(a.style,t(`style`),s.style,e.styles),effect:Ly(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function lJ(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const uJ={kind:`hidden`},dJ={kind:`shown`};function fJ(e,t){try{return lJ(e,t)?dJ:uJ}catch(e){let t=yw(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function pJ(e,t){let n=q.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function mJ(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function hJ({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function gJ({text:e,placement:t,lead:n,trail:r}){return{text:_J(e),placement:t,...n!==void 0&&{lead:_J(n)},...r!==void 0&&{trail:_J(r)}}}function _J(e){let t=e.blankCopy(e.plain);t.style=WP(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(WP(i).clearMetaAndLinks(),n,r);return t}function vJ(e){let t=hJ(e);if(t.length===1)return e.text;let n=pJ(t);return n.style=e.text.style,n}function yJ(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,placement:s,lead:c=[],trail:l=[]}=t;if(e.length===0)return[];let u=pJ(e,a).pad(o),d=new q(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:pJ([d,...c],a)},...l.length>0&&{trail:pJ([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(mJ(u,n,p),[{text:u,...f}])}function bJ(e,t,n){let r=`x`.repeat(Math.min(n,t)).replace(/x$/,` `),i=r+e,a=[],o=0;return Hne(i,t).forEach(e=>{let t=e.trimEnd(),n=i.indexOf(t,o);t!==``&&n>r.length&&a.push(n-r.length),o=n+t.length}),a}function xJ(e,t){if(e.length===0)return 0;let{lines:n}=bF(e.map(({owner:e})=>e),t),r=B(uF(n[n.length-1]));return Math.max(0,r-gF(t)+_F(t))}function SJ(e,t,n){if(e.cellLength<=t)return!0;let{lines:r}=bF([e],{...n,width:1/0});return B(uF(r.flat()))<=n.width}function CJ(e,t,n,r){if(SJ(e.owner,t,r))return[e];let i=e.owner.copy().expandTabs(),a=xJ(n,r);return i.divide(bJ(i.plain,t,a)).map((n,i)=>({...e,owner:n.truncate(t,{marker:``}).padLeft(i>0?r.padding:0)})).filter(({owner:e},t,{length:n})=>n===1||e.plain.trim()!==``)}function wJ(e,t){let n=Math.max(2,yF(t)-gF(t)-t.padding);return TJ(e,t).reduce((e,r)=>[...e,...CJ(r,n,e,t)],[])}function TJ(e,t){let n=()=>e.map(e=>({owner:vJ(e),placement:e.placement})),r=[];if(e.forEach(({fill:e},t)=>{e!==void 0&&r.push({at:t,how:e})}),r.length===0||!Number.isFinite(t.width))return n();let i=bF(e.map(vJ),t).lines;if(i.length>1)return n();let a=Math.max(0,t.width-B(uF(i.flat()))),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];mJ(c,c.cellLength+a,n)}),n()}function EJ(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=DJ(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:WP(a.style)};if(e.style.link){i();let r=DJ([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function DJ(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>OJ(e.frag,n?n.add(e.style):e.style)),i=q.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function OJ(e,t){let n=e.copy();return n.style=t,n}function kJ(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function AJ(e,t){let{look:n}=kJ(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function jJ(e,t){let{layout:n}=kJ(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function MJ(e,t){if(e.bound!==void 0)throw Error(`a render bound a compile another render holds`);return e.bound=t,{[Symbol.dispose]:()=>{e.bound=void 0}}}function NJ(e,t,n,r){let i=new Map,a=Object.entries(t);for(let[t,o]of[...a.filter(([,e])=>!(`do`in e)),...a.filter(([,e])=>`do`in e)])i.set(t,PJ(e,t,o,n,r,i));return i}function PJ(e,t,n,r,i,a){if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=mS(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,labelOf:t.labelOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=Ex.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=mS(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,labelOf:t.labelOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=mS(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,labelOf:e.labelOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:LJ(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:LJ(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`slash`in n)return{kind:`slash`,line:n.slash};if(`run`in n)return{kind:`run`,name:t,declaration:vS(n),argv:n.run.map(n=>LJ(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,LJ(e,r,t)])};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:LJ(e,n.name,t)};if(`themeDefault`in n)return{kind:`theme-default-save`};let[o,...s]=n.do.map(e=>{let n=a.get(e);if(n===void 0)throw Error(`action "${t}" fires "${e}", which is not declared in this config`);return n});return{kind:`do`,head:o,rest:s}}function FJ(e){return e.kind===`do`?FJ(e.head):e}function IJ(e){switch(FJ(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`slash`:case`run`:case`do`:return!1}}function LJ(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function RJ(e,t){return e.has(t)?hw(e.read(t)):``}function zJ(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function BJ(e,t,n,r){let i=new q(e,{style:W.combine([r,new W({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function VJ(e,t,n=!1){let r=new W({link:t,bold:n?!0:void 0}),i=new q(e.plain,{style:W.combine([WP(e.style),r])});for(let t of e.spans)i.stylize(W.combine([WP(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function HJ(e,t){return Math.max(e.members.indexOf(RJ(t,e.stateVar)),0)}function UJ(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=RJ(r,e.stateVar);return{effects:[{verb:FS,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=RJ(r,e.stateVar);return{effects:[{verb:FS,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=RJ(r,e.stateVar);return{effects:[{verb:FS,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(HJ(e,r)+1)%e.members.length];return{effects:[{verb:FS,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:IS,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:LS,args:[i,zJ(e.text,nj(r))]}],active:!1};case`open`:return{effects:[{verb:RS,args:[i,zJ(e.target,nj(r))]}],active:!1};case`persist-literal`:{let t=RJ(r,e.stateVar);return{effects:[{verb:BS,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=RJ(r,e.stateVar);return{effects:[{verb:BS,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(HJ(e,r)+1)%e.members.length];return{effects:[{verb:BS,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:VS,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:KS,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:JS,args:[i]}],active:!1};case`redo`:return{effects:[{verb:YS,args:[i]}],active:!1};case`back`:return{effects:[{verb:XS,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:ZS,args:[i]}],active:!1};case`save`:return{effects:[{verb:HS,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:US,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:WS,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:GS,args:[i,zJ(e.name,nj(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:$S,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:eC,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:tC,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:iC,args:[i,e.line]}],active:!1};case`run`:{let t=nj(r),n=JSON.stringify({run:e.argv.map(e=>zJ(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,zJ(n,t)]))}),o=a.sign({sessionId:i,action:e.name,declaration:e.declaration,evaluated:n});return{effects:[{verb:`run`,args:[i,e.name,n,o]}],active:!1}}case`layout-op`:return{effects:[{verb:qS,args:[i,e.key,UR(e.op)]}],active:!1};case`do`:{let o=UJ(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>UJ(e,t,void 0,r,i,a).effects)],active:o.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:qS,args:[i,e.key,UR(r)]}],active:!1}}}}function WJ(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:va(`action "${e}"`,n,t.members.length,HJ(t,r)),boundValue:void 0};if(n.length>2)throw Error(`action "${e}" takes a display and an optional bound value, got ${n.length} arguments (per-state displays are a cycle action's form)`);return{display:n[0],boundValue:n[1]?.plain}}function GJ(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=kJ(n,`action "${e}"`).store,{display:a,boundValue:o}=WJ(e,FJ(r),t,i),s=RJ(i,`session.id`),{effects:c,active:l}=UJ(r,a.plain,o,i,s,n.links.signer);return VJ(a,fC(n.links.to,c),l)}function KJ(e){return{action:{fn:(t,...n)=>GJ(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function qJ(e,t,n){return BJ(`✕`,fC(e,[{verb:FS,args:[RJ(t,`session.id`),n,ma]}]),!1)}function JJ(e,t,n){return new W({bgcolor:U.fromRgba(t),color:U.fromRgba(Uv(e,t,n))})}function YJ({tint:e,text:t}){return new W({bgcolor:U.fromRgba(e),color:U.fromRgba(t)})}function XJ(e,t,n){return new W({color:U.fromRgba(dd(e.get(`warning`),t,Hv,n))})}function ZJ(e,t,n){return W.combine([JJ(e,t,n),XJ(e,t,n)])}function QJ(e,t,n){return YJ(ty(e.palette,e.disclosure,t,n))}function $J(e){let t=U.fromRgba(e.get(`background`)),n=q.fromFragments(W_.map(n=>new q(`▀`,{style:new W({color:U.fromRgba(e.get(n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const eY=(e,t)=>{let n=typeof e==`string`?new q(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},tY=e=>new W({bold:e});function nY(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>eY(a,W.combine([QJ(e,{...n,distribution:t},i),tY(o)]));let o=JJ(e.palette,a,i);return(e,t,i,a)=>rY(i,W.combine([o,tY(a)]),r(t,n))}const rY=(e,t,n)=>eY(q.fromFragments([eY(e,t),eY(` `,t),$J(n)]));function iY(e,t,n,r){return t===void 0?eY(r):rY(r,void 0,t(n,e))}function aY(e,t,n,r,i){let a=JJ(e.palette,i,r);return(e,r,i,o)=>eY(q.fromFragments([eY(o?`[`:` `,a),$J(n(r,t)),eY(o?`]`:` `,a)]))}function oY(e,t,n){let r=t.map(t=>({label:t.label,indices:e.flatMap((e,n)=>e.group===t.id?[n]:[])})).filter(e=>e.indices.length>0);if(r.reduce((e,t)=>e+t.indices.length,0)!==e.length){let n=new Set(t.map(e=>e.id)),r=e.flatMap((e,t)=>n.has(e.group)?[]:[`#${t} (group "${e.group}")`]);throw Error(`library: ${r.join(`, `)} name a group the domain does not list (${[...n].join(`, `)})`)}return n?r.flatMap(e=>sY(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function sY(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function cY(e,t){return new q(e).truncate(t,{marker:`…`}).plain}function lY(e){return{current:null,drawnAt:e}}function uY(e,t,n,r,i,a,o){let s={segName:t,placementId:n,palette:r,disclosure:i,tint:a,text:o,bg:void 0,drops:[]};return e.current=s,s}function dY(e,t,n){return pY(e,()=>n(uY(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function fY(e,t){return pY(e,()=>(e.current=null,t()))}function pY(e,t){let n=e.current;try{return t()}finally{e.current=n}}function mY(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function hY(e){return new q(e).cellLength}function gY(e){let{width:t,chromeCols:n,padding:r}=kJ(e,`a row fit`);return Math.max(1,t-n-2*r)}function _Y(e){let{padding:t,seamCols:n}=kJ(e,`a row fit`);return Math.max(1,gY(e)-(hY(`✕`)+2*t+n))}function vY(e,t,n){if(!Number.isFinite(t))return e.length>0?[e.map((e,t)=>t)]:[];let r=Math.max(1,t-n),i=[],a=[],o=0;for(let t=0;t<e.length;t++){let n=e[t];a.length===0?(a=[t],o=n):o+1+n<=r?(a.push(t),o+=1+n):(i.push(a),a=[t],o=n)}return a.length>0&&i.push(a),i}function yY(e,t,n){let r=hY(`←`)+1+hY(`→`)+1,i=vY(e,t,n);return(i.length>1?vY(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function bY(e){let t=[];for(let n of e)t.length>0&&t.push(new q(` `)),t.push(n);let n=q.fromFragments(t);return n.overflow=`ignore`,n.end=``,n}function xY(e,t,n,r,i){let a=e.compiled.get(t);if(!a||a.kind!==n)throw Error(`${i} references action "${t}" which must be ${r}, got ${a?`a ${a.kind} action`:`no such action`}`);return a}function SY(e,t,n){let r=e.compiled.get(t),i=r&&FJ(r);if(!i||i.kind!==`set-option`&&i.kind!==`persist-option`&&i.kind!==`layout-op-option`)throw Error(`${n} references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${i?`a ${i.kind} action`:`no such action`}`);return i}function CY(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=kJ(a,`picker`).store,d=RJ(u,`session.id`),f=`stateVar`in t?RJ(u,t.stateVar):void 0,p=(e,n)=>{let r=t.options[e];return o({index:e,count:t.options.length},r,n,r===f)},m=i?r.kind===`led`?_Y(a):gY(a):1/0,h=(r.kind===`led`?0:hY(`✕`)+1)+c.reduce((e,t)=>e+hY(t.glyph)+1,0),g=t.library&&{groups:t.library.groups,entries:t.options.map(t.library.entry)},_=t.labelOf??(e=>e),v=g===void 0?t.options.map((e,t)=>p(t,_(e))):[],y=g===void 0?yY(v.map(e=>e.cellLength),m,h):oY(g.entries,g.groups,i),b=parseInt(RJ(u,n.stateVar),10),x=e=>Math.max(0,y.findIndex(t=>t.some(t=>t.indices.includes(e)))),S=x(f===void 0?-1:t.options.indexOf(f)),C=Number.isInteger(b)?b<0?S:Math.min(b,y.length-1):0,w=y[C]??[],T=e=>fC(a.links.to,[{verb:FS,args:[d,n.key,String(e)]}]),E=r.kind===`led`?[]:[{verb:FS,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],ee=r.kind===`own`&&r.onPick?E:[],D=e=>fC(a.links.to,[...UJ(l,e,e,u,d,a.links.signer).effects,...ee]),te=(e,n)=>VJ(e,D(t.options[n])),O=r.kind===`led`?[]:[BJ(`✕`,fC(a.links.to,E),!1,s)];O.push(...c.map(({glyph:e,option:r})=>BJ(e,fC(a.links.to,[...UJ(l,r,r,u,d,a.links.signer).effects,{verb:FS,args:[d,n.key,String(x(t.options.indexOf(r)))]}]),!1))),C>0&&O.push(BJ(`←`,T(C-1),!1));let k=C<y.length-1?[BJ(`→`,T(C+1),!1)]:[];if(g===void 0){let e=w.flatMap(e=>e.indices);return[bY([...O,...e.map(e=>te(v[e],e)),...k])]}let ne=new W({bold:!0}),A=y.length>1?` ${C+1}/${y.length}`:``,re=w.length===1?[new q(`${w[0].label}${A}`,{style:ne})]:[],ie=[bY([...O,...re,...k])];for(let e of w){w.length>1&&ie.push(bY([new q(e.label,{style:ne})]));let n=Math.max(...e.indices.map(e=>hY(_(t.options[e]))));for(let r of e.indices){let e=_(t.options[r]),i=g.entries[r].description,a=i===void 0?void 0:eF(i),o=` `.repeat(n-hY(e)+2),s=a===void 0?e:`${e}${o}${a}`;ie.push(bY([te(p(r,cY(s,m)),r)]))}}return ie}function wY(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{IA(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=xY(e,r,`set-int`,`an int action ({ set, int: true })`,`picker`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=SY(e,n,`picker`),u=mY(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let d=t.drawnAt(),f=t=>CY(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,nY(u,Dv(void 0),AJ(e,`{{ picker }}`),l.paletteOf,d,t),XJ(u.palette,t,d)),p=$v(u.palette,u.disclosure,d),[,...m]=l.library===void 0?[]:f(p.plane);return m.length===0?f(u.bg)[0]:(u.drops.push(...m),f(p.state)[0])},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function TY(e,t){let n=e.length,r=e.indexOf(t),i=r===-1?void 0:r;return{at:i,next:((i??-1)+1)%n,prev:((i??n)-1+n)%n}}function EY(e,t,n,r,i){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let a=kJ(i,`carousel`).store;if(!a.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let o=i.compiled.get(e),s=RJ(a,`session.id`),{options:c}=t;if(c.length===0)return bY([]);let l=RJ(a,t.stateVar),u=TY(c,l),d=e=>fC(i.links.to,UJ(o,c[e],c[e],a,s,i.links.signer).effects);return bY([BJ(`◀`,d(u.prev),!1),VJ(iY(AJ(i,`{{ carousel }}`),u.at===void 0?void 0:t.paletteOf,l,r),fC(i.links.to,UJ(i.compiled.get(n),l,void 0,a,s,i.links.signer).effects)),BJ(`▶`,d(u.next),!1)])}function DY(e){return{carousel:{fn:(t,n,r)=>{if(r.trim()===``)throw Error(`carousel "${t}": label is empty`);if(!e.compiled.has(n))throw Error(`carousel "${t}": open must name a declared action, got ${JSON.stringify(n)}`);if(IJ(e.compiled.get(n)))throw Error(`carousel "${t}": open "${n}" writes a value the template binds, and the label binds none — name an action that writes a fixed value, a cycle, or a do of them`);return EY(t,SY(e,t,`carousel`),n,r,e)},argTypes:[`string`,`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}function OY(e,t,n){let r=SY(e,t,n);if(!(`stateVar`in r))throw Error(`${n} references action "${t}", which inserts a segment and holds no current value — a ${n} needs a { set, from } or { persist, from } action`);if(r.paletteOf===void 0)throw Error(`${n} references action "${t}", whose options are not colour-valued — a swatch draws the palette an option puts in force, as the "themes", "placementThemes" and "styles" domains do`);return r}function kY(e,t,n){let r=Math.imul(e^e>>>16,73244475);r=Math.imul(r^r>>>16,73244475),r^=r>>>16;let i=n===void 0?t:Math.max(t-1,1);return((n??-1)+1+(r>>>0)%i)%t}function AY(e,t,n,r){let i=OY(e,t,n),a=r??RJ(kJ(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,AJ(e,`{{ ${n} }}`))}function jY(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(IA(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return $J(AY(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function MY(e,t,n){return{swatches:{fn:(r,i)=>{let a=OY(e,r,`swatches`),o=xY(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=mY(t,`{{ swatches }}`);if(s.bg===void 0)throw Error(`{{ swatches }} is not available while segments.${s.segName}'s own "bg:" is being evaluated — a swatch row is drawn on that background`);let c=t.drawnAt(),{options:l}=a,u=l.length,[d]=CY(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,aY(s,AJ(e,`{{ swatches }}`),a.paletteOf,c,s.bg),XJ(s.palette,s.bg,c),u===0?[]:(()=>{let t=TY(l,RJ(kJ(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t.prev]},{glyph:`?`,option:l[kY(n().getTime(),u,t.at)]},{glyph:`▶`,option:l[t.next]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const NY=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function PY(e,t,n,r){let i=$v(e,n,r),a=(t,n)=>({text:t,colour:n,ink:Uv(e,n,r)});return[[pv(e,t,r).map((n,i)=>{let a=Vv(e,n);return{text:NY[i%NY.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,e.get(`warning`)),a(`error`,e.get(`error`))]]]}function FY(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new q(` ${e} `,{style:YJ({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new q(e)),r.push(a)}return r}function IY(e,t,n,r,i){let a=PY(e,t,n,r).map(e=>FY(e,i)),o=q.fromFragments(a.flatMap((e,t)=>t===0?e:[new q(`
203
+ Single-row example: root: { h: ["seg1", "seg2"] }`,line:J(e.source,[`layout`])}),t.root!==void 0&&(a.root=LW(e,`root`,t.root)),t.insert!==void 0&&(a.insert=zW(e,t.insert,i)),t.actions!==void 0&&(a.actions=ZB(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=lG(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=SN(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=dG(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=EN(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=XB(e,t.helpers)),t.plugins!==void 0&&(a.plugins=OK(e,t.plugins)),qW(e,a),iG(e,a),oP(e,a),JN(e,a,TS,`the global settings menu`),YN(e,a,n),a}const DK=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function OK(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 ${Ib(t)}`,line:J(e.source,[`plugins`])})}const kK={},AK=gI(`commands.`),jK=SI(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),MK=uI(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),NK=`{{ ${CP} }}`,PK={min:0,max:100,step:5},FK={warnAt:{label:`warning at %`,domain:PK,default:50},errorAt:{label:`error at %`,domain:{...PK,atLeast:`warnAt`},default:80}};function IK(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:PK,default:80}}}const LK={globals:{palette:`tokyo-night`},variables:{...AK.variables,...TM,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:`⊫`},...MK.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:NK},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 ${MK.armed} }}{{ if ne .git.branch "" }} {{ end }}${MK.template}{{ end }}`,fg:NK,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if eq .git.prState "open" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (eq .git.prState "open") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:iI(``).template},commands:{group:`session-tools`,description:`Type /compact, /model or /clear into this session; /clear asks for a second click. Hidden when not inside tmux.`,template:AK.template,when:AK.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:IK(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:IK(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:FK,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:FK,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) ${Hv} }}`,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:jK.template,bg:jK.bg,when:jK.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...iI(``).actions,...AK.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...MK.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...jK.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:kK,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 ${Hv} }}{{ \$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 (${CP}) 2 (readableOn (color "accent") (bgOf) ${Hv})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Hv}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ $age := .git.timeSinceCommit }}{{ if and .settings.age (gt $age 0) }} ◷ {{ template "formatTimeSince" $age }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:CI(`.`),formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatToolTally:`{{ $names := splitList "," . }}{{ range $i, $pair := $names }}{{ if lt $i 2 }}{{ if $i }} {{ end }}{{ $kv := splitList ":" $pair }}{{ index $kv 0 }}{{ if ne (index $kv 1) "1" }}×{{ index $kv 1 }}{{ end }}{{ end }}{{ end }}{{ if gt (len $names) 2 }} +{{ sub (len $names) 2 }}{{ end }}`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},RK=new Set([LK.globals.palette,...Object.keys(LK.themeDefaults),...Object.values(LK.segments).map(e=>e.palette)].filter(e=>e!==void 0)),zK=Oz(SK(`<default>`,JSON.stringify(LK),RK),LK),BK=nS(zK.presets);function VK(e){return BK.includes(e)}function HK(e){return e.input+e.output+e.cacheCreation+e.cacheRead}const UK={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0};function WK(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function GK(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function KK(e,t,n){return{[GK(ot(e))]:{...UK,cost:t,input:n}}}function qK(e,t){let n=GK(ot(t)),r=e.sums[n],i=e.own[n];if(r===void 0&&i===void 0)return I;let a={...UK};return r!==void 0&&WK(a,r),i!==void 0&&WK(a,i),F({cost:a.cost,tokens:HK(a),tokenBreakdown:{input:a.input,output:a.output,cacheCreation:a.cacheCreation,cacheRead:a.cacheRead},date:n})}function JK(e,t,n){return wn({dir:e.project_dir,env:n===void 0?[]:[[Go,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}const YK=[`session`,`today`,`speed`,`context`,`metrics`,`activity`,`cache`,`autocompact`,`git`,`pr`,`tmux`,`hostName`,`hostUser`];function XK(e){let t=new Set(e);return t.has(`pr`)&&t.add(`git`),new Set(YK.filter(e=>t.has(e)))}function ZK(e,t){return e.builtins[t]??Co(t)}function QK(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function $K(e){return{...Object.fromEntries(fx.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:VK(e.preset)}}}const eq={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function tq(e){if(Eo(e))return`pending`;if(wo(e))return`undeclared`;let{prState:t,prError:n,prEarlier:r}=e??{};return Eo(t)?`pending`:wo(t)?`undeclared`:t===void 0?n===void 0?r===void 0?`-`:`earlier-${String(r)}`:`failed`:t}const nq=10*1e3;function rq(e,t){if(!(t<60))return e*3600/t}function iq(e,t,n,r){let i=r-t;if(i<50||i>nq)return;let a=n-e;if(!(a<=0))return a*1e3/i}function aq(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=iq(t.input,t.atMs,n.input,n.atMs),i=iq(t.output,t.atMs,n.output,n.atMs),a=iq(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function oq(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>nq)continue;let o=iq(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function sq(e){return OU(e.termCols??120)}function cq(e,t){return Jo(qo(e.claudeConfigDir,t))}function lq(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}function uq(e){return Object.entries(e)}function dq(e){return e.kind===`pending`&&e.why===`unread`?e.landed:null}function fq(e){return{current:()=>e.current(),refresh:null,landing:()=>dq(e.current()),fault:()=>null}}const pq=e=>fq(Fj(e));function mq(e,t){return{current:()=>{let n=e.current();return n.kind===`ok`?F(t(n.value)):n}}}function hq({owners:e,facts:t},n,r,i){let a=t.hookData.session_id,o=()=>e.faults.of(a,n);return{current:()=>{let t=o();if(t!==void 0)return t;try{return r()}catch(t){return e.log(`error`,`${n} read threw: ${O(t)}`),L(`${n}: ${String(t)}`,`read`)}},refresh:{lane:n,run:i},landing:()=>null,fault:()=>{let e=o();return e===void 0?null:{lane:n,reason:e.reason}}}}function gq(e){switch(e.kind){case`pending`:case`failed`:return e;case`absent`:return I;case`ok`:return e.value.pullRequest??So(`unread`)}}function _q({pullRequest:e,...t}){return t}const vq={session:e=>hq(e,`session`,()=>e.owners.usageStore.usageOf(e.facts.hookData.session_id,e.facts.hookData),t=>t.usage().usage(e.facts.hookData)),today:e=>{let t=e.owners.usageStore.declareToday(e.holds,e.facts.hints.claudeConfigDir);return hq(e,`today`,()=>Tq(t,e.owners.usageStore,e.facts.hookData.session_id),e=>e.usage().today())},speed:e=>hq(e,`speed`,()=>e.owners.usageStore.speedOf(e.facts.hookData.session_id),e=>e.usage().speed(ot(e.at).getTime())),context:e=>hq(e,`context`,()=>e.owners.contextProvider.contextOf(e.facts.hookData),()=>e.owners.contextProvider.getContextInfo(e.facts.hookData)),metrics:e=>hq(e,`metrics`,()=>e.owners.metricsProvider.metricsOf(e.facts.hookData.session_id,e.facts.hookData),()=>e.owners.metricsProvider.getMetricsInfo(e.facts.hookData.session_id,e.facts.hookData)),activity:e=>hq(e,`activity`,()=>e.owners.activityProvider.activityOf(e.facts.hookData.session_id),()=>e.owners.activityProvider.getActivityInfo(e.facts.hookData.session_id,e.facts.hookData)),cache:e=>hq(e,`cache`,()=>e.owners.cacheExpiry.expiryOf(e.facts.hookData.session_id),()=>e.owners.cacheExpiry.refresh(e.facts.hookData.session_id,e.facts.hookData.transcript_path)),autocompact:e=>{let t=()=>cq(e.facts.hints,e.owners.home);return hq(e,`autocompact`,()=>e.owners.autoCompact.stored(t()),async()=>e.owners.autoCompact.window(t()))},git:e=>fq(mq(e.repo(),_q)),pr:e=>{let t=e.repo();return{current:()=>gq(t.current()),refresh:null,landing:()=>null,fault:()=>null}},tmux:e=>{let t=e.facts.hints.tmux??null;return t===null?pq(I):fq(mq(e.owners.tmuxService.declare(e.holds,t),e=>({session:e})))},hostName:e=>fq(e.owners.hostService.declareName(e.holds)),hostUser:e=>fq(e.owners.hostService.declareUser(e.holds))};async function yq(e,t,n){let{hookData:r,deps:i}=e,a=r.session_id,o,s={at:t,usage:()=>o??=i.usageStore.request(a,r.transcript_path)},c=async({lane:e,run:t})=>{let r=i.clock.monotonic();n.set(e,null);let o=null;try{await t(s)}catch(t){i.log(`error`,`${e} lane threw: ${O(t)}`),o=`${e}: ${String(t)}`}n.set(e,Qe(i.clock,r)),i.faults.refreshed(a,e,o)};await Promise.all(uq(i.lanes().builtins).flatMap(([,e])=>e.refresh===null?[]:[c(e.refresh)]))}function bq(e,{builtins:t,sources:n}){return{builtins:Object.fromEntries([...t].map(t=>[t,pq(e)])),sources:new Map([...n.keys()].map(t=>[t,Fj(e)]))}}const xq={showSha:!0,showWorkingTree:!0,showStashCount:!0,showUpstream:!0,showRepoName:!0,showRepoUrl:!0,showOperation:!0,showCommittedAt:!0};function Sq({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,{...xq,showPullRequest:n.has(`pr`)},t.workspace?.project_dir]}function Cq(e,t,n,{builtins:r,sources:i}){let a=[],o=(e,t,n)=>{try{return t()}catch(t){return a.push(`${e}: ${O(t)}`),n(L(`${e}: ${String(t)}`,`read`))}},s,c={owners:e,holds:t,facts:n,repo:()=>s??=o(`git`,()=>e.gitProvider.declare(t,...Sq(n,r)),Fj)};return{lanes:{builtins:Object.fromEntries([...r].map(e=>[e,o(e,()=>vq[e](c),pq)])),sources:new Map([...i].map(([r,i])=>[r,o(r,()=>e.managedStorage.declare(t,i,n.sessionId),Fj)]))},faults:a}}function wq({deps:e}){let{builtins:t,sources:n}=e.lanes(),r=uq(t);return{builtins:Object.fromEntries(r.map(([e,t])=>[e,t.current()])),sources:new Map([...n].map(([e,t])=>[e,t.current()])),faults:r.flatMap(([,e])=>e.fault()??[])}}function Tq(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:F({sums:r.value.sums,own:i.kind===`ok`?i.value:{}})}function Eq(e){return[...uq(e.builtins).map(([,e])=>e.landing()),...[...e.sources.values()].map(e=>dq(e.current()))].flatMap(e=>e===null?[]:[e])}const Dq=e=>{switch(e.kind){case`pending`:return e;case`absent`:return I;case`ok`:return F(e.value);case`failed`:return L(e.reason,e.failedAt)}};function Oq(e,t){switch(e.kind){case`pending`:return So(e.why);case`failed`:case`absent`:return;case`ok`:return t(e.value)}}const kq=e=>e.kind===`ok`?e.value:void 0;function Aq(...e){let t=e.find(e=>e.kind===`pending`);return t?.kind===`pending`?So(t.why):void 0}const jq=(e,t,n={})=>({phase:`turn`,facts:e,parts:n,compose:t}),Mq={session:jq([`session`],({session:e})=>Oq(e,e=>$q({cost:e.session.cost,tokens:e.session.tokens}))),burn:jq([`session`,`metrics`],({session:e,metrics:t})=>Aq(e,t)??Kq(kq(e)?.session.cost,kq(t)?.sessionDuration)),speed:jq([`speed`],({speed:e})=>Oq(e,qq)),cache:jq([`cache`],({cache:e})=>Oq(e,e=>({expiresAt:e}))),context:jq([`context`],({context:e})=>Oq(e,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage}))),metrics:jq([`metrics`],({metrics:e})=>Oq(e,e=>$q({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved}))),activity:jq([`activity`],({activity:e})=>Oq(e,Zq)),autocompact:jq([`autocompact`,`context`],({autocompact:e,context:t})=>Aq(t)??Xq(e,kq(t)?.maxTokens)),git:jq([`git`],({git:e,pr:t})=>e.kind===`pending`?So(e.why):e.kind===`ok`?tJ(e.value,t):void 0,{pr:Object.keys(eq)}),"tmux.session":jq([`tmux`],({tmux:e})=>e.kind===`pending`?So(e.why):kq(e)?.session),"host.name":jq([`hostName`],({hostName:e})=>e.kind===`pending`?So(e.why):kq(e)),"host.user":jq([`hostUser`],({hostUser:e})=>e.kind===`pending`?So(e.why):kq(e)),today:((e,t)=>({phase:`draw`,facts:e,parts:{},project:t}))([`today`],({today:e},t)=>Jq(e,t))},Nq=Mq,Pq=Mq,Fq=Object.entries({...Nq,...Pq});function Iq(e,t){let n={};for(let r of t.facts){let t=ZK(e,r);if(t.kind===`undeclared`)return t;n[r]=Dq(t)}for(let r of Object.keys(t.parts)){let t=ZK(e,r);n[r]=t.kind===`undeclared`?t:Dq(t)}return n}function Lq(e,t){let n=Iq(e,Nq[t]);return wo(n)?n:Nq[t].compose(n)}function Rq(e,t,n){let r=Iq(e,Pq[t]);return wo(r)?r:Pq[t].project(r,n)}function zq(e,t){return{today:Rq(e,`today`,t)}}function Bq(e){let t=new Set;for(let n of e)for(let[e,r]of Fq)if(!(!PU(e,n)&&!PU(n,e))){for(let e of r.facts)t.add(e);for(let[i,a]of Object.entries(r.parts))(PU(n,e)||a.some(t=>PU(`${e}.${t}`,n)))&&t.add(i)}return XK(t)}function Vq(e,t,n){let{hookData:r,hints:i}=t,{effective:a,configFacts:o}=n,{configPath:s,...c}=o,l=t=>Lq(e,t),u=i.tmux??null,d=l(`tmux.session`),f=l(`host.name`),p=l(`host.user`),m=l(`git`),h=l(`session`),g=l(`burn`),_=l(`speed`),v=l(`cache`),y=l(`context`),b=l(`metrics`),x=l(`activity`),S=l(`autocompact`),C=r.rate_limits?.five_hour,w=r.rate_limits?.seven_day,T=eJ(t.home),E=r.workspace?{...r.workspace,current_dir:eJ(r.workspace.current_dir)??``,project_dir:eJ(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>eJ(e)??e)}:r.workspace,ee=r.session_id;return{...r,...E!==void 0&&{workspace:E},...T!==void 0&&{home:T},...m!==void 0&&{git:m},...r.location!==void 0&&{location:{...r.location,main:eJ(r.location.main)??``}},...u!==null&&{tmux:{pane:u.pane,...d!==void 0&&{session:d}}},host:{...f!==void 0&&{name:f},...p!==void 0&&{user:p},...i.ssh!==void 0&&{ssh:i.ssh}},...$K(a),history:n.history,navigation:{back:n.back},term:{cols:sq(i)},...c,...s!==null&&{configPath:s},resumeCommand:JK(E,ee,i.claudeConfigDir),...h!==void 0&&{session:h},...g!==void 0&&{burn:g},..._!==void 0&&{speed:_},...C!==void 0&&{block:{nativeUtilization:C.used_percentage,resetsAt:C.resets_at}},...w!==void 0&&{weekly:{percentage:w.used_percentage,resetsAt:w.resets_at}},...v!==void 0&&{cache:v},...y!==void 0&&{context:y},...b!==void 0&&{metrics:b},...x!==void 0&&{activity:x},...S!==void 0&&{autocompact:S},...Gq(Object.keys(e.sources),t=>{let n=Dq(e.sources[t]);return n.kind===`pending`?So(n.why):n})}}function Hq(e){return[...e].join(`,`)||`-`}function Uq(e){let t=Object.entries(e);return{sources:String(t.length),sourcesPending:t.flatMap(([e,t])=>t.kind===`pending`?[`${e}:${t.why}`]:[]).join(`,`)||`-`}}function Wq(e){let t=Object.entries(e);return{runs:String(t.length),runsPending:t.flatMap(([e,{reading:t}])=>t.kind===`pending`?[`${Ln(e)}:${t.why}`]:[]).join(`,`)||`-`}}function Gq(e,t){let n=Object.fromEntries(xC.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 Kq(e,t){let n=e!=null&&t!=null?rq(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function qq(e){let t=aq(e),n=oq(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function Jq(e,t){if(e.kind===`pending`)return So(e.why);if(e.kind!==`ok`)return;let n=qK(e.value,t);return n.kind===`ok`?{cost:n.value.cost,tokens:n.value.tokens}:void 0}async function Yq(e,t,n){await yq(e,t,n),await Mj(()=>{let t=Eq(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function Xq(e,t){switch(e.kind){case`pending`:return So(e.why);case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return xI(e.value,t)}}function Zq(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=Qq(e.running),i=Qq(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 Qq(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function $q(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 eJ(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function tJ(e,t){let n=e=>e?.kind===`ok`?e.value:void 0,r=n(e.aheadBehind),i=n(e.sha),a=n(e.operation),o=n(e.committedAt),s=n(e.stashCount),c=n(e.upstream),l=e.upstream===void 0?void 0:n(BU(e.upstream,e.aheadBehind)),u=n(e.repoName),d=n(e.repoUrl),f=To(t)?t:VU(t,e.head),p={};switch(f.kind){case`pending`:case`undeclared`:{let e=f.kind===`pending`?So(f.why):f;p={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:p={prNumber:f.value.number,prState:f.value.state,prUrl:f.value.url};break;case`failed`:p={prError:f.reason};break;case`earlier`:p={prEarlier:f.value.state};break;case`absent`:break}return{branch:e.branch,status:e.status,...r!==void 0&&{ahead:r.ahead,behind:r.behind},...e.workingTree!==void 0&&{staged:e.workingTree.staged,unstaged:e.workingTree.unstaged,untracked:e.workingTree.untracked,conflicts:e.workingTree.conflicts},...i!==void 0&&{sha:i},...a!==void 0&&{operation:a},...o!==void 0&&{committedAt:o},...s!==void 0&&{stash:s},...c!==void 0&&{upstream:c},...l!==void 0&&{tracking:l},...u!==void 0&&{repoName:u},...d!==void 0&&{repoUrl:d},...p}}const nJ=Object.freeze({});function rJ(e,t){return e.kind===`decided`?t[e.name]??nJ:nJ}function iJ(e,t){return{...e,...Object.fromEntries(px.map(n=>[n,e[n]??t[n]]))}}const aJ=(e,t)=>il(n=>{let{setting:r,on:i,inTmux:a}=Zc[n].switch;return e[r]===i&&(t||!a)});function oJ(e,t,n,r){let i=hx(e);return hy(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function sJ(e,t){return rS(t(`preset`),e.globals.preset,e.presets)}function cJ(e,t,n){let r=sJ(e,t),i=cS(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Lx(a.palette,t(`theme`),i.palette),s=iJ(i,rJ(o,e.themeDefaults));return{...Object.fromEntries(fx.map(e=>[e,oJ(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:Dy(a.style,t(`style`),s.style,e.styles),effect:Ly(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function lJ(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const uJ={kind:`hidden`},dJ={kind:`shown`};function fJ(e,t){try{return lJ(e,t)?dJ:uJ}catch(e){let t=vw(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function pJ(e,t){let n=q.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function mJ(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function hJ({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function gJ({text:e,placement:t,lead:n,trail:r}){return{text:_J(e),placement:t,...n!==void 0&&{lead:_J(n)},...r!==void 0&&{trail:_J(r)}}}function _J(e){let t=e.blankCopy(e.plain);t.style=WP(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(WP(i).clearMetaAndLinks(),n,r);return t}function vJ(e){let t=hJ(e);if(t.length===1)return e.text;let n=pJ(t);return n.style=e.text.style,n}function yJ(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,placement:s,lead:c=[],trail:l=[]}=t;if(e.length===0)return[];let u=pJ(e,a).pad(o),d=new q(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:pJ([d,...c],a)},...l.length>0&&{trail:pJ([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(mJ(u,n,p),[{text:u,...f}])}function bJ(e,t,n){let r=`x`.repeat(Math.min(n,t)).replace(/x$/,` `),i=r+e,a=[],o=0;return Hne(i,t).forEach(e=>{let t=e.trimEnd(),n=i.indexOf(t,o);t!==``&&n>r.length&&a.push(n-r.length),o=n+t.length}),a}function xJ(e,t){if(e.length===0)return 0;let{lines:n}=bF(e.map(({owner:e})=>e),t),r=B(uF(n[n.length-1]));return Math.max(0,r-gF(t)+_F(t))}function SJ(e,t,n){if(e.cellLength<=t)return!0;let{lines:r}=bF([e],{...n,width:1/0});return B(uF(r.flat()))<=n.width}function CJ(e,t,n,r){if(SJ(e.owner,t,r))return[e];let i=e.owner.copy().expandTabs(),a=xJ(n,r);return i.divide(bJ(i.plain,t,a)).map((n,i)=>({...e,owner:n.truncate(t,{marker:``}).padLeft(i>0?r.padding:0)})).filter(({owner:e},t,{length:n})=>n===1||e.plain.trim()!==``)}function wJ(e,t){let n=Math.max(2,yF(t)-gF(t)-t.padding);return TJ(e,t).reduce((e,r)=>[...e,...CJ(r,n,e,t)],[])}function TJ(e,t){let n=()=>e.map(e=>({owner:vJ(e),placement:e.placement})),r=[];if(e.forEach(({fill:e},t)=>{e!==void 0&&r.push({at:t,how:e})}),r.length===0||!Number.isFinite(t.width))return n();let i=bF(e.map(vJ),t).lines;if(i.length>1)return n();let a=Math.max(0,t.width-B(uF(i.flat()))),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];mJ(c,c.cellLength+a,n)}),n()}function EJ(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=DJ(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:WP(a.style)};if(e.style.link){i();let r=DJ([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function DJ(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>OJ(e.frag,n?n.add(e.style):e.style)),i=q.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function OJ(e,t){let n=e.copy();return n.style=t,n}function kJ(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function AJ(e,t){let{look:n}=kJ(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function jJ(e,t){let{layout:n}=kJ(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function MJ(e,t){if(e.bound!==void 0)throw Error(`a render bound a compile another render holds`);return e.bound=t,{[Symbol.dispose]:()=>{e.bound=void 0}}}function NJ(e,t,n,r){let i=new Map,a=Object.entries(t);for(let[t,o]of[...a.filter(([,e])=>!(`do`in e)),...a.filter(([,e])=>`do`in e)])i.set(t,PJ(e,t,o,n,r,i));return i}function PJ(e,t,n,r,i,a){if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=pS(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,labelOf:t.labelOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=Tx.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=pS(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,labelOf:t.labelOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=pS(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,labelOf:e.labelOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:LJ(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:LJ(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`slash`in n)return{kind:`slash`,line:n.slash};if(`run`in n)return{kind:`run`,name:t,declaration:_S(n),argv:n.run.map(n=>LJ(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,LJ(e,r,t)])};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:LJ(e,n.name,t)};if(`themeDefault`in n)return{kind:`theme-default-save`};let[o,...s]=n.do.map(e=>{let n=a.get(e);if(n===void 0)throw Error(`action "${t}" fires "${e}", which is not declared in this config`);return n});return{kind:`do`,head:o,rest:s}}function FJ(e){return e.kind===`do`?FJ(e.head):e}function IJ(e){switch(FJ(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`slash`:case`run`:case`do`:return!1}}function LJ(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function RJ(e,t){return e.has(t)?mw(e.read(t)):``}function zJ(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function BJ(e,t,n,r){let i=new q(e,{style:W.combine([r,new W({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function VJ(e,t,n=!1){let r=new W({link:t,bold:n?!0:void 0}),i=new q(e.plain,{style:W.combine([WP(e.style),r])});for(let t of e.spans)i.stylize(W.combine([WP(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function HJ(e,t){return Math.max(e.members.indexOf(RJ(t,e.stateVar)),0)}function UJ(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=RJ(r,e.stateVar);return{effects:[{verb:PS,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=RJ(r,e.stateVar);return{effects:[{verb:PS,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=RJ(r,e.stateVar);return{effects:[{verb:PS,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(HJ(e,r)+1)%e.members.length];return{effects:[{verb:PS,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:FS,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:IS,args:[i,zJ(e.text,nj(r))]}],active:!1};case`open`:return{effects:[{verb:LS,args:[i,zJ(e.target,nj(r))]}],active:!1};case`persist-literal`:{let t=RJ(r,e.stateVar);return{effects:[{verb:zS,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=RJ(r,e.stateVar);return{effects:[{verb:zS,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(HJ(e,r)+1)%e.members.length];return{effects:[{verb:zS,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:BS,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:GS,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:qS,args:[i]}],active:!1};case`redo`:return{effects:[{verb:JS,args:[i]}],active:!1};case`back`:return{effects:[{verb:YS,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:XS,args:[i]}],active:!1};case`save`:return{effects:[{verb:VS,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:HS,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:US,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:WS,args:[i,zJ(e.name,nj(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:QS,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:$S,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:eC,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:rC,args:[i,e.line]}],active:!1};case`run`:{let t=nj(r),n=JSON.stringify({run:e.argv.map(e=>zJ(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,zJ(n,t)]))}),o=a.sign({sessionId:i,action:e.name,declaration:e.declaration,evaluated:n});return{effects:[{verb:`run`,args:[i,e.name,n,o]}],active:!1}}case`layout-op`:return{effects:[{verb:KS,args:[i,e.key,UR(e.op)]}],active:!1};case`do`:{let o=UJ(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>UJ(e,t,void 0,r,i,a).effects)],active:o.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:KS,args:[i,e.key,UR(r)]}],active:!1}}}}function WJ(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:va(`action "${e}"`,n,t.members.length,HJ(t,r)),boundValue:void 0};if(n.length>2)throw Error(`action "${e}" takes a display and an optional bound value, got ${n.length} arguments (per-state displays are a cycle action's form)`);return{display:n[0],boundValue:n[1]?.plain}}function GJ(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=kJ(n,`action "${e}"`).store,{display:a,boundValue:o}=WJ(e,FJ(r),t,i),s=RJ(i,`session.id`),{effects:c,active:l}=UJ(r,a.plain,o,i,s,n.links.signer);return VJ(a,dC(n.links.to,c),l)}function KJ(e){return{action:{fn:(t,...n)=>GJ(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function qJ(e,t,n){return BJ(`✕`,dC(e,[{verb:PS,args:[RJ(t,`session.id`),n,ma]}]),!1)}function JJ(e,t,n){return new W({bgcolor:U.fromRgba(t),color:U.fromRgba(Uv(e,t,n))})}function YJ({tint:e,text:t}){return new W({bgcolor:U.fromRgba(e),color:U.fromRgba(t)})}function XJ(e,t,n){return new W({color:U.fromRgba(dd(e.get(`warning`),t,Hv,n))})}function ZJ(e,t,n){return W.combine([JJ(e,t,n),XJ(e,t,n)])}function QJ(e,t,n){return YJ(ty(e.palette,e.disclosure,t,n))}function $J(e){let t=U.fromRgba(e.get(`background`)),n=q.fromFragments(W_.map(n=>new q(`▀`,{style:new W({color:U.fromRgba(e.get(n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const eY=(e,t)=>{let n=typeof e==`string`?new q(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},tY=e=>new W({bold:e});function nY(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>eY(a,W.combine([QJ(e,{...n,distribution:t},i),tY(o)]));let o=JJ(e.palette,a,i);return(e,t,i,a)=>rY(i,W.combine([o,tY(a)]),r(t,n))}const rY=(e,t,n)=>eY(q.fromFragments([eY(e,t),eY(` `,t),$J(n)]));function iY(e,t,n,r){return t===void 0?eY(r):rY(r,void 0,t(n,e))}function aY(e,t,n,r,i){let a=JJ(e.palette,i,r);return(e,r,i,o)=>eY(q.fromFragments([eY(o?`[`:` `,a),$J(n(r,t)),eY(o?`]`:` `,a)]))}function oY(e,t,n){let r=t.map(t=>({label:t.label,indices:e.flatMap((e,n)=>e.group===t.id?[n]:[])})).filter(e=>e.indices.length>0);if(r.reduce((e,t)=>e+t.indices.length,0)!==e.length){let n=new Set(t.map(e=>e.id)),r=e.flatMap((e,t)=>n.has(e.group)?[]:[`#${t} (group "${e.group}")`]);throw Error(`library: ${r.join(`, `)} name a group the domain does not list (${[...n].join(`, `)})`)}return n?r.flatMap(e=>sY(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function sY(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function cY(e,t){return new q(e).truncate(t,{marker:`…`}).plain}function lY(e){return{current:null,drawnAt:e}}function uY(e,t,n,r,i,a,o){let s={segName:t,placementId:n,palette:r,disclosure:i,tint:a,text:o,bg:void 0,drops:[]};return e.current=s,s}function dY(e,t,n){return pY(e,()=>n(uY(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function fY(e,t){return pY(e,()=>(e.current=null,t()))}function pY(e,t){let n=e.current;try{return t()}finally{e.current=n}}function mY(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function hY(e){return new q(e).cellLength}function gY(e){let{width:t,chromeCols:n,padding:r}=kJ(e,`a row fit`);return Math.max(1,t-n-2*r)}function _Y(e){let{padding:t,seamCols:n}=kJ(e,`a row fit`);return Math.max(1,gY(e)-(hY(`✕`)+2*t+n))}function vY(e,t,n){if(!Number.isFinite(t))return e.length>0?[e.map((e,t)=>t)]:[];let r=Math.max(1,t-n),i=[],a=[],o=0;for(let t=0;t<e.length;t++){let n=e[t];a.length===0?(a=[t],o=n):o+1+n<=r?(a.push(t),o+=1+n):(i.push(a),a=[t],o=n)}return a.length>0&&i.push(a),i}function yY(e,t,n){let r=hY(`←`)+1+hY(`→`)+1,i=vY(e,t,n);return(i.length>1?vY(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function bY(e){let t=[];for(let n of e)t.length>0&&t.push(new q(` `)),t.push(n);let n=q.fromFragments(t);return n.overflow=`ignore`,n.end=``,n}function xY(e,t,n,r,i){let a=e.compiled.get(t);if(!a||a.kind!==n)throw Error(`${i} references action "${t}" which must be ${r}, got ${a?`a ${a.kind} action`:`no such action`}`);return a}function SY(e,t,n){let r=e.compiled.get(t),i=r&&FJ(r);if(!i||i.kind!==`set-option`&&i.kind!==`persist-option`&&i.kind!==`layout-op-option`)throw Error(`${n} references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${i?`a ${i.kind} action`:`no such action`}`);return i}function CY(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=kJ(a,`picker`).store,d=RJ(u,`session.id`),f=`stateVar`in t?RJ(u,t.stateVar):void 0,p=(e,n)=>{let r=t.options[e];return o({index:e,count:t.options.length},r,n,r===f)},m=i?r.kind===`led`?_Y(a):gY(a):1/0,h=(r.kind===`led`?0:hY(`✕`)+1)+c.reduce((e,t)=>e+hY(t.glyph)+1,0),g=t.library&&{groups:t.library.groups,entries:t.options.map(t.library.entry)},_=t.labelOf??(e=>e),v=g===void 0?t.options.map((e,t)=>p(t,_(e))):[],y=g===void 0?yY(v.map(e=>e.cellLength),m,h):oY(g.entries,g.groups,i),b=parseInt(RJ(u,n.stateVar),10),x=e=>Math.max(0,y.findIndex(t=>t.some(t=>t.indices.includes(e)))),S=x(f===void 0?-1:t.options.indexOf(f)),C=Number.isInteger(b)?b<0?S:Math.min(b,y.length-1):0,w=y[C]??[],T=e=>dC(a.links.to,[{verb:PS,args:[d,n.key,String(e)]}]),E=r.kind===`led`?[]:[{verb:PS,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],ee=r.kind===`own`&&r.onPick?E:[],D=e=>dC(a.links.to,[...UJ(l,e,e,u,d,a.links.signer).effects,...ee]),te=(e,n)=>VJ(e,D(t.options[n])),O=r.kind===`led`?[]:[BJ(`✕`,dC(a.links.to,E),!1,s)];O.push(...c.map(({glyph:e,option:r})=>BJ(e,dC(a.links.to,[...UJ(l,r,r,u,d,a.links.signer).effects,{verb:PS,args:[d,n.key,String(x(t.options.indexOf(r)))]}]),!1))),C>0&&O.push(BJ(`←`,T(C-1),!1));let k=C<y.length-1?[BJ(`→`,T(C+1),!1)]:[];if(g===void 0){let e=w.flatMap(e=>e.indices);return[bY([...O,...e.map(e=>te(v[e],e)),...k])]}let ne=new W({bold:!0}),A=y.length>1?` ${C+1}/${y.length}`:``,re=w.length===1?[new q(`${w[0].label}${A}`,{style:ne})]:[],ie=[bY([...O,...re,...k])];for(let e of w){w.length>1&&ie.push(bY([new q(e.label,{style:ne})]));let n=Math.max(...e.indices.map(e=>hY(_(t.options[e]))));for(let r of e.indices){let e=_(t.options[r]),i=g.entries[r].description,a=i===void 0?void 0:eF(i),o=` `.repeat(n-hY(e)+2),s=a===void 0?e:`${e}${o}${a}`;ie.push(bY([te(p(r,cY(s,m)),r)]))}}return ie}function wY(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{IA(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=xY(e,r,`set-int`,`an int action ({ set, int: true })`,`picker`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=SY(e,n,`picker`),u=mY(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let d=t.drawnAt(),f=t=>CY(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,nY(u,Dv(void 0),AJ(e,`{{ picker }}`),l.paletteOf,d,t),XJ(u.palette,t,d)),p=$v(u.palette,u.disclosure,d),[,...m]=l.library===void 0?[]:f(p.plane);return m.length===0?f(u.bg)[0]:(u.drops.push(...m),f(p.state)[0])},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function TY(e,t){let n=e.length,r=e.indexOf(t),i=r===-1?void 0:r;return{at:i,next:((i??-1)+1)%n,prev:((i??n)-1+n)%n}}function EY(e,t,n,r,i){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let a=kJ(i,`carousel`).store;if(!a.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let o=i.compiled.get(e),s=RJ(a,`session.id`),{options:c}=t;if(c.length===0)return bY([]);let l=RJ(a,t.stateVar),u=TY(c,l),d=e=>dC(i.links.to,UJ(o,c[e],c[e],a,s,i.links.signer).effects);return bY([BJ(`◀`,d(u.prev),!1),VJ(iY(AJ(i,`{{ carousel }}`),u.at===void 0?void 0:t.paletteOf,l,r),dC(i.links.to,UJ(i.compiled.get(n),l,void 0,a,s,i.links.signer).effects)),BJ(`▶`,d(u.next),!1)])}function DY(e){return{carousel:{fn:(t,n,r)=>{if(r.trim()===``)throw Error(`carousel "${t}": label is empty`);if(!e.compiled.has(n))throw Error(`carousel "${t}": open must name a declared action, got ${JSON.stringify(n)}`);if(IJ(e.compiled.get(n)))throw Error(`carousel "${t}": open "${n}" writes a value the template binds, and the label binds none — name an action that writes a fixed value, a cycle, or a do of them`);return EY(t,SY(e,t,`carousel`),n,r,e)},argTypes:[`string`,`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}function OY(e,t,n){let r=SY(e,t,n);if(!(`stateVar`in r))throw Error(`${n} references action "${t}", which inserts a segment and holds no current value — a ${n} needs a { set, from } or { persist, from } action`);if(r.paletteOf===void 0)throw Error(`${n} references action "${t}", whose options are not colour-valued — a swatch draws the palette an option puts in force, as the "themes", "placementThemes" and "styles" domains do`);return r}function kY(e,t,n){let r=Math.imul(e^e>>>16,73244475);r=Math.imul(r^r>>>16,73244475),r^=r>>>16;let i=n===void 0?t:Math.max(t-1,1);return((n??-1)+1+(r>>>0)%i)%t}function AY(e,t,n,r){let i=OY(e,t,n),a=r??RJ(kJ(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,AJ(e,`{{ ${n} }}`))}function jY(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(IA(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return $J(AY(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function MY(e,t,n){return{swatches:{fn:(r,i)=>{let a=OY(e,r,`swatches`),o=xY(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=mY(t,`{{ swatches }}`);if(s.bg===void 0)throw Error(`{{ swatches }} is not available while segments.${s.segName}'s own "bg:" is being evaluated — a swatch row is drawn on that background`);let c=t.drawnAt(),{options:l}=a,u=l.length,[d]=CY(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,aY(s,AJ(e,`{{ swatches }}`),a.paletteOf,c,s.bg),XJ(s.palette,s.bg,c),u===0?[]:(()=>{let t=TY(l,RJ(kJ(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t.prev]},{glyph:`?`,option:l[kY(n().getTime(),u,t.at)]},{glyph:`▶`,option:l[t.next]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const NY=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function PY(e,t,n,r){let i=$v(e,n,r),a=(t,n)=>({text:t,colour:n,ink:Uv(e,n,r)});return[[pv(e,t,r).map((n,i)=>{let a=Vv(e,n);return{text:NY[i%NY.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,e.get(`warning`)),a(`error`,e.get(`error`))]]]}function FY(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new q(` ${e} `,{style:YJ({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new q(e)),r.push(a)}return r}function IY(e,t,n,r,i){let a=PY(e,t,n,r).map(e=>FY(e,i)),o=q.fromFragments(a.flatMap((e,t)=>t===0?e:[new q(`
204
204
  `),...e]));return o.overflow=`ignore`,o.end=``,o}function LY(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(IA(`themePreview`,[`applyAction`],i),r!==void 0&&typeof r!=`string`)throw Error(`themePreview: applyAction must name a declared action, got ${JSON.stringify(r)}`);let{palette:a,decor:o}=AJ(e,`{{ themePreview }}`);return IY(r===void 0?a:AY(e,r,`themePreview`),o,{...mY(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),_Y(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const RY=e=>e.slice(e.lastIndexOf(`.`)+1),zY=(e,t)=>{let n=new q(RY(e));return n.truncate(t,{marker:`…`}),n.plain};function BY(e,t){let n=e.map(e=>e.map(({name:e})=>hY(RY(e)))),r=e=>n.every(n=>n.reduce((t,n)=>t+Math.min(n,e)+2,0)<=t),i=Math.max(1,...n.flat());for(;i>1&&!r(i);)--i;return i}function VY(e,t,n,r){let i=BY(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new q(` ${zY(s,i)} `,{style:YJ(dy(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=q.fromFragments(a.flatMap((e,t)=>t===0?e:[new q(`
205
- `),...e]));return o.overflow=`ignore`,o.end=``,o}const HY=`layoutPreview`;function UY(e,t){return{[HY]:{fn:()=>VY(jJ(e,`{{ layoutPreview }}`),AJ(e,`{{ layoutPreview }}`).decor,t.drawnAt(),_Y(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function WY(e,t,n,r){let i=mY(r.activeSegment,`{{ menu }}`),a=r.action,o=PM(i.placementId,e,n.key),s=LM(o),c=NM(e),l=kJ(a,`menu`).store,u=RJ(l,o)===c,d=RJ(l,`session.id`),f=u?ma:c,p=BJ(va(`{{ menu "${e}" }}`,t,2,+!!u),fC(a.links.to,[{verb:FS,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=$v(i.palette,i.disclosure,t).plane,l=SY(a,e,`menu`);return CY(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,ma],[s,`0`]],onPick:n.closeOnPick},n.paged,a,nY(i,n.distribution,AJ(a,`{{ menu }}`),l.paletteOf,t,c),XJ(i.palette,c,t))})():[]),p}const GY=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function KY(e,t){let n=t[t.length-1],r=GY(n)?n:void 0,i=r===void 0?t:t.slice(0,-1),a=i.findIndex(e=>typeof e!=`string`);if(a!==-1)throw Error(`{{ menu "${e}" }} display #${a+1} is not text (${JSON.stringify(i[a])}) — a menu binds its trigger text, then an optional trailing (dict …) of options`);return{displays:i,options:VM(r??{})}}function qY(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=KY(t,n);return WY(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function JY(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=YY(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new q(t?i:a,{style:l===void 0?void 0:new W({color:l})}))}let l=q.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function YY(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.min(n,Math.max(0,Math.round(e/t*n)))}function XY(e){let t={fn:(()=>{let t=mY(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],arity:{kind:`exact`},returnType:`string`},n={fn:(()=>mY(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=mY(e,`{{ roleTextOn }}`);return iX(r,$Y(t),ed(r,n),e.drawnAt()).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=_A(()=>mY(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...aX(s)];return JY({value:e,max:t,width:n,filled:r,empty:a,colourAt:c===void 0?void 0:e=>String(i.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...i,bgOf:t,tint:n,roleTextOn:r,gauge:a}}const ZY={"#000000":[`darken-1`,`darken-2`,`darken-3`],"#ffffff":[`lighten-1`,`lighten-2`,`lighten-3`]},QY=Object.values(ZY).flat();function $Y(e){if(!Object.hasOwn(fv,e)){let t=Object.keys(fv).map(e=>`"${e}"`).join(`, `);throw Error(`{{ roleTextOn }}: "${e}" is not a semantic role; it takes one of ${t}`)}return e}function eX(e){let t=Fu[e];if(t===void 0)throw Error(`"${e}" is not an ANSI colour name rich-js knows`);return ku.get(t)}const tX=(e,t,n)=>{let r=ZY[n];if(r===void 0)throw Error(`contrastFor named ${n}, which is neither pole`);let i=n=>[`text-${t}`,t,...n.map(e=>`${t}-${e}`)].map(t=>ed(e,t));return{preferred:i(r),all:i(QY)}},nX=(e,t)=>{let n=fv[t].map(eX);return{preferred:n,all:n}},rX={[H.DEFAULT]:tX,[H.STANDARD]:nX,[H.EIGHT_BIT]:tX,[H.TRUECOLOR]:tX,[H.WINDOWS]:nX};function iX(e,t,n,r){let i=fd(n,r),a=e=>({colour:e,ratio:Gl(fd(e,r),i)}),{preferred:o,all:s}=rX[r](e,t,ud(i).hex),c=s.map(a).reduce((e,t)=>t.ratio>e.ratio?t:e);return(o.map(a).find(({ratio:e})=>e>=4.5)??c).colour}function aX(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}const oX={input:`view`,state:`view`,template:`view`,time:`view`,shell:`view`,file:`view`,literal:`directory`,dropped:`directory`,source:`view`},sX=new WeakMap;function cX(e){let t=sX.get(e);return t===void 0&&(t=new Map([...aw(e)].map(([e,t])=>[e,oX[t.kind]])),sX.set(e,t)),t}function lX(e){let t=[],n=[];for(let r of e){if(!r.contains(`
205
+ `),...e]));return o.overflow=`ignore`,o.end=``,o}const HY=`layoutPreview`;function UY(e,t){return{[HY]:{fn:()=>VY(jJ(e,`{{ layoutPreview }}`),AJ(e,`{{ layoutPreview }}`).decor,t.drawnAt(),_Y(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function WY(e,t,n,r){let i=mY(r.activeSegment,`{{ menu }}`),a=r.action,o=PM(i.placementId,e,n.key),s=LM(o),c=NM(e),l=kJ(a,`menu`).store,u=RJ(l,o)===c,d=RJ(l,`session.id`),f=u?ma:c,p=BJ(va(`{{ menu "${e}" }}`,t,2,+!!u),dC(a.links.to,[{verb:PS,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=$v(i.palette,i.disclosure,t).plane,l=SY(a,e,`menu`);return CY(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,ma],[s,`0`]],onPick:n.closeOnPick},n.paged,a,nY(i,n.distribution,AJ(a,`{{ menu }}`),l.paletteOf,t,c),XJ(i.palette,c,t))})():[]),p}const GY=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function KY(e,t){let n=t[t.length-1],r=GY(n)?n:void 0,i=r===void 0?t:t.slice(0,-1),a=i.findIndex(e=>typeof e!=`string`);if(a!==-1)throw Error(`{{ menu "${e}" }} display #${a+1} is not text (${JSON.stringify(i[a])}) — a menu binds its trigger text, then an optional trailing (dict …) of options`);return{displays:i,options:VM(r??{})}}function qY(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=KY(t,n);return WY(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function JY(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=YY(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new q(t?i:a,{style:l===void 0?void 0:new W({color:l})}))}let l=q.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function YY(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.min(n,Math.max(0,Math.round(e/t*n)))}function XY(e){let t={fn:(()=>{let t=mY(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],arity:{kind:`exact`},returnType:`string`},n={fn:(()=>mY(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=mY(e,`{{ roleTextOn }}`);return iX(r,$Y(t),ed(r,n),e.drawnAt()).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=_A(()=>mY(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...aX(s)];return JY({value:e,max:t,width:n,filled:r,empty:a,colourAt:c===void 0?void 0:e=>String(i.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...i,bgOf:t,tint:n,roleTextOn:r,gauge:a}}const ZY={"#000000":[`darken-1`,`darken-2`,`darken-3`],"#ffffff":[`lighten-1`,`lighten-2`,`lighten-3`]},QY=Object.values(ZY).flat();function $Y(e){if(!Object.hasOwn(fv,e)){let t=Object.keys(fv).map(e=>`"${e}"`).join(`, `);throw Error(`{{ roleTextOn }}: "${e}" is not a semantic role; it takes one of ${t}`)}return e}function eX(e){let t=Fu[e];if(t===void 0)throw Error(`"${e}" is not an ANSI colour name rich-js knows`);return ku.get(t)}const tX=(e,t,n)=>{let r=ZY[n];if(r===void 0)throw Error(`contrastFor named ${n}, which is neither pole`);let i=n=>[`text-${t}`,t,...n.map(e=>`${t}-${e}`)].map(t=>ed(e,t));return{preferred:i(r),all:i(QY)}},nX=(e,t)=>{let n=fv[t].map(eX);return{preferred:n,all:n}},rX={[H.DEFAULT]:tX,[H.STANDARD]:nX,[H.EIGHT_BIT]:tX,[H.TRUECOLOR]:tX,[H.WINDOWS]:nX};function iX(e,t,n,r){let i=fd(n,r),a=e=>({colour:e,ratio:Gl(fd(e,r),i)}),{preferred:o,all:s}=rX[r](e,t,ud(i).hex),c=s.map(a).reduce((e,t)=>t.ratio>e.ratio?t:e);return(o.map(a).find(({ratio:e})=>e>=4.5)??c).colour}function aX(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}const oX={input:`view`,state:`view`,template:`view`,time:`view`,shell:`view`,file:`view`,literal:`directory`,dropped:`directory`,source:`view`},sX=new WeakMap;function cX(e){let t=sX.get(e);return t===void 0&&(t=new Map([...iw(e)].map(([e,t])=>[e,oX[t.kind]])),sX.set(e,t)),t}function lX(e){let t=[],n=[];for(let r of e){if(!r.contains(`
206
206
  `)){n.push(r);continue}let e=r.split(`
207
- `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function uX(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}const dX=e=>e.kind===`failed`?uJ:e;function fX(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function pX(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:n,opened:r.length>0,ground:i},deeper:r}}function mX(e){return{...e,cells:e.cells.map(gJ)}}function hX(e,t){let n=t.flatMap(e=>e.filter(e=>e.place===`above`)),r=t.map(e=>e.filter(e=>e.place===`flow`));return[...n,...gX(e,r)]}function gX(e,t){switch(e){case`vertical`:return t.flatMap(e=>e);case`horizontal`:return t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`,place:`flow`},...t.flatMap(e=>e.slice(1))]}}function _X(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:hX(e.direction,e.children.map((t,i)=>n(t,[...r,vX(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function vX(e,t){return e.steps[t]}function yX(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=bX(e);return{width:xX(t),reach:SX(t)}}function bX(e){let t=e.children.map(yX),n=n=>e.direction===`vertical`&&t.slice(0,n).some(({width:e})=>e>0);if(e.direction===`vertical`||e.unit===!0)return t.map((e,t)=>({start:0,span:e,ownLine:n(t)}));let r=0;return t.map((e,t)=>{let i=r;return r+=e.width,{start:i,span:e,ownLine:n(t)}})}const xX=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),SX=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function CX(e,t){let n=bX(e);if(t?.axis===`cell`)return n.map(({start:e,span:n,ownLine:r})=>{let i=t.index+e;return r?{...t,index:i,lineStart:i,lineEnd:i+n.width-1}:{...t,index:i}});let r=nb[e.direction],i=Dv(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),SX(n),xX(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const wX={compile(e,t){let n=CX(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,cb(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),hX(e.direction,e.children.map((n,r)=>t.renderChild(n,dX(t.gate),vX(e,r))))}},TX={drop:e=>e.place,above:()=>`above`},EX={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},DX={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:rb(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(xa(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,lb(t.path),void 0),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render:(e,t)=>t.placed(e.id,OX(e,t))};function OX(e,t){let n=t.lookupSegment(e.name);if(n===void 0)throw Error(`Layout segment "${e.name}" has no matching segment`);if(t.gate.kind===`hidden`)return[];let r=ij(t.scope,e.settings);if(t.gate.kind===`failed`)return PX(e,r,t,t.gate.message);try{let i=t.placement(e),a=fX(t.gate,i.gate());if(a.kind===`failed`)return PX(e,r,t,a.message);if(a.kind===`hidden`)return[];let o=i.bodyGate(),s=o.kind===`failed`&&a.kind===`pending`?a:o;if(s.kind===`failed`)return PX(e,r,t,s.message);let c=Mx(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:dP(c)},u=e=>({width:n.width??`auto`,justify:n.justify??`left`,truncate:n.truncate??`right`,baseStyle:e,padding:t.padding,placement:l}),d=s.kind===`shown`,f=a.kind===`pending`?a:s,p=f.kind===`pending`?kX(f.variable):AX(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?jX(p.segment,u):MX(e,r,t,p.variable,c,d,u);if(m===null)return[];let{styles:h,inline:g,drops:_}=m,v=e.opens,y=v===void 0?[]:t.renderBody(v.body,d?a:uJ,h.disclosure).map(e=>({...e,place:TX[v.placement](e)})),b=(e,t,n)=>yJ(EJ([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?EX[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},w=S.flatMap(e=>b(new q(` `.repeat(NX(hJ(e)))),h.trigger,0)),T=(e,t)=>e.band===`own`?t===x?S:w:[],E=y.map((e,t)=>({cells:[...T(e,t),...e.cells],band:`deeper`,place:e.place})),ee=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ee.flatMap(e=>e.cells),...y.flatMap(T)].flatMap(hJ)),[...ee,...E]}catch(n){return PX(e,r,t,n.message??String(n))}}const kX=e=>({kind:`waiting`,variable:e});function AX(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=yw(e);if(t===void 0)throw e;return kX(t.variable)}}function jX(e,t){let{styles:n,fragments:r,lead:i,trail:a,drops:o,open:s}=e,c=s?n.trigger:n.closed,l=t(c);return{styles:n,inline:lX(EJ(r,c)).map((e,t)=>({cells:yJ(e,{...l,lead:t===0?EJ(i,c):[],trail:t===0?EJ(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:yJ(EJ([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function MX(e,t,n,r,i,a,o){n.waited(r);let s=n.lastDrawn(e.id);if(s?.kind===`hidden`)return null;let c=n.decorations(e,i),l=a?c.trigger:c.closed,u=EJ(FX(e.lead,e,t,n),l),d=EJ(FX(e.trail,e,t,n),l);return{styles:c,inline:(s===void 0||s.drawing.own.length===0?[[`auto`]]:s.drawing.own.map(e=>e.cells.map(e=>e.text.cellLength))).map((e,t)=>({cells:e.flatMap((e,n)=>{let r=t===0&&n===0;return yJ(EJ([new q(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function NX(e){return e.reduce((e,t)=>e+t.cellLength,0)}function PX(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:yJ([new q(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:dP(n.palette)},lead:FX(e.lead,e,t,n),trail:FX(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function FX(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=yw(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const IX={container:wX,segment:DX};function LX(e){return IX[e]}var RX=class{last=null;from(e){let{last:t}=this;return t!==null&&t.source.config===e.config&&t.source.preset===e.preset&&t.source.revision===e.revision&&t.source.width===e.width?t:null}begin(e,t){let n=new Map,r=new Map;return{placed:(e,r)=>{let{drawing:i}=t(e,r);return n.set(e,i===null?zX:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const zX={kind:`hidden`},BX={palette:`theme`,style:`style`,effect:`effect`},VX=Ex.get(`colorCompatibility`),HX={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function UX(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function WX(e){if(e.ok)return e.value;throw e.error}const GX=e=>({read:()=>e}),KX=H_({basePalette:V_,palette:V_,decor:iy});var qX=class{evaluated=0;memory=new RX;scope;binding;facts;look=X.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&KX(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=X.observable.box(r,{deep:!1}),this.scope=nj(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(VX);return e.kind===`found`&&typeof e.value==`string`&&Hy(e.value)?e.value:`truecolor`});let i=(0,X.observable)(HX,void 0,{deep:!1});this.facts=i;let a=this.look,o=this.phase,s=()=>this.layout.read();this.binding={store:e,registry:t,get width(){return i.width},get chromeCols(){return i.chromeCols},get padding(){return i.padding},get seamCols(){return i.seamCols},get look(){return o.ruling?void 0:a.get()},get layout(){return o.ruling?void 0:s}},this.layout=this.derive(`layout`,n.layoutReadsInstant,()=>{let e=n.roots.get(i.preset),t=a.get().palette;return _X(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=jR(e);return i===void 0?[]:[{name:i,address:n,palette:Mx(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>Uy(this.colorCompatibility())})}bind(e){(0,X.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,X.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=kM(e);return t===void 0?DM(e)===void 0?mM(this.view.get().payload(),e):mM(this.projected,e):pM(this.slotName(t))}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[BX[e]];if(t.kind===`decided`)return XX(t.name,null,null);let r=QX(this.source,e,t.source);if(this.source.instant.has(r.template))return{kind:`per-draw`,rule:r};let i=this.rule(r.template);switch(i.kind){case`named`:{let t=null;return n=$X(this.source,e,i.name,r.where,e=>{t=e}),XX(n,t,null)}case`pending`:return XX(n??ky[e],null,i.variable);case`failed`:return n=ky[e],XX(n,Ay(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!ZX(i,e))&&(i=e),i}),this.slots.set(e,t)}return t.read()}slotName(e){let t=this.slot(e);return t.kind===`settled`?t.name:this.drawnSlots.get(e)??ky[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,X.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return fJ(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>fY(this.source.activeSegment,()=>fJ(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new eZ(this,e),this.placements.set(e,t)),t}rule(e){let t=this.rules.get(e);return t===void 0&&(t=this.derive(`rule`,this.readsInstant(e),()=>{this.phase.ruling=!0;let t=this.source.runtime.bound===this.binding?null:MJ(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=yw(e);return t===void 0?{kind:`failed`,error:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}finally{t?.[Symbol.dispose](),this.phase.ruling=!1}}),this.rules.set(e,t)),t.read()}readsInstant(...e){return e.some(e=>e!==void 0&&this.source.instant.has(e))}derive(e,t,n){let r=()=>(this.evaluated++,n());return this.store.derive(`part ${e}`,t?`projection`:`computed`,t?this.oncePerDraw(r):r)}oncePerDraw(e){let t=null;return()=>(t?.draw!==this.draws&&(t={draw:this.draws,answer:UX(e)}),WX(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:jR(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function JX(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new qX(t,n,e,r);return e.views.set(t,a),a}function YX(e,t){let n=e.views.get(t);if(n===void 0)throw Error(`a store was drawn before its view was bound (bindView): its inputs have no source`);return n}const XX=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),ZX=(e,t)=>e.kind===`settled`?t.kind===`settled`&&e.name===t.name&&e.warning===t.warning&&e.waited===t.waited:t.kind===`per-draw`&&e.rule===t.rule;function QX(e,t,n){let r=e.globalExpressions.get(t)?.get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the view but no compiled template exists — the compile and the resolution disagree about isExpression`);return r}function $X(e,t,n,r,i){switch(t){case`palette`:return Lx(n,r,i).name;case`style`:return Ey(n,e.styles).name;case`effect`:return Iy(n).name}}var eZ=class{where=tZ(H_({palette:V_,region:ny}));ground=tZ(H_({colours:rZ,bodyOpen:V_}));opened=tZ(H_({colours:rZ,open:V_}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=ij(e.scope,t.settings),{when:a,bg:o,fg:s,template:c}=n,{lead:l,trail:u}=t,d=t.opens?.open;this.ownGate=a===void 0?GX(dJ):e.derive(`${t.id} when`,e.readsInstant(a),()=>fY(r,()=>fJ(a,i))),this.open=d===void 0?GX(uJ):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>fY(r,()=>fJ(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return oZ(r,t,n,a,e.registry.drawnAt(),o,s,i)}),this.body=e.derive(`${t.id} body`,e.readsInstant(c),()=>{let{colours:e,bodyOpen:n}=this.ground.get();return sZ(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?GX(lZ):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return cZ(r,t,e,n,l,u,i)})}gate(){return this.ownGate.read()}bodyGate(){return this.open.read()}evaluate(e,t){this.where.set({palette:e,region:t});let n=this.colours.read();this.ground.set({colours:n,bodyOpen:this.open.read().kind===`shown`});let r=this.body.read();return this.opened.set({colours:n,open:r.open}),dZ(n,r,this.affixes.read())}};function tZ(e){let t=X.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,X.runInAction)(()=>t.set(e)),get:()=>t.get()}}const nZ=(e,t)=>e.hex===t.hex,rZ=H_({palette:V_,drawnAt:V_,tint:nZ,text:nZ,bg:nZ,disclosure:ay});function iZ(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const aZ=e=>$v(e.palette,e.disclosure,e.drawnAt);function oZ(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...dy(n,r,i)};return dY(e,iZ(t,c),e=>{let t=pP(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function sZ(e,t,n,r,i,a){return dY(e,iZ(t,n),e=>(e.bg=i?aZ(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function cZ(e,t,n,r,i,a,o){return dY(e,iZ(t,n),e=>(e.bg=r?aZ(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const lZ={lead:[],trail:[],drops:[]};function uZ(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return JJ(t,aZ(e).state,n)},get band(){return JJ(t,aZ(e).plane,n)},get close(){return ZJ(t,aZ(e).state,n)},disclosure:r}}function dZ(e,t,n){return{styles:uZ(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function fZ(e,t,n,r,i,a,o){let s=oZ(e,t,n,r,i,void 0,void 0,o);return dZ(s,sZ(e,t,s,a,!1,o),lZ)}function pZ(e,t,n,r,i){return uZ(oZ(e,t,n,r,i,void 0,void 0,{}))}function mZ(e,t){return{payload:()=>e,selections:()=>t}}function hZ(e){if(`ttl`in e)return{kind:`ttl`,durationMs:lM(e.ttl)};if(`watch_file`in e)return{kind:`watch_file`,path:e.watch_file};if(`depends_on`in e)return{kind:`depends_on`,varNames:e.depends_on};if(`key`in e)return{kind:`key`,template:e.key};if(`never`in e)return{kind:`never`};throw Error(`Unknown CacheDecl discriminator — loader invariant violated: ${JSON.stringify(e)}`)}function gZ(e,t){switch(fb(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,regex:new RegExp(e.regex),default:t};case`text`:return{kind:`text`,default:t}}}function _Z(e,t,n,r,i){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`source`:e.declareSourceDocument(t);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default,i);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:hZ(n.cache),parse:gZ(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:hZ(n.cache),parse:gZ(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{type:n.type??`string`,varDefault:n.default,derivation:i});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function vZ(e,t,n,r=sT.EMPTY){let i=r;for(let[r,a]of Object.entries(t))try{i=e.parse(`{{ define "${r}" }}${a}{{ end }}`,i).defines()}catch(e){throw Error(`Template parse error in ${n}.${r}: ${e.message}`,{cause:e})}return i}function yZ(e,t,n){let{compiled:r,loadWarnings:i}=xZ(e,t,n.cwd,bZ(n.links),TZ);return{...r,loadWarnings:i}}const bZ=e=>(t,n)=>EZ(n,e);function xZ(e,t,n,r,i=TZ){let a=SZ(e),o=CZ(a);return{compiled:r(o,a),compileKey:o,loadWarnings:wZ(e,t,n,i)}}function SZ(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of Dx)n in t&&r.set(e,n);for(let[t,n]of yb(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...bG(e)].sort(([e],[t])=>e<t?-1:1)}}function CZ(e){return ae(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function wZ(e,t,n,r){let i=cX(e),a=bG(e),o=[];for(let[s,c]of aw(e))if(r.has(i.get(s)))try{_Z(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const TZ=new Set([`directory`,`view`]);function EZ({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,links:r},a=()=>kJ(i,`drawnAt`).registry.drawnAt(),o=lY(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=rS(e.presets),u=bR(e),d=[e=>MY(i,o,e.now)],f=tj({extraFuncs:{...KJ(i),...jY(i),...wY(i,o),...DY(i),...LY(i,o),...UY(i,o),...qY(s),...XY(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=vZ(f,e.helpers,`helpers`),m=new Map,h=e=>{let t=f.parse(e,p);return m.set(t,e),t},g=new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n=h(e);return g.set(e,n),n},v=new Map(t);i.compiled=NJ(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=n.partials===void 0?p:vZ(f,n.partials,`segments.${t}.partials`,p),r=t=>{let n=f.parse(t,e);return m.set(n,t),n},i=(e,i,a=n.partials===void 0?_:r)=>{try{return a(e)}catch(e){throw Error(`Template parse error in segments.${t}.${i}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:i(n.when,`when`),template:i(n.template,`template`,r),bg:n.bg===void 0?void 0:i(n.bg,`bg`,r),fg:n.fg===void 0?void 0:i(n.fg,`fg`,r)}}let b=(e,t,n)=>{try{return _(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},x=t=>{let n=Cb(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Bee(t,e,a,t=>String(kJ(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},S=(e,t,n)=>{let r={path:t,at:n,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:S,placementSettings:x};return LX(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=oS(e,t);C.set(t,S(n,r,void 0))}let w=new Map(xy.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of SG(e)){let e=t.join(`.`),i=w.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:kZ(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let T=new Set(n.map(([e])=>e)),E={reads:kU({names:T,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:ej(d)},ee=TG(E),D=[...C.values()].flatMap(OZ(y)).some(e=>ee(m.get(e))),te=D?new Set([...E.clock,HY]):E.clock,O=TG({...E,clock:te}),k=new Set([...m].flatMap(([e,t])=>O(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=TG({reads:kU({names:T,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:E.projections,clock:te});for(let e of pH){let n=y[t][e];n!==void 0&&r(m.get(n))&&k.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,links:r,globalExpressions:w,instant:k,layoutReadsInstant:D,styles:e.styles,runtime:i,views:new WeakMap}}function DZ(e){return Object.entries(e.segments).flatMap(([t,n])=>[n.when,n.bg,n.fg,n.template].some(t=>t!==void 0&&e.instant.has(t))?[t]:[])}const OZ=e=>t=>{let n=[];return _X(t,e=>(n.push(e),!0)),n.flatMap(t=>[...t.when===void 0?[]:[t.when],...t.kind===`segment`&&e[t.name].when!==void 0?[e[t.name].when]:[]])};function kZ(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}const AZ=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function jZ(e,t,n,r,i){let a=MZ(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function MZ(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??ky[e];case`failed`:return r({kind:`rule`,slot:e,message:Ay(t.where,e,`the rule failed — ${n.error}`)}),ky[e]}}function NZ(e){return PZ(e).filter(e=>!e.name.startsWith(TS)).map(e=>e.id)}function PZ(e){return e.kind===`container`?e.children.flatMap(PZ):[e,...e.opens===void 0?[]:PZ(e.opens.body)]}function FZ(e,t,n,r,i,a){let o={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return JX(e,t,n,mZ(o,a)),o}function IZ(e,t,n,r,i,a,o,s,c){try{var l=Oo();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new XP(``),h=m.clockAt(a,My[c.animationSpeed]),g=l.u(WA(a,h.timeline)),_=YX(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:gF(v),padding:v.padding,seamCols:_F(v),preset:c.preset},i);let y=_.evaluated;l.u(MJ(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:uv[c.variation],shade:tv[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},w=_.memory.begin(C,pX),T=_.memory.from(C),E=new Set,ee={held:e=>T?.rules.get(e),waited:e=>E.add(e),settled:w.rule},D=new Map,te=e=>{let n=_.slot(e);if(D.set(e,n.kind===`settled`?`kept`:`per-draw`),n.kind===`settled`)return n.warning!==null&&p({kind:`rule`,slot:e,message:n.warning}),n.waited!==null&&E.add(n.waited),n.name;let r=$X(t,e,jZ(e,n.rule,_,p,ee),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:O,style:k,effect:ne}=_.selections(),A=O.kind===`decided`?O:Lx(te(`palette`),``,AZ),re=k.kind===`decided`?k:Ey(te(`style`),e.styles),ie=ne.kind===`decided`?ne:Iy(te(`effect`)),ae=A.value,oe=Px(ae,re.value);_.publishLook({basePalette:ae,palette:oe,decor:S});let se=oe.get(`warning`),ce=c.idleSince===void 0?null:{idleSince:c.idleSince,timeoutS:c.menuTimeout,fill:se,text:Uv(oe,se,r.drawnAt())},le=m.motion(ie.value,h,{transitions:x,source:C,last:T,returned:pX,hold:mX},ce);u?.clear();let ue=t=>e.segments[t],de=(e,i,a)=>{let o=i.kind===`hidden`?i:fX(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${NZ(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:o.message,message:`${t}: ${o.message} — what it gates is hidden`})}}:o,c={scope:_.scope,palette:oe,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,i,o)=>fZ(t.activeSegment,e,i,a,r.drawnAt(),o,n),lookupSegment:ue,renderChild:(e,t,n)=>de(e,t,ly(a,n)),renderBody:(e,t,n)=>de(e,t,uy(n)),closeDisclosure:e=>qJ(t.links.to,n,e),placed:(e,t)=>w.placed(e,le.placed(e,t)),lastDrawn:e=>T?.placements.get(e),waited:e=>E.add(e),decorations:(e,n)=>pZ(t.activeSegment,e,n,a,r.drawnAt())};return LX(e.kind).render(e,c)},fe=t.roots.get(b);if(fe===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${tS}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let pe=uX(de(fe,dJ,cy(S))).map(({line:e,row:t})=>{let n=wJ(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...bF(n.map(e=>e.owner),v,le.row(t,r,n))}});le.drawn(),w.commit();let me=()=>pe.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||PZ(fe).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`),he=Math.min(g.heard(),...pe.map(e=>e.nextChange)),ge=Number.isFinite(he)?`moves`:me()?`can-move`:`still`;for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{frame:{depth:v.colorCompatibility,rows:pe.flatMap(({kind:e,lines:t})=>t.map(t=>({kind:e,runs:t}))),nextChange:he,motion:ge,pending:[...E].sort()},evaluated:_.evaluated-y,cellBreaks:pe.reduce((e,t)=>e+t.cellBreaks,0),rules:D}}catch(e){l.e=e}finally{l.d()}}function LZ(e){return aJ(e.effective(),e.payload().tmux!==void 0)}function RZ(e,t,n,r,i,a,o,s){let{drawing:c,feeds:l,diagnostics:u}=t,{source:d}=e,f=d.effective(),p=d.payload().term.cols,m=IZ(e.state.config,e.state.compiled,e.store,e.registry,{diagnostics:mU(u),drawing:c,feeds:l,...zq(d.facts(),n)},n,QK(f,p),{perSegmentSink:e.lastRenderCellsBySegment,onRenderWarning:s},{...f,effects:r,idleSince:i}),h=LZ(d),g={width:p,rows:gU(d.hints().termRows,c.by===`feed`?Qc.flatMap(e=>{let t=Zc[e].rows;return h[e]&&t!==null?[t]:[]}):[]),colorCompatibility:m.frame.depth},_=hU(a,u);return{...m,body:_===null?m.frame:rF(m.frame,_U(u,_,o,e.sessionId,c.by,g)),viewing:_,geometry:g}}const zZ={moving:1e3/30,still:1e3},BZ=[`data`,`state`,`reload`,`visibility`];function VZ(e){return Qc.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 HZ(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const UZ=(e,t)=>Zc[t].handsOff?e.resp:e.statusline,WZ=e=>Math.round(1e3/e);var GZ=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)??this.open(e),i={lane:this.laneOf(r,t.lane),sent:null};return r.followers.set(t,i),this.send(t,i),this.hasten(r),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${r.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(r,t)}laneOf(e,t){let n=e.lanes.get(t);if(n!==void 0)return n;let r=this.deps.encoders[t](),i={rate:[],encode:r,out:e.last===null?null:r(e.last.bar,UZ(e.last.answers,t))};return e.lanes.set(t,i),i}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]++,n.phase.kind!==`rendering`&&(n.wokeSince??=this.deps.clock.monotonic()),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 al;let r=t-1,i=this.shown(n);return il(e=>{let a=n.lanes.get(e)?.rate;if(a===void 0)return nl;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,lanes: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},wokeSince:null,wakeToFrameLast:null,wakeToFrameMax: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.lanes.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:`rendering`};let n=e.wokeSince;e.wokeSince=null;let r=this.deps.clock.monotonic(),i=this.deps.instant(),a=Math.min(Math.max(t,i),i+.002),o=r+(a-i)*1e3;try{this.step(e,n,r,o,a)}catch(t){if(e.lastStart=o,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${O(t)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,a)}}step(e,t,n,r,i){let a=this.deps.render(e.sessionId,WZ(this.spacingOf(e)),i);if(a===null){e.noView++,e.phase={kind:`waiting`};return}e.phase={kind:`pushing`},e.lastStart=r;let o=this.deps.clock.monotonic();t!==null&&(e.wakeToFrameLast=o-t,e.wakeToFrameMax=Math.max(e.wakeToFrameMax,o-t)),this.drawn++,e.drawn++,e.drawMs+=o-n,e.evaluated+=a.evaluated,e.cellBreaks+=a.cellBreaks,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,a),this.push(e,a,i),this.feeds.get(e.sessionId)===e&&(o-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,a,i)))}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===`rendering`)return!1;let n=this.deps.clock.monotonic(),r=Math.max(n,e.lastStart+this.spacingOf(e)),i=this.deps.instant();return this.arm(e,i+(r-n)/1e3,i)}arm(e,t,n){let r=Math.max(0,(t-n)*1e3),i=this.deps.clock.monotonic()+r;return e.phase.kind===`due`&&e.phase.at<=i?!1:(this.setTimer(e,t,i,r),!0)}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)},a=[...e.lanes].map(([e,n])=>({held:n,out:n.encode(t.bar,UZ(i,e))}));if(!(e.last?.answers.resp===i.resp&&e.last.answers.statusline===i.statusline&&a.every(({held:e,out:t})=>e.out?.json===t.json))){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{held:e,out:t}of a)e.out?.json!==t.json&&HZ(e.rate,n),e.out=t;for(let[t,n]of e.followers)this.send(t,n)}}send(e,t){let{out:n}=t.lane;n===null||t.sent===n.json||(e.frame(n),t.sent=n.json)}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:oN(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=Vj.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=${WZ(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${BZ.map(t=>`${t}:${e.woke[t]}`).join(`,`)} wakeToFrame=${e.wakeToFrameLast===null?`-`:`last:${e.wakeToFrameLast.toFixed(1)}ms,max:${e.wakeToFrameMax.toFixed(1)}ms`} coalesced=${e.coalesced} daemonRefreshed=${o} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};const KZ=`click.error`;function qZ(e,t,n,r){let i=YZ(e,t).filter(e=>nt(e,5,r,`request`)!==`over`);$Z(e,t,{newest:{text:n,at:r,answered:!1},earlier:i})}function JZ(e,t,n){let r=eQ(e,t);if(r===null)return;let i=e=>n.some(t=>rt(e,t))?{...e,answered:!0}:e,a={newest:i(r.newest),earlier:r.earlier.map(i)};a.newest===r.newest&&a.earlier.every((e,t)=>e===r.earlier[t])||$Z(e,t,a)}function YZ(e,t){let n=eQ(e,t);return n===null?[]:[...n.earlier,n.newest]}function XZ(e,t,n,r){return YZ(e,t).map(e=>({error:e,hold:nt(e,5,n,r)}))}const ZZ=e=>e.flatMap(({error:e,hold:t})=>t===`over`?[]:[e]),QZ=e=>ZZ(e).filter(e=>!e.answered);function $Z(e,t,{newest:n,earlier:r}){e.set(t,KZ,JSON.stringify({...n,earlier:r}))}function eQ(e,t){let n=e.get(t,KZ);if(n===null)return null;let r;try{r=JSON.parse(n)}catch{return null}let i=tQ(r);if(i===null)return null;let{earlier:a}=r;return{newest:i,earlier:Array.isArray(a)?a.flatMap(e=>{let t=tQ(e);return t===null?[]:[t]}):[]}}function tQ(e){if(typeof e!=`object`||!e)return null;let{text:t,at:n,answered:r}=e;return typeof t==`string`&&typeof n==`number`&&(r===void 0||typeof r==`boolean`)?{text:t,at:n,answered:r===!0}:null}function nQ(e,t){return Qc.filter(n=>e[n]&&Zc[n].handsOff&&t.has(n))}function rQ(e,t,n){return{severity:nU,lines:[[rU(`[⟲ claude]`,fC(e,[{verb:KS,args:[t,...n.map(e=>Zc[e].switch.setting)]}]))]]}}function iQ(e,t){for(let n of Object.entries(t))e.push(n)}const aQ={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function oQ(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,O(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function sQ(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...oQ(n)];return{level:aQ[n.kind],line:cQ(e,i)}}const cQ=(e,t)=>`${e}${t.map(([e,t])=>` ${e}=${z(t)}`).join(``)}`;function lQ(e,t,n){if(t.kind===`pending`)return So(t.why);if(e!==void 0&&e.kind!==`pending`){let{at:n,...r}=e;if((0,X.compareStructural)(r,t))return e}return{...t,at:n}}const uQ=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`]),dQ=[[`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`]],fQ=[[`workspace.added_dirs`,`string-list`]];function pQ(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of dQ){let i=gQ(n,e);if(i==null)t.missingRequired.push(e);else{let n=mQ(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of fQ){let i=gQ(n,e),a=i===void 0?r:hQ(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))uQ.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function mQ(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function hQ(e){return Array.isArray(e)&&e.every(e=>mQ(e)===`string`)?`string-list`:mQ(e)}function gQ(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 _Q(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 vQ(e){let t=_Q(e);if(!t.ok)throw Error(`session id ${t.problem}`);return t.id}const yQ=[`session`,`today`,`context`,`metrics`,`activity`,`cache`,`speed`,`autocompact`];var bQ=class{bySession=X.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:L(n,`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,X.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};new Set(YK);function xQ(e,t){let n=Object.keys(e.history);return e.revision===t.revision&&e.back===t.back&&n.every(n=>e.history[n]===t.history[n])&&SQ(e.values,t.values)}new Set(yQ);function SQ(e,t){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>e[n]===t[n])}function CQ(e){return{hookData:e.hookData,cwd:e.cwd,hints:e.hints}}function wQ(e){let t=e.kind===`recording`?{kind:e.kind,v:7,session:e.session,home:e.home}:e.kind===`facts`?{kind:e.kind,at:e.at,facts:e.facts}:e.kind===`draw`?{kind:e.kind,at:e.at,drawing:e.drawing,feeds:e.feeds,state:{...e.state,idleSince:e.state.idleSince??null},diagnostics:e.diagnostics}:e.kind===`state`?{kind:e.kind,state:e.state}:e.kind===`turn`?{kind:e.kind,held:e.held,at:e.document.at,facts:e.document.facts,...CQ(e.request),state:e.state}:{kind:e.kind,...e.kind===`request`&&{at:e.at},...CQ(e.request)};return`${JSON.stringify(t)}\n`}function TQ(e,t){let n=new Map,r=!1,i=e=>{for(let t of e.watching)t();e.watching.clear()},a=(e,t,r)=>{let a=n.get(e);a===void 0||!a.delete(t)||(a.size===0&&n.delete(e),i(t),t.sink.end(r))},o=(e,n,r)=>{if(!(r.kind===`declared`&&r.request===n.declaration))try{n.sink.write(r),r.kind===`facts`&&(n.document=r.facts),r.kind===`turn`&&(n.document=r.document.facts),(r.kind===`state`||r.kind===`draw`||r.kind===`turn`)&&(n.state=r.state),(r.kind===`request`||r.kind===`declared`||r.kind===`turn`)&&(n.declaration=r.request)}catch(r){t(`error`,`recording sid=${JSON.stringify(e)}: ${O(r)}`),a(e,n,{kind:`failed`,error:r})}},s=(e,t,n)=>o(e,t,n),c=(e,t,r,i)=>{if(i.facts===t.document)return;let a=r.source.state();(t.state===null||!xQ(t.state,a))&&s(e,t,{kind:`state`,state:a}),n.get(e)?.has(t)&&o(e,t,{kind:`facts`,...i})},l=(e,t,n)=>{let r=n.source.held();t.turn?.view===n&&t.turn.held===r||(t.turn={view:n,held:r},s(e,t,{kind:`turn`,held:r,...n.source.turn()}))},u=(t,r,i,{view:a,state:o,drawing:u,feeds:d,diagnostics:f})=>{let p=e.sessionView(t),m={at:i,drawing:u,feeds:d,state:o,diagnostics:f},h=[()=>l(t,r,a),()=>c(t,r,a,a.followed.stamped()),()=>s(t,r,{kind:`declared`,request:a.facts()}),()=>s(t,r,{kind:`draw`,...m}),...p===null?[]:[()=>l(t,r,p)]];for(let e of h)n.get(t)?.has(r)&&e()},d=(t,r)=>{let i=e.sessionView(t);if(i===null)return;let a=(e,i)=>{if(!n.get(t)?.has(r))return;let a=(0,X.reaction)(e,i,{fireImmediately:!0});n.get(t)?.has(r)?r.watching.add(a):a()};a(()=>i.source.held(),()=>l(t,r,i)),a(()=>i.followed.stamped(),e=>c(t,r,i,e))};return{record(t,i){if(r)throw Error(`the daemon is closing: it records nothing more`);let o=e.sessionView(t);if(o===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 c={sink:i,watching:new Set,document:null,declaration:null,state:null,turn:null},l=n.get(t)??new Set;return n.set(t,l.add(c)),s(t,c,{kind:`recording`,session:t,home:o.source.home()}),l.has(c)&&d(t,c),()=>a(t,c,{kind:`stopped`})},moved(e){for(let t of n.get(e)??[])i(t),d(e,t)},arrived(e,t){let r=new Set;for(let i of n.get(e)??[])s(e,i,{kind:`request`,...t}),r.add(i);return{at:t.at,noted:r}},drew(e,{at:t,noted:r},i){let a=[...n.get(e)??[]].filter(e=>r.has(e));if(a.length===0)return;let o=i();for(let n of a)u(e,n,t,o)},fed(e,t,r){let i=[...n.get(e)??[]];if(i.length===0)return;let a=r();for(let n of i)u(e,n,t,a)},close(){r=!0;for(let[e,t]of n)for(let n of t)a(e,n,{kind:`closed`})}}}function EQ(e,t){let n=null,r=TQ({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 DQ(e,t,n){let r=e.arrived(t.sessionId,{at:n,request:t.facts()});return{...t.settle(n),arrival:r}}const OQ=(e,t)=>({view:e,state:{...e.source.state(),idleSince:t.idleSince},...t.handed});function kQ(e,t,n,r){let i=r();return e.drew(t.sessionId,n,()=>OQ(t,i)),i}function AQ(e,t,n,r){let i=r();return e.fed(t.sessionId,n,()=>OQ(t,i)),i}var jQ=class extends Error{name=`RecordingFailed`};function MQ(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={request:0,feed:0},d=()=>{},f=t.after(i*1e3,()=>d()),p=()=>d(),m={write:e=>{h(c,wQ(e)),l++,e.kind===`draw`&&u[e.drawing.by]++},end:e=>{f(),a.removeEventListener(`abort`,p);let t=e.kind===`failed`?e.error:null;try{g(c),u.request+u.feed===0&&ee(r)}catch(e){t??=e}t===null?o({path:r,lines:l,answers:u.request,frames:u.feed,daemonClosed:e.kind===`closed`}):s(new jQ(`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),ee(r),s(e)}})}const NQ=()=>{},PQ=e=>({ok:!1,error:e instanceof Error?e.message:O(e),code:`RENDER_FAILED`,daemonV:3}),FQ={ansi:e=>({ok:!0,output:Ine(e)}),frame:e=>({ok:!0,frame:e})};function IQ(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.monotonic(),s=[[`sid`,t]];try{try{var c=Oo();let i=c.u(UQ(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=AQ(e.recorder,i.view,r,()=>GQ(e,i,{by:`feed`,fps:n})),p=FQ.ansi(o.body),m=$Q(e.links.to,t,o,nQ(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}=sQ(`render`,s,{kind:`threw`,error:e},Qe(i,o)),r=PQ(e);return{bar:Ane(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:NQ,failure:{level:t,line:`frame ${n}`}}}}function LQ(e,t,n){let{sessionState:r}=e;return cJ(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function RQ(e,t){try{var n=Oo();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:aJ(i.view.source.effective(),Mc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function zQ(e,t,n){let r=e.frameFeeds.latest(n);return BQ(e,t,n,r===null||Mc(r.hints.tmux))}function BQ(e,t,n,r){try{var i=Oo();return aJ(LQ(e,n,i.u(e.renderCache.hold(t)).state),r)}catch(e){i.e=e}finally{i.d()}}function VQ(e,t,n,r){iQ(n,{renderer:r,at:t.toFixed(3)});let i=e.hints,a=Pr(e,i),o=Fr(a);return iQ(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`,pane:ul(e.pane),rateLimits:e.rateLimits}),o}function HQ(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:_ee(e.watcherRegistry.filesystem,a)}}},c=VQ(o,n,r,e.rendererName);iQ(r,{encoding:o.encoding});let l=o.requested;return WQ(i.holdSession(l,o),o,c,n,r)}function UQ(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=VQ(o,n,r,e.rendererName)}catch(e){throw a[Symbol.dispose](),e}return WQ(a,o,s,n,r)}function WQ(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 GQ(e,t,n){let{sessionState:r,frameFeeds:i,renderCache:a,updateWatch:o,linkIds:s,links:c,fileEvents:l,renderWarnings:u,payloadProviders:d,effectSessions:f,menuIdle:p,launcher:m,mismatchRuns:h}=e,{req:g,at:_,facts:v,sessionId:y,entry:b,state:x,view:S,hintsError:C}=t,w=S.source.payload(),T=S.source.effective(),E=S.source.failure(),ee=LZ(S.source);iQ(v,{lanes:Qc.filter(e=>ee[e]).join(`,`)||`-`}),iQ(v,{width:String(w.term.cols)});let D=XZ(r,y,_,n.by),te=o.notice({to:c.to,sessionId:y,dismissed:r.get(y,xz),enabled:T.updateNotice}),O=DU(b.repos,y,c),k=(e,t)=>({about:e,text:t,copy:t}),ne=e=>k(e??``,e),A=[ne(Lr(g.refusedArgs)),ne(C),k(`session-pane`,dl(g.pane,ee,h.lasted(g.sessionId,g.pane))),k(`load`,b.lastError),k(`update-act`,o.error()),k(`link-ids`,s.error()),...x.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),...ZZ(D).map(e=>k(`click\0${e.at}\0${e.text}`,e.text))].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),re=b.watch===null?null:dj(`config watch`,b.watch,null),ie=m.launcherWarnings(_,n.by),ae=ie.find(e=>e.kind===`launch-pipes`),oe=ae?.event??null,se=[...qc(l.delivery(),e.watcherRegistry.namesPolled),...ie,...re===null?[]:[{kind:`config-watch`,message:re}],...b.lastWarning===null?[]:[{kind:`load`,message:b.lastWarning}],...E===null?[]:[{kind:`facts`,message:E.cause===`inputs`?`the bar is held on the last turn taken: ${E.reason}`:`the bar is drawn from the last facts that were read; the next could not be stamped: ${E.reason}`}],...S.source.foreign().map(KQ)],ce={config:x.config},le=iU(c.to,y,n.by,A,[...te,...O],[...se.map(e=>({about:qQ(e),message:e.message})),...u.ofSession(y,n.by,ce).map(e=>({about:`${e.kind}\0${e.message}`,message:e.message}))].map(e=>({about:e.about,text:e.message,copy:e.message}))),ue=S.source.facts(),de={drawing:n,feeds:i.feedsOf(y,_),diagnostics:le},fe=To(w.metrics)?void 0:w.metrics;iQ(v,{builtins:Hq(Object.keys(ue.builtins)),...Uq(ue.sources)}),iQ(v,Wq(ue.runs)),iQ(v,{factsSeq:String(ue.seq),prompts:String(fe?.messageCount??`-`),nonPrompts:String(fe?.nonPrompts??`-`),pr:tq(w.git),feeds:VZ(de.feeds)});let pe=[],me=f.of(y),{body:he,viewing:ge,geometry:_e,evaluated:ve,cellBreaks:ye,rules:be,idleSince:xe}=p.drawn(y,_,T.menuTimeout,e=>RZ(S,de,_,me,e,r.get(y,MS),c.to,e=>pe.push(e))),Se=oU(le),Ce=new Map(le.map((e,t)=>[Se[t],e.copy])),we=()=>a.delivered(y,n.by,Ce),Te=p.since(y,_);iQ(v,{menuIdle:Te===void 0?`-`:`${(_-Te).toFixed(1)}s/${T.menuTimeout}s`});let Ee=u.drawn(y,n.by,ce,pe),De=d.gitProvider.getStats(),Oe=d.usageStore.getStats(),ke=me.lastFrame(),Ae=ke.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,je=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,Me=e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`file-events`:return`${e.kind}:${e.state}`;case`domain`:return`domain:${e.key}`;case`load`:case`facts`:case`config-watch`:case`lifeline`:case`launch-pipes`:case`when`:return e.kind}},Ne=[...se,...pe].map(Me).join(`,`)||`-`;return iQ(v,{git:`${De.size}/${De.hits}h/${De.misses}m`,usage:`${Oe.size}/${Oe.hits}h/${Oe.misses}m`,effect:ke.effect,effectT:ke.t.toFixed(3),speed:`${ke.speed}x`,effectRows:`${ke.made}made/${ke.reused}reused`,effectOwn:Ae,fadeBasis:ke.basis,stateRev:String(ke.revision),fades:je(ke.fades),leaves:je(ke.leaves),motion:he.motion,evaluated:String(ve),cellBreaks:String(ye),pending:he.pending.join(`,`)||`-`,rules:[...be].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:A.length>0?`Y`:`N`,clickError:D.map(({hold:e})=>e).join(`,`)||`-`,pipeEvent:ae?.hold??`-`,upd:String(te.length),ask:String(O.length),warn:Ne,diag:String(le.length),warnRecord:Ee?`new`:`kept`,viewer:ge===null?`-`:`${ge.index}/${le.length}p${ge.page+1}`}),{drawn:{body:he,viewerOpen:ge!==null,diagnostics:le,geometry:_e},evaluated:ve,cellBreaks:ye,answersClick:QZ(D),pipeShown:oe,delivered:we,lanes:ee,idleSince:xe,handed:de}}const KQ=({key:e,held:t,admits:n})=>({kind:`domain`,key:e,message:`"${e}" holds ${JSON.stringify(t)}, which this config does not admit (it admits ${n}), so the bar ignores it and draws as if nothing were picked`}),qQ=e=>e.kind===`domain`?`${e.kind}\0${e.key}`:e.kind;function JQ(e,t){let{laneSetups:n,tmuxStatusLines:r}=e,i=BQ(e,t.requested,t.sessionId,Mc(t.hints.tmux));return r.observe(t.sessionId,t.pane,i.tmuxStatus),n.noted(t.sessionId,i)}function YQ(e,t,n){return kQ(e.recorder,t.view,n,()=>GQ(e,t,el))}function XQ(e){return{sessionId:e.hookData.session_id,hints:e.hints,origin:e.requested,transcript:e.hookData.transcript_path,answered:xF(e.hookData)}}function ZQ(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);return s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,cl(s.hints,t,e.heldSession),r.tmuxStatus),a.clicked(t,n,r)}async function QQ(e,t,n,r,i){try{var a=Oo();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(HQ(e,t,n,i)),u=DQ(e.recorder,l.view,n),d=o.monotonic(),f=r-d;iQ(i,{deadline:`${t.deadline.kind}:${Math.round(f)}ms`});let p=await Nj(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)}: ${O(e)}`),o.after),m=o.monotonic();iQ(i,{waited:`${Math.round(m-d)}ms`,ended:p,refreshed:lq(u.refreshed)});let{drawn:h,answersClick:g,pipeShown:_,delivered:v,lanes:y}=YQ(e,l,u.arrival),b=t.sessionId,x=nQ(y,s.following(b)),S=SF(t.hints.client??null)===`statusline`,C=FQ[t.encoding](S?$Q(e.links.to,b,h,x):h.body);return iQ(i,{handoff:(S?x:[]).join(`,`)||`-`,drew:`${Qe(o,m)}ms`}),{resp:C,motion:h.body.motion,answersClick:g,pipeShown:_,delivered:v}}catch(e){a.e=e}finally{a.d()}}function $Q(e,t,n,r){let[i,...a]=r;return i===void 0||n.viewerOpen?n.body:rF(n.body,vU(rQ(e,t,[i,...a]),n.diagnostics,e,t,n.geometry))}const e$=/^─{20,}/,t$=/^❯(\s|$)/,n$=/›\s*stashed$/;function r$(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>e$.test(e)?[t]:[]).at(-2);return n===void 0||!t$.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function i$(e){if(e.inMode)return{kind:`in-mode`};let t=r$(e);return t===null?{kind:`no-prompt`}:n$.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function a$(e){return/^❯\s*\S/u.test(r$(e)?.prompt??``)}const o$=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function s$(e){return e.screen.some(e=>o$.test(e))}const c$={"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 l$(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 u$(e,t,n){let r=i$(await e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:c$[r.kind]};let i=await e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}async function d$(e,t,n,r,i){let a=await sc(e,t,n,r,i);if(a.kind===`failed`)throw Error(a.reason);return a}async function f$(e,t){let n=await d$(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 p$(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 m$(e,t,n){let r=await d$(e,t,`claude-input.type`,p$(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 h$(e){return{read:t=>f$(e,t),type:(t,n)=>m$(e,t,n)}}const g$={launch:({what:e})=>`launch:${e}`,"type-slash":({line:e})=>`type-slash:${e}`,"apply-update":()=>`apply-update`,run:({run:e})=>`run:${e.action}`,"lane-setup":({lane:e,on:t})=>`lane-setup:${e}-${t?`on`:`off`}`,doctor:({step:e})=>`doctor:${e.kind}`};function _$(e){let t=g$[e.kind];return t(e)}const v$=`render-origin`,y$=`client-hints`,b$=(e,t)=>Ze(e,t)>10*1e3;function x$(e,t,n,r){e.delete(n),e.set(n,r),e.size>t&&e.delete(e.keys().next().value)}var S$=class{processes=new Map;constructor(e){this.turns=e}record(e,t,n){if(this.turns.inTurn()===null)throw Error(`mismatch runs: a write of ${JSON.stringify(e)} outside any turn`);switch(t.kind){case`runs`:{let r=sl(t.claude),i=this.processes.get(r)?.confirmed;return x$(this.processes,64,r,{confirmed:i?.sessionId===e?i:{sessionId:e,since:n},runs:new Map}),null}case`unconfirmed`:return null;case`mismatched`:{let r=sl(t.claude),i=this.processes.get(r)??{confirmed:null,runs:new Map};x$(this.processes,64,r,i);let a=i.confirmed;if(a?.sessionId===t.held&&!b$(a.since,n))return i.runs.delete(e),null;let o=Math.min(i.runs.get(e)?.since??n,n),s={since:o,lasted:b$(o,n)};return x$(i.runs,4,e,s),s}}}of(e,t){return t.kind===`unconfirmed`?null:this.processes.get(sl(t.claude))?.runs.get(e)??null}lasted(e,t){return this.of(e,t)?.lasted??!1}};const C$=(e,t)=>e===null?`-`:`${e.lasted?`lasted `:``}${Ze(e.since,t)}ms`;function w$(e,t){return{get:(n,r)=>{let i=e.get(n,r);return i===null||t(n)?.verdict(r,i).kind===`foreign`?null:i},revision:t=>e.revision(t)}}function T$(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?Ky:qy;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const E$=Object.entries(xx),D$=new Set(Cx.map(e=>e.sessionKey)),O$=()=>!1;function k$(e,t){return cJ(e,e=>D$.has(e)?t(e):null,O$)}const A$=[`preset`,`theme`];function j$(e,t,n){let r=new Set(A$.slice(0,n).map(e=>xx[e].sessionKey));return cJ(e,e=>r.has(e)?t(e):null,O$)}function M$(e,t){let n=Array.from({length:A$.length+1},(n,r)=>j$(e,t,r));return e=>{let t=A$.indexOf(e);return n[t===-1?A$.length:t]}}function N$(e,t,n,r){return e.flatMap(([e,i])=>{let a=T$(t,e);return a===null||a===T$(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function P$(e,t,n){return T$(k$(e,t),n)}function F$(e,t){let n=k$(e,t);return N$(E$,n,M$(e,t),t=>I$(e,n.preset,t.configKey))}function I$(e,t,n){return n in(aS(e.presets,t).globals??{})?BN(t,n):n}function L$(e,t,n){let r=iS(t(xx.preset.sessionKey),e.globals.preset,e.presets),i=VN(n);return{key:i?.scope===`globals`?I$(e,r,i.field):n,globals:lS(e,r)}}function R$(e,t){let{preset:n}=k$(e,t);return V$(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:Ob(a,s);return c===void 0||Db(c)===Db(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function z$(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return rS(e.presets).flatMap(n=>{let i=V$(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 Tb(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:Ob(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const B$=new WeakMap;function V$(e,t){let n=B$.get(e)??new Map;B$.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...sb(oS(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Cb(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=k$(e,t);return{from:n.preset,globals:aS(e.presets,n.preset).globals??{},picks:N$(E$.filter(([e])=>e!==`preset`),n,M$(e,t),e=>e.configKey),placements:R$(e,t)}}function U$(e,t){return cJ({...e,globals:{palette:t},presets:{}},()=>null,O$)}function W$(e,t){let n=k$(e,t),r=T$(n,`theme`);if(r===null)return{kind:`rule`};let i=U$(e,r),a=lS(e,n.preset),o=Object.fromEntries(mx.map(e=>[e,T$(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:mx.some(e=>o[e]!==T$(i,e))}}function G$(e){return{sessionKeys:Cx.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...vN(e)?BK.map(t=>BN(t,e)):[],...zN(e)?gy().map(t=>RN(t,e)):[]]}}function K$(e){return new Set(Cx.map(e=>e.configKey).filter(t=>G$(t).fileKeys.some(t=>Y$(e,J$(t)))))}function q$(e,t,n){let r=F$(e,n),i=new Set(r.map(e=>e.configKey)),a=Ox(e=>i.has(xx[e].configKey)||t.has(xx[e].configKey)),o=W$(e,n);return{unsaved:r.length+R$(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function J$(e){let t=VN(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return HN(t)}function Y$(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&Y$(e[n],r)}function X$(e,t,n){let r=kx.get(n);if(r!==void 0)return P$(e,t,r);for(let[,t]of yb(e))if(t.key===n)return t.default??null;return null}function Z$(e,t){let n=MN(e).get(t);return n===void 0?null:String(n)}const Q$={inside:()=>[],defaultOf:()=>ma,menus:[]},$$=e=>`${e.key}\0${e.member}`;function e1(e){let t=new Map,n=n=>{let r=`${n.name}\0${rb(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:tG(a,rb(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))??new Map;n.set($$(t),t),o.set($$(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($$(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 rS(e.presets))d(oS(e,t).node,[]);for(let t of Object.values(e.actions)){let e=Oa(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));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get($$(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),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const t1=new WeakMap;function n1(e){let t=t1.get(e);if(t!==void 0)return t;let n=e1(e);return t1.set(e,n),n}function r1(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 i1(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 a1(e,t,n,r){let i=t(e),a=(t,a,o)=>{let s=r1(n(t),e=>i.get(t,e),a);(0,X.runInAction)(()=>{o();for(let n of s)e.clear(t,n)}),s.length>0&&r(`close-nested: folded=${s.join(`,`)} (session=${t})`)},o=(t,n)=>a(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)=>o(e,[{key:t,value:n}]),setBatch:o,clear:(t,r)=>a(t,[{key:r,value:n(t).defaultOf(r)}],()=>e.clear(t,r))}}const o1=new Set([`1`,`true`]),s1=new Set([`0`,`false`,``]);function c1(e,t){let n=N1(e),r=n.scope===`segment-palette`?`string`:vx(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(o1.has(t))return`true`;if(s1.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function l1(e,t){try{return e.readFileSync(t)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function u1(e,t,n,r){try{if(n===null){e.rmSync(vr(e,t));return}Cr(e,t,n)}catch(e){let n=`config write failed (${t}): ${e.message}`;throw r(`error`,n),Error(n)}}function d1(e){return/^\s*$/.test(e)?null:Fa(e)}function f1(e,t){return e!==null&&La(e,t)!==void 0}function p1(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(p1),...i}}return e}function m1(e){if(!Ux(e))return p1(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,p1(t)])),...n}}const h1=LK,g1=h1.segments,_1=h1.presets,v1=h1.root;function y1(e,t,n,r){if(!f1(e,t)&&n===void 0)throw new R(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function b1(e,t){let n=HN(t);return t.scope===`segment-palette`&&y1(e,[`segments`,t.segment],g1[t.segment],n.join(`.`)),n}function x1(e){return Fa(Ga(e))}function S1(){return Object.entries(v1.rows).map(([e,t])=>{let n=p1(t);return{path:[`root`],fragment:x1({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function C1(e,t){let n=e===null?void 0:La(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function w1(e,t){if(t===void 0)return null;let n=m1(t);return{path:e,fragment:x1(n),unit:{path:e,value:n}}}function T1(e,t){let n=[`presets`,t],r=[...n,`root`],i=_1[t];y1(e,n,i,r.join(`.`));let a=C1(e,r)??w1(r,i?.root);return a!==null&&fo(a.fragment)?a:null}function E1(e,t){let n=uo(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 D1(e,t){return[...S1(),C1(e,[`root`]),T1(e,t)].filter(e=>e!==null).reduce(E1,new Map)}function O1(e,t,n){for(let{node:r,...i}of D1(e,t).values())if(mo(r,n))return i;throw new R(`${k1(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 k1(e,t){return T1(e,t)?.path??[`root`]}function A1(e,t){return t.scope===`preset-root`?k1(e,t.preset):HN(t)}function j1(e,{unit:t}){return t===null?e:io(e,t.path,Ga(t.value),Ua)}function M1(e){let t=VN(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function N1(e){let t=M1(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function P1(e,t,n,r,i){let a=K1(t,r),o,s=()=>(o??={chain:z1(t,n)}).chain;q1(t,s,a),i(t,s,a),u1(t.disk,t.path,r,e.logger),e.record(t.path,n,r)}function F1(e,t,n){let r=R1(e,t(),n);if(r.length>0)throw new R(`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 I1=()=>{};function L1(e,t){try{return t()}catch(t){throw!(t instanceof R)||e.above.length===0?t:new R(`${t.message} — or it is declared by ${e.above.map(e=>e.path).join(`, `)}, which the bar does not edit`)}}function R1(e,t,n){if(t===null)return[];let r=new Set(W1(U1(t),U1(n)));return W1(H1(e,t),H1(e,n)).filter(e=>!r.has(e))}function z1(e,t){try{return B1(e,t)}catch(e){if(e instanceof Ab)return null;throw e}}function B1(e,t){return pK(t===null?e.disk:V1(e.disk,e.path,t),e.memo,e.locs,t===null?e.above:[RH(e.path),...e.above],zK,{warned:()=>{}},{repo:e.repo,cwd:e.cwd})}function V1(e,t,n){return{readFileSync:r=>r===t?n:e.readFileSync(r),readdirSync:t=>e.readdirSync(t),statSync:t=>e.statSync(t),lstatSync:t=>e.lstatSync(t),realpathSync:t=>e.realpathSync(t)}}function H1(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function U1(e){return e.layers.at(-1)?.config??e.base}function W1(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=>W1(e[r],t[r],n===``?r:`${n}.${r}`))}function G1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function K1(e,t){try{return B1(e,t)}catch(e){throw e instanceof Ab?new R(`refused: the config file would not load after this click — ${e.message}`):e}}function q1(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 R(`refused: this click would leave a placement of a segment nothing declares — ${o.map(({file:e,issue:t})=>new Ab(e,[t]).message).join(`
209
- `)}`)}function J1(e,t){let n=N1(t),r=d1(l1(e.disk,e.path)??``),i=r===null?void 0:La(r,HN(n));return i!==void 0&&`value`in i?i.value:void 0}function Y1(e,t,n){X1(e,t,n,[])}function X1(e,t,n,r){let i=l1(t.disk,t.path),a=n.reduce((e,[t,n])=>io(e,b1(d1(e),N1(t)),c1(t,n),Ua),i??``);P1(e,t,i,L1(t,()=>Z1(a,t.path,r,e=>e)),F1)}function Z1(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=O1(d1(s),n,i),l=vo(j1(s,c),c.path,i,a,Ga(o));if(l===null)throw new R(`${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 Q1(e,t,n){let r=d1(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of D1(r,t)){if(!mo(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?za(e,c):Ga(s.value);if(a!==`#`)return io(e,[...i,`rows`,a],l,Ua);if(T1(r,t)!==null)throw new R(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return io(e,i,l,Ua)}return e}function $1(e,t){return oo(e,t,t[0]===`presets`&&t.length>2&&!VK(t[1])?2:0)}function e0(e,t,n){let r=n.map(M1),i=l1(t.disk,t.path);if(i===null)return;let a=r.reduce((e,t)=>$1(e,A1(d1(e),t)),i);a!==i&&P1(e,t,i,a,I1)}function t0(e){let t=e===null?void 0:La(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function n0(e,t){let n=new Set([...BK,...t0(e),...t.above.flatMap(e=>Object.keys(Na.default.parse(t.disk.readFileSync(e.path)).presets??{}))].map(MM));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(MM(e)))}function r0(e,t,n,r,i,a){let o=l1(t.disk,t.path),s=d1(o??``),c=n0(s,t),l=[`presets`,c],u=L1(t,()=>T1(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?za(o??``,u.fragment):Ga(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Ga(r)]]],f=i.map(([e,t])=>{let n=BN(c,e);return[b1(s,N1(n)),c1(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>io(e,t,n,Ua),io(o??``,l,`{}`,Ua));return P1(e,t,o,L1(t,()=>Z1(p,t.path,a.map(e=>({...e,preset:c})),Q1)),F1),c}function i0(e,t,n,r){let i=l1(t.disk,t.path);P1(e,t,i,io(i??``,[`themeDefaults`,n],Ga(r),Ua),F1)}function a0(e,t,n){if(VK(n))throw new R(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=l1(t.disk,t.path),a=d1(i??``);if(i===null||a===null||La(a,r)===void 0)throw new R(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=La(a,[`globals`,`preset`]);P1(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>$1(e,t),i),I1)}function o0(e,t,n,r){let i=M1(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=l1(t.disk,t.path),o=r.op===`remove`?r.target:r.anchor,s=L1(t,()=>O1(d1(a??``),i.preset,o)),c=j1(a??``,s),{after:l,placed:u}=s0(c,s.path,r,()=>{let e=K1(t,c).config;return rS(e.presets).map(t=>oS(e,t).node)});if(l===null)throw new R(`${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 P1(e,t,a,l,F1),u}function s0(e,t,n,r){switch(n.op){case`remove`:return{after:go(e,t,n.target),placed:null};case`insert`:{let i=GR(n.segment,n.anchor,r());return{after:_o(e,t,i,n.anchor,n.relation),placed:i}}}}const c0={inTurn:()=>`single-run`};function l0(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 u0={load:()=>({}),save:()=>{},flush:()=>{}};var d0=class{sessions;storage;head=0;atom=(0,X.createAtom)(`SessionState`);constructor(e,t=u0,n=256){this.turns=e,this.maxSessions=n,this.storage=t,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){this.held(e),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.held(e),this.commit(e,e=>{e.values.delete(t)&&(e.revision=++this.head)})}restore(e,t,n){this.held(e),(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,X.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()})}held(e){if(this.turns.inTurn()===null)throw Error(`session state: a write of ${JSON.stringify(e)} outside any turn`)}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=u0}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 f0(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 p0(e,t){return _0(e.dir,t)??m0(e,t)}function m0(e,t){let n=e.onDisk(e.dir);for(let r of h0(t)){let i=g0(n,e.onDisk(r));if(i!==null)return s.join(i,s.relative(r,t))}return null}function h0(e){let t=s.dirname(e);return t===e?[]:[t,...h0(t)]}function g0(e,t){let n=s.relative(e,t);return n===`..`||n.startsWith(`..${s.sep}`)||s.isAbsolute(n)?null:n}function _0(e,t){let n=g0(e,t);return n===``?null:n}function v0(e,t){let n=p0(e,t);return n===null?{kind:`world`,path:t}:{kind:`home`,path:n}}var y0=class extends Error{};function b0(e,t){if(typeof t==`string`){if(!s.isAbsolute(t))throw new y0(`an older build's stored path ${JSON.stringify(t)} is not absolute`);return x0(e,t)}if(typeof t!=`object`||!t)throw new y0(`stored path is not an object: ${JSON.stringify(t)}`);let{kind:n,path:r}=t;if(typeof r!=`string`)throw new y0(`stored path has no path: ${JSON.stringify(t)}`);if(n===`home`){let t=s.join(e.dir,r);if(s.isAbsolute(r)||_0(e.dir,t)!==r)throw new y0(`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 y0(`stored world path ${JSON.stringify(r)} is not absolute`);if(_0(e.dir,r)!==null)throw new y0(`stored world path ${r} lies under the home's root ${e.dir}; a home's file is stored relative to it`);return x0(e,r)}throw new y0(`stored path has no kind of home or world: ${JSON.stringify(t)}`)}function x0(e,t){let n=p0(e,t);return n===null?t:s.join(e.dir,n)}const S0={load:()=>({}),save:()=>{}},C0=new Set(Cx.map(e=>e.sessionKey)),w0=e=>C0.has(e)||e.startsWith(eP),T0=8*1024*1024,E0={past:[],future:[]},D0=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var O0=class{held=X.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,X.runInAction)(()=>this.held.replace(e))}constructor(e,t,n,r=S0){this.disk=e,this.sessionState=t,this.logger=n,this.storage=r,this.state=new Map(Object.entries(r.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??E0;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??E0}begin(){let e=new Map,t=!1,n=(n,r)=>{t=!0;let i=e.get(n)??new Map,a=i.get(D0(r));i.set(D0(r),a===void 0?r:{...r,before:a.before}),e.set(n,i)},r=new Map;return{sessionState:l0(this.sessionState,()=>!0,(e,i,a,o)=>{if(t=!0,!(!w0(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:I0(i,r),o=n.get(e),s=o===void 0?a:B0(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 R(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,R0(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new R(`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(D0)),a=n.net.filter(e=>!i.has(D0(e))),o=j0(V0(z0(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new R(`rewind: ${r.map(U0).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 R(`redo: nothing to redo`);let a=[...n,i],o=j0(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...N0(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(D0)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:V0(n,t),future:V0(i,t),...a!==void 0&&{savepoint:{at:V0([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(D0(e))),below:V0(a.below,t)}}}),new R(`${r}: ${o.map(U0).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):l1(this.disk,t.file)}write(e,t,n){t.kind===`file`?u1(this.disk,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||k0(n)>T0;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,A0(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${T0} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function k0(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 A0({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...N0(n,1,[])}:{past:e,future:t.slice(1),...N0(n,0,[])}}function j0(e){return e.slice(-50)}const M0=e=>e===nP.member;function N0(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:P0(e.net,n),below:e.below}}}function P0(e,t){let n=new Map(e.map(e=>[D0(e),e]));for(let e of t){let t=n.get(D0(e));n.set(D0(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const F0=e=>e.map(e=>({...e,before:e.after,after:e.before}));function I0(e,t){let n=[...e.past,t],r=j0(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...N0(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...L0(e.future,a),...i.below]},n.length-r.length,t)}}function L0(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function R0(e,t){return{past:e.past.slice(0,-1),future:j0([...e.future,t]),...N0(e.savepoint,0,F0(t))}}function z0(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...L0(r,t.at-i.length),...t.below]}function B0(e,t){if(M0(t.after)&&!M0(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!M0(t.after)&&M0(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function V0(e,t){return e.map(e=>e.filter(e=>!t.has(D0(e)))).filter(e=>e.length>0)}function H0(e){return e.map(U0).join(`, `)}function U0(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function W0(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 G0(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(W0))}function K0(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(W0)&&G0(t.below)}function q0(e){if(typeof e!=`object`||!e)return!1;let t=e;return G0(t.past)&&G0(t.future)&&(t.savepoint===void 0||K0(t.savepoint))}function J0(e,t){let n=e=>e.kind===`file`||w0(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 X0(e,t,n,r){return{load:()=>{let i;try{i=e.readFileSync(t)}catch(e){let t=e.code;return t!==`ENOENT`&&r(`warn`,`settings-history read failed (${t}); starting empty`),{}}let a;try{a=JSON.parse(i)}catch{a=null}if(typeof a!=`object`||!a||Array.isArray(a)||!Object.values(a).every(q0))return r(`warn`,`settings-history load: unexpected shape, starting empty`),{};let o=f0(n),s;try{s=Object.entries(a).map(([e,t])=>[e,Y0(t,(t,n)=>{try{return b0(o,t)}catch(t){throw t instanceof y0?new y0(`session ${e}'s ${n}: ${t.message}`):t}})])}catch(e){if(!(e instanceof y0))throw e;return r(`warn`,`settings-history load: ${e.message}; starting empty`),{}}let c=new Set,l=Object.fromEntries(s.map(([e,t])=>[e,J0(t,c)]));return c.size>0&&r(`warn`,`settings-history load: dropped the changes to ${[...c].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),l},save:i=>{let a=f0(n),o=Object.fromEntries(Object.entries(i).map(([e,t])=>[e,Y0(t,e=>v0(a,e))]));try{Cr(e,t,JSON.stringify(o),384)}catch(e){let t=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw r(`error`,t),Error(t)}}}}const Z0=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function Q0(e){return{...Object.fromEntries(Z0.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 $0=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function e2(e){let t=e=>({kind:`failed`,reason:e});if(!$0(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!$0(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!FF.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${FF.join(` or `)}`)}return{kind:`ok`,value:e}}function t2(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const n2=(e,t)=>Ez(e,t,`doctor-marks.json`,{},e2),r2=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},i2=(e,t)=>e.includes(t)?e:[...e,t],a2=(e,t)=>Ez(e,t,`doctor-clicked-terminals.json`,[],r2);var o2=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const s2=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},c2=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),l2=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=c2(e,t);return r===void 0?n:r.projectDir},u2=(e,t)=>c2(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function d2(e){let t=new Map;for(let n of e.split(`
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*f2(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 p2={pullRequests:e=>Bq(e).has(`pr`),rateLimits:e=>[...e].some(e=>PU(`block`,e)||PU(`weekly`,e))};function m2(e,t){let n=new Map;for(let r of sb(oS(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=>vb(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,RU(e,t,n.get(t))])),a=e=>r.filter(t=>p2[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}const h2=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function g2(e){if(typeof e==`string`)return h2.exec(e)?.[1]}function _2(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 v2(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 y2(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=_2(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`?g2(v2(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 b2(e,t){return e===void 0?[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>v(e)):[e]}async function x2(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await S2(No(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function S2(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function C2(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await No(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 zo(t,void 0,void 0);if(s.kind!==`ok`){Pe(`Failed to check agent file ${t}`);continue}i=j2(i,t,s.value);let c=O2(Bo(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){Pe(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function w2(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(E2(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=v2(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||T2.test(r)?`claude-code`:`prompt`}const T2=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function E2(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function D2(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=w2(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:y2(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 O2(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 k2(e){let t=O2(e);if(t.kind===`unparsed`)return Pe(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return D2(t.value)}catch(e){return Pe(`Failed to project JSONL line: ${e}`),null}}function A2(e){let t=[];for(let n of e.split(`
207
+ `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function uX(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}const dX=e=>e.kind===`failed`?uJ:e;function fX(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function pX(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:n,opened:r.length>0,ground:i},deeper:r}}function mX(e){return{...e,cells:e.cells.map(gJ)}}function hX(e,t){let n=t.flatMap(e=>e.filter(e=>e.place===`above`)),r=t.map(e=>e.filter(e=>e.place===`flow`));return[...n,...gX(e,r)]}function gX(e,t){switch(e){case`vertical`:return t.flatMap(e=>e);case`horizontal`:return t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`,place:`flow`},...t.flatMap(e=>e.slice(1))]}}function _X(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:hX(e.direction,e.children.map((t,i)=>n(t,[...r,vX(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function vX(e,t){return e.steps[t]}function yX(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=bX(e);return{width:xX(t),reach:SX(t)}}function bX(e){let t=e.children.map(yX),n=n=>e.direction===`vertical`&&t.slice(0,n).some(({width:e})=>e>0);if(e.direction===`vertical`||e.unit===!0)return t.map((e,t)=>({start:0,span:e,ownLine:n(t)}));let r=0;return t.map((e,t)=>{let i=r;return r+=e.width,{start:i,span:e,ownLine:n(t)}})}const xX=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),SX=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function CX(e,t){let n=bX(e);if(t?.axis===`cell`)return n.map(({start:e,span:n,ownLine:r})=>{let i=t.index+e;return r?{...t,index:i,lineStart:i,lineEnd:i+n.width-1}:{...t,index:i}});let r=tb[e.direction],i=Dv(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),SX(n),xX(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const wX={compile(e,t){let n=CX(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,sb(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),hX(e.direction,e.children.map((n,r)=>t.renderChild(n,dX(t.gate),vX(e,r))))}},TX={drop:e=>e.place,above:()=>`above`},EX={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},DX={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:nb(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(xa(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,cb(t.path),void 0),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render:(e,t)=>t.placed(e.id,OX(e,t))};function OX(e,t){let n=t.lookupSegment(e.name);if(n===void 0)throw Error(`Layout segment "${e.name}" has no matching segment`);if(t.gate.kind===`hidden`)return[];let r=ij(t.scope,e.settings);if(t.gate.kind===`failed`)return PX(e,r,t,t.gate.message);try{let i=t.placement(e),a=fX(t.gate,i.gate());if(a.kind===`failed`)return PX(e,r,t,a.message);if(a.kind===`hidden`)return[];let o=i.bodyGate(),s=o.kind===`failed`&&a.kind===`pending`?a:o;if(s.kind===`failed`)return PX(e,r,t,s.message);let c=jx(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:dP(c)},u=e=>({width:n.width??`auto`,justify:n.justify??`left`,truncate:n.truncate??`right`,baseStyle:e,padding:t.padding,placement:l}),d=s.kind===`shown`,f=a.kind===`pending`?a:s,p=f.kind===`pending`?kX(f.variable):AX(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?jX(p.segment,u):MX(e,r,t,p.variable,c,d,u);if(m===null)return[];let{styles:h,inline:g,drops:_}=m,v=e.opens,y=v===void 0?[]:t.renderBody(v.body,d?a:uJ,h.disclosure).map(e=>({...e,place:TX[v.placement](e)})),b=(e,t,n)=>yJ(EJ([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?EX[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},w=S.flatMap(e=>b(new q(` `.repeat(NX(hJ(e)))),h.trigger,0)),T=(e,t)=>e.band===`own`?t===x?S:w:[],E=y.map((e,t)=>({cells:[...T(e,t),...e.cells],band:`deeper`,place:e.place})),ee=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ee.flatMap(e=>e.cells),...y.flatMap(T)].flatMap(hJ)),[...ee,...E]}catch(n){return PX(e,r,t,n.message??String(n))}}const kX=e=>({kind:`waiting`,variable:e});function AX(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=vw(e);if(t===void 0)throw e;return kX(t.variable)}}function jX(e,t){let{styles:n,fragments:r,lead:i,trail:a,drops:o,open:s}=e,c=s?n.trigger:n.closed,l=t(c);return{styles:n,inline:lX(EJ(r,c)).map((e,t)=>({cells:yJ(e,{...l,lead:t===0?EJ(i,c):[],trail:t===0?EJ(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:yJ(EJ([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function MX(e,t,n,r,i,a,o){n.waited(r);let s=n.lastDrawn(e.id);if(s?.kind===`hidden`)return null;let c=n.decorations(e,i),l=a?c.trigger:c.closed,u=EJ(FX(e.lead,e,t,n),l),d=EJ(FX(e.trail,e,t,n),l);return{styles:c,inline:(s===void 0||s.drawing.own.length===0?[[`auto`]]:s.drawing.own.map(e=>e.cells.map(e=>e.text.cellLength))).map((e,t)=>({cells:e.flatMap((e,n)=>{let r=t===0&&n===0;return yJ(EJ([new q(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function NX(e){return e.reduce((e,t)=>e+t.cellLength,0)}function PX(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:yJ([new q(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:dP(n.palette)},lead:FX(e.lead,e,t,n),trail:FX(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function FX(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=vw(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const IX={container:wX,segment:DX};function LX(e){return IX[e]}var RX=class{last=null;from(e){let{last:t}=this;return t!==null&&t.source.config===e.config&&t.source.preset===e.preset&&t.source.revision===e.revision&&t.source.width===e.width?t:null}begin(e,t){let n=new Map,r=new Map;return{placed:(e,r)=>{let{drawing:i}=t(e,r);return n.set(e,i===null?zX:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const zX={kind:`hidden`},BX={palette:`theme`,style:`style`,effect:`effect`},VX=Tx.get(`colorCompatibility`),HX={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function UX(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function WX(e){if(e.ok)return e.value;throw e.error}const GX=e=>({read:()=>e}),KX=H_({basePalette:V_,palette:V_,decor:iy});var qX=class{evaluated=0;memory=new RX;scope;binding;facts;look=X.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&KX(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=X.observable.box(r,{deep:!1}),this.scope=nj(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(VX);return e.kind===`found`&&typeof e.value==`string`&&Vy(e.value)?e.value:`truecolor`});let i=(0,X.observable)(HX,void 0,{deep:!1});this.facts=i;let a=this.look,o=this.phase,s=()=>this.layout.read();this.binding={store:e,registry:t,get width(){return i.width},get chromeCols(){return i.chromeCols},get padding(){return i.padding},get seamCols(){return i.seamCols},get look(){return o.ruling?void 0:a.get()},get layout(){return o.ruling?void 0:s}},this.layout=this.derive(`layout`,n.layoutReadsInstant,()=>{let e=n.roots.get(i.preset),t=a.get().palette;return _X(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=jR(e);return i===void 0?[]:[{name:i,address:n,palette:jx(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>Hy(this.colorCompatibility())})}bind(e){(0,X.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,X.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=kM(e);return t===void 0?DM(e)===void 0?mM(this.view.get().payload(),e):mM(this.projected,e):pM(this.slotName(t))}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[BX[e]];if(t.kind===`decided`)return XX(t.name,null,null);let r=QX(this.source,e,t.source);if(this.source.instant.has(r.template))return{kind:`per-draw`,rule:r};let i=this.rule(r.template);switch(i.kind){case`named`:{let t=null;return n=$X(this.source,e,i.name,r.where,e=>{t=e}),XX(n,t,null)}case`pending`:return XX(n??ky[e],null,i.variable);case`failed`:return n=ky[e],XX(n,Ay(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!ZX(i,e))&&(i=e),i}),this.slots.set(e,t)}return t.read()}slotName(e){let t=this.slot(e);return t.kind===`settled`?t.name:this.drawnSlots.get(e)??ky[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,X.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return fJ(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>fY(this.source.activeSegment,()=>fJ(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new eZ(this,e),this.placements.set(e,t)),t}rule(e){let t=this.rules.get(e);return t===void 0&&(t=this.derive(`rule`,this.readsInstant(e),()=>{this.phase.ruling=!0;let t=this.source.runtime.bound===this.binding?null:MJ(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=vw(e);return t===void 0?{kind:`failed`,error:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}finally{t?.[Symbol.dispose](),this.phase.ruling=!1}}),this.rules.set(e,t)),t.read()}readsInstant(...e){return e.some(e=>e!==void 0&&this.source.instant.has(e))}derive(e,t,n){let r=()=>(this.evaluated++,n());return this.store.derive(`part ${e}`,t?`projection`:`computed`,t?this.oncePerDraw(r):r)}oncePerDraw(e){let t=null;return()=>(t?.draw!==this.draws&&(t={draw:this.draws,answer:UX(e)}),WX(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:jR(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function JX(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new qX(t,n,e,r);return e.views.set(t,a),a}function YX(e,t){let n=e.views.get(t);if(n===void 0)throw Error(`a store was drawn before its view was bound (bindView): its inputs have no source`);return n}const XX=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),ZX=(e,t)=>e.kind===`settled`?t.kind===`settled`&&e.name===t.name&&e.warning===t.warning&&e.waited===t.waited:t.kind===`per-draw`&&e.rule===t.rule;function QX(e,t,n){let r=e.globalExpressions.get(t)?.get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the view but no compiled template exists — the compile and the resolution disagree about isExpression`);return r}function $X(e,t,n,r,i){switch(t){case`palette`:return Ix(n,r,i).name;case`style`:return Ey(n,e.styles).name;case`effect`:return Iy(n).name}}var eZ=class{where=tZ(H_({palette:V_,region:ny}));ground=tZ(H_({colours:rZ,bodyOpen:V_}));opened=tZ(H_({colours:rZ,open:V_}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=ij(e.scope,t.settings),{when:a,bg:o,fg:s,template:c}=n,{lead:l,trail:u}=t,d=t.opens?.open;this.ownGate=a===void 0?GX(dJ):e.derive(`${t.id} when`,e.readsInstant(a),()=>fY(r,()=>fJ(a,i))),this.open=d===void 0?GX(uJ):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>fY(r,()=>fJ(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return oZ(r,t,n,a,e.registry.drawnAt(),o,s,i)}),this.body=e.derive(`${t.id} body`,e.readsInstant(c),()=>{let{colours:e,bodyOpen:n}=this.ground.get();return sZ(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?GX(lZ):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return cZ(r,t,e,n,l,u,i)})}gate(){return this.ownGate.read()}bodyGate(){return this.open.read()}evaluate(e,t){this.where.set({palette:e,region:t});let n=this.colours.read();this.ground.set({colours:n,bodyOpen:this.open.read().kind===`shown`});let r=this.body.read();return this.opened.set({colours:n,open:r.open}),dZ(n,r,this.affixes.read())}};function tZ(e){let t=X.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,X.runInAction)(()=>t.set(e)),get:()=>t.get()}}const nZ=(e,t)=>e.hex===t.hex,rZ=H_({palette:V_,drawnAt:V_,tint:nZ,text:nZ,bg:nZ,disclosure:ay});function iZ(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const aZ=e=>$v(e.palette,e.disclosure,e.drawnAt);function oZ(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...dy(n,r,i)};return dY(e,iZ(t,c),e=>{let t=pP(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function sZ(e,t,n,r,i,a){return dY(e,iZ(t,n),e=>(e.bg=i?aZ(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function cZ(e,t,n,r,i,a,o){return dY(e,iZ(t,n),e=>(e.bg=r?aZ(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const lZ={lead:[],trail:[],drops:[]};function uZ(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return JJ(t,aZ(e).state,n)},get band(){return JJ(t,aZ(e).plane,n)},get close(){return ZJ(t,aZ(e).state,n)},disclosure:r}}function dZ(e,t,n){return{styles:uZ(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function fZ(e,t,n,r,i,a,o){let s=oZ(e,t,n,r,i,void 0,void 0,o);return dZ(s,sZ(e,t,s,a,!1,o),lZ)}function pZ(e,t,n,r,i){return uZ(oZ(e,t,n,r,i,void 0,void 0,{}))}function mZ(e,t){return{payload:()=>e,selections:()=>t}}function hZ(e){if(`ttl`in e)return{kind:`ttl`,durationMs:lM(e.ttl)};if(`watch_file`in e)return{kind:`watch_file`,path:e.watch_file};if(`depends_on`in e)return{kind:`depends_on`,varNames:e.depends_on};if(`key`in e)return{kind:`key`,template:e.key};if(`never`in e)return{kind:`never`};throw Error(`Unknown CacheDecl discriminator — loader invariant violated: ${JSON.stringify(e)}`)}function gZ(e,t){switch(db(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,regex:new RegExp(e.regex),default:t};case`text`:return{kind:`text`,default:t}}}function _Z(e,t,n,r,i){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`source`:e.declareSourceDocument(t);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default,i);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:hZ(n.cache),parse:gZ(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:hZ(n.cache),parse:gZ(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{type:n.type??`string`,varDefault:n.default,derivation:i});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function vZ(e,t,n,r=oT.EMPTY){let i=r;for(let[r,a]of Object.entries(t))try{i=e.parse(`{{ define "${r}" }}${a}{{ end }}`,i).defines()}catch(e){throw Error(`Template parse error in ${n}.${r}: ${e.message}`,{cause:e})}return i}function yZ(e,t,n){let{compiled:r,loadWarnings:i}=xZ(e,t,n.cwd,bZ(n.links),TZ);return{...r,loadWarnings:i}}const bZ=e=>(t,n)=>EZ(n,e);function xZ(e,t,n,r,i=TZ){let a=SZ(e),o=CZ(a);return{compiled:r(o,a),compileKey:o,loadWarnings:wZ(e,t,n,i)}}function SZ(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of Ex)n in t&&r.set(e,n);for(let[t,n]of vb(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...bG(e)].sort(([e],[t])=>e<t?-1:1)}}function CZ(e){return ae(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function wZ(e,t,n,r){let i=cX(e),a=bG(e),o=[];for(let[s,c]of iw(e))if(r.has(i.get(s)))try{_Z(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const TZ=new Set([`directory`,`view`]);function EZ({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,links:r},a=()=>kJ(i,`drawnAt`).registry.drawnAt(),o=lY(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=nS(e.presets),u=bR(e),d=[e=>MY(i,o,e.now)],f=tj({extraFuncs:{...KJ(i),...jY(i),...wY(i,o),...DY(i),...LY(i,o),...UY(i,o),...qY(s),...XY(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=vZ(f,e.helpers,`helpers`),m=new Map,h=e=>{let t=f.parse(e,p);return m.set(t,e),t},g=new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n=h(e);return g.set(e,n),n},v=new Map(t);i.compiled=NJ(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=n.partials===void 0?p:vZ(f,n.partials,`segments.${t}.partials`,p),r=t=>{let n=f.parse(t,e);return m.set(n,t),n},i=(e,i,a=n.partials===void 0?_:r)=>{try{return a(e)}catch(e){throw Error(`Template parse error in segments.${t}.${i}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:i(n.when,`when`),template:i(n.template,`template`,r),bg:n.bg===void 0?void 0:i(n.bg,`bg`,r),fg:n.fg===void 0?void 0:i(n.fg,`fg`,r)}}let b=(e,t,n)=>{try{return _(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},x=t=>{let n=Sb(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Vee(t,e,a,t=>String(kJ(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},S=(e,t,n)=>{let r={path:t,at:n,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:S,placementSettings:x};return LX(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=aS(e,t);C.set(t,S(n,r,void 0))}let w=new Map(xy.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of SG(e)){let e=t.join(`.`),i=w.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:kZ(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let T=new Set(n.map(([e])=>e)),E={reads:kU({names:T,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:ej(d)},ee=TG(E),D=[...C.values()].flatMap(OZ(y)).some(e=>ee(m.get(e))),te=D?new Set([...E.clock,HY]):E.clock,O=TG({...E,clock:te}),k=new Set([...m].flatMap(([e,t])=>O(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=TG({reads:kU({names:T,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:E.projections,clock:te});for(let e of pH){let n=y[t][e];n!==void 0&&r(m.get(n))&&k.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,links:r,globalExpressions:w,instant:k,layoutReadsInstant:D,styles:e.styles,runtime:i,views:new WeakMap}}function DZ(e){return Object.entries(e.segments).flatMap(([t,n])=>[n.when,n.bg,n.fg,n.template].some(t=>t!==void 0&&e.instant.has(t))?[t]:[])}const OZ=e=>t=>{let n=[];return _X(t,e=>(n.push(e),!0)),n.flatMap(t=>[...t.when===void 0?[]:[t.when],...t.kind===`segment`&&e[t.name].when!==void 0?[e[t.name].when]:[]])};function kZ(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}const AZ=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function jZ(e,t,n,r,i){let a=MZ(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function MZ(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??ky[e];case`failed`:return r({kind:`rule`,slot:e,message:Ay(t.where,e,`the rule failed — ${n.error}`)}),ky[e]}}function NZ(e){return PZ(e).filter(e=>!e.name.startsWith(wS)).map(e=>e.id)}function PZ(e){return e.kind===`container`?e.children.flatMap(PZ):[e,...e.opens===void 0?[]:PZ(e.opens.body)]}function FZ(e,t,n,r,i,a){let o={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return JX(e,t,n,mZ(o,a)),o}function IZ(e,t,n,r,i,a,o,s,c){try{var l=Oo();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new XP(``),h=m.clockAt(a,My[c.animationSpeed]),g=l.u(WA(a,h.timeline)),_=YX(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:gF(v),padding:v.padding,seamCols:_F(v),preset:c.preset},i);let y=_.evaluated;l.u(MJ(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:uv[c.variation],shade:tv[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},w=_.memory.begin(C,pX),T=_.memory.from(C),E=new Set,ee={held:e=>T?.rules.get(e),waited:e=>E.add(e),settled:w.rule},D=new Map,te=e=>{let n=_.slot(e);if(D.set(e,n.kind===`settled`?`kept`:`per-draw`),n.kind===`settled`)return n.warning!==null&&p({kind:`rule`,slot:e,message:n.warning}),n.waited!==null&&E.add(n.waited),n.name;let r=$X(t,e,jZ(e,n.rule,_,p,ee),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:O,style:k,effect:ne}=_.selections(),A=O.kind===`decided`?O:Ix(te(`palette`),``,AZ),re=k.kind===`decided`?k:Ey(te(`style`),e.styles),ie=ne.kind===`decided`?ne:Iy(te(`effect`)),ae=A.value,oe=Nx(ae,re.value);_.publishLook({basePalette:ae,palette:oe,decor:S});let se=oe.get(`warning`),ce=c.idleSince===void 0?null:{idleSince:c.idleSince,timeoutS:c.menuTimeout,fill:se,text:Uv(oe,se,r.drawnAt())},le=m.motion(ie.value,h,{transitions:x,source:C,last:T,returned:pX,hold:mX},ce);u?.clear();let ue=t=>e.segments[t],de=(e,i,a)=>{let o=i.kind===`hidden`?i:fX(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${NZ(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:o.message,message:`${t}: ${o.message} — what it gates is hidden`})}}:o,c={scope:_.scope,palette:oe,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,i,o)=>fZ(t.activeSegment,e,i,a,r.drawnAt(),o,n),lookupSegment:ue,renderChild:(e,t,n)=>de(e,t,ly(a,n)),renderBody:(e,t,n)=>de(e,t,uy(n)),closeDisclosure:e=>qJ(t.links.to,n,e),placed:(e,t)=>w.placed(e,le.placed(e,t)),lastDrawn:e=>T?.placements.get(e),waited:e=>E.add(e),decorations:(e,n)=>pZ(t.activeSegment,e,n,a,r.drawnAt())};return LX(e.kind).render(e,c)},fe=t.roots.get(b);if(fe===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${eS}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let pe=uX(de(fe,dJ,cy(S))).map(({line:e,row:t})=>{let n=wJ(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...bF(n.map(e=>e.owner),v,le.row(t,r,n))}});le.drawn(),w.commit();let me=()=>pe.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||PZ(fe).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`),he=Math.min(g.heard(),...pe.map(e=>e.nextChange)),ge=Number.isFinite(he)?`moves`:me()?`can-move`:`still`;for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{frame:{depth:v.colorCompatibility,rows:pe.flatMap(({kind:e,lines:t})=>t.map(t=>({kind:e,runs:t}))),nextChange:he,motion:ge,pending:[...E].sort()},evaluated:_.evaluated-y,cellBreaks:pe.reduce((e,t)=>e+t.cellBreaks,0),rules:D}}catch(e){l.e=e}finally{l.d()}}function LZ(e){return aJ(e.effective(),e.payload().tmux!==void 0)}function RZ(e,t,n,r,i,a,o,s){let{drawing:c,feeds:l,diagnostics:u}=t,{source:d}=e,f=d.effective(),p=d.payload().term.cols,m=IZ(e.state.config,e.state.compiled,e.store,e.registry,{diagnostics:mU(u),drawing:c,feeds:l,...zq(d.facts(),n)},n,QK(f,p),{perSegmentSink:e.lastRenderCellsBySegment,onRenderWarning:s},{...f,effects:r,idleSince:i}),h=LZ(d),g={width:p,rows:gU(d.hints().termRows,c.by===`feed`?Qc.flatMap(e=>{let t=Zc[e].rows;return h[e]&&t!==null?[t]:[]}):[]),colorCompatibility:m.frame.depth},_=hU(a,u);return{...m,body:_===null?m.frame:rF(m.frame,_U(u,_,o,e.sessionId,c.by,g)),viewing:_,geometry:g}}const zZ={moving:1e3/30,still:1e3},BZ=[`data`,`state`,`reload`,`visibility`];function VZ(e){return Qc.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 HZ(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const UZ=(e,t)=>Zc[t].handsOff?e.resp:e.statusline,WZ=e=>Math.round(1e3/e);var GZ=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)??this.open(e),i={lane:this.laneOf(r,t.lane),sent:null};return r.followers.set(t,i),this.send(t,i),this.hasten(r),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${r.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(r,t)}laneOf(e,t){let n=e.lanes.get(t);if(n!==void 0)return n;let r=this.deps.encoders[t](),i={rate:[],encode:r,out:e.last===null?null:r(e.last.bar,UZ(e.last.answers,t))};return e.lanes.set(t,i),i}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]++,n.phase.kind!==`rendering`&&(n.wokeSince??=this.deps.clock.monotonic()),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 al;let r=t-1,i=this.shown(n);return il(e=>{let a=n.lanes.get(e)?.rate;if(a===void 0)return nl;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,lanes: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},wokeSince:null,wakeToFrameLast:null,wakeToFrameMax: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.lanes.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:`rendering`};let n=e.wokeSince;e.wokeSince=null;let r=this.deps.clock.monotonic(),i=this.deps.instant(),a=Math.min(Math.max(t,i),i+.002),o=r+(a-i)*1e3;try{this.step(e,n,r,o,a)}catch(t){if(e.lastStart=o,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${O(t)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,a)}}step(e,t,n,r,i){let a=this.deps.render(e.sessionId,WZ(this.spacingOf(e)),i);if(a===null){e.noView++,e.phase={kind:`waiting`};return}e.phase={kind:`pushing`},e.lastStart=r;let o=this.deps.clock.monotonic();t!==null&&(e.wakeToFrameLast=o-t,e.wakeToFrameMax=Math.max(e.wakeToFrameMax,o-t)),this.drawn++,e.drawn++,e.drawMs+=o-n,e.evaluated+=a.evaluated,e.cellBreaks+=a.cellBreaks,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,a),this.push(e,a,i),this.feeds.get(e.sessionId)===e&&(o-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,a,i)))}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===`rendering`)return!1;let n=this.deps.clock.monotonic(),r=Math.max(n,e.lastStart+this.spacingOf(e)),i=this.deps.instant();return this.arm(e,i+(r-n)/1e3,i)}arm(e,t,n){let r=Math.max(0,(t-n)*1e3),i=this.deps.clock.monotonic()+r;return e.phase.kind===`due`&&e.phase.at<=i?!1:(this.setTimer(e,t,i,r),!0)}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)},a=[...e.lanes].map(([e,n])=>({held:n,out:n.encode(t.bar,UZ(i,e))}));if(!(e.last?.answers.resp===i.resp&&e.last.answers.statusline===i.statusline&&a.every(({held:e,out:t})=>e.out?.json===t.json))){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{held:e,out:t}of a)e.out?.json!==t.json&&HZ(e.rate,n),e.out=t;for(let[t,n]of e.followers)this.send(t,n)}}send(e,t){let{out:n}=t.lane;n===null||t.sent===n.json||(e.frame(n),t.sent=n.json)}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:oN(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=Vj.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=${WZ(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${BZ.map(t=>`${t}:${e.woke[t]}`).join(`,`)} wakeToFrame=${e.wakeToFrameLast===null?`-`:`last:${e.wakeToFrameLast.toFixed(1)}ms,max:${e.wakeToFrameMax.toFixed(1)}ms`} coalesced=${e.coalesced} daemonRefreshed=${o} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};const KZ=`click.error`;function qZ(e,t,n,r){let i=YZ(e,t).filter(e=>nt(e,5,r,`request`)!==`over`);$Z(e,t,{newest:{text:n,at:r,answered:!1},earlier:i})}function JZ(e,t,n){let r=eQ(e,t);if(r===null)return;let i=e=>n.some(t=>rt(e,t))?{...e,answered:!0}:e,a={newest:i(r.newest),earlier:r.earlier.map(i)};a.newest===r.newest&&a.earlier.every((e,t)=>e===r.earlier[t])||$Z(e,t,a)}function YZ(e,t){let n=eQ(e,t);return n===null?[]:[...n.earlier,n.newest]}function XZ(e,t,n,r){return YZ(e,t).map(e=>({error:e,hold:nt(e,5,n,r)}))}const ZZ=e=>e.flatMap(({error:e,hold:t})=>t===`over`?[]:[e]),QZ=e=>ZZ(e).filter(e=>!e.answered);function $Z(e,t,{newest:n,earlier:r}){e.set(t,KZ,JSON.stringify({...n,earlier:r}))}function eQ(e,t){let n=e.get(t,KZ);if(n===null)return null;let r;try{r=JSON.parse(n)}catch{return null}let i=tQ(r);if(i===null)return null;let{earlier:a}=r;return{newest:i,earlier:Array.isArray(a)?a.flatMap(e=>{let t=tQ(e);return t===null?[]:[t]}):[]}}function tQ(e){if(typeof e!=`object`||!e)return null;let{text:t,at:n,answered:r}=e;return typeof t==`string`&&typeof n==`number`&&(r===void 0||typeof r==`boolean`)?{text:t,at:n,answered:r===!0}:null}function nQ(e,t){return Qc.filter(n=>e[n]&&Zc[n].handsOff&&t.has(n))}function rQ(e,t,n){return{severity:nU,lines:[[rU(`[⟲ claude]`,dC(e,[{verb:GS,args:[t,...n.map(e=>Zc[e].switch.setting)]}]))]]}}function iQ(e,t){for(let n of Object.entries(t))e.push(n)}const aQ={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function oQ(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,O(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function sQ(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...oQ(n)];return{level:aQ[n.kind],line:cQ(e,i)}}const cQ=(e,t)=>`${e}${t.map(([e,t])=>` ${e}=${z(t)}`).join(``)}`;function lQ(e,t,n){if(t.kind===`pending`)return So(t.why);if(e!==void 0&&e.kind!==`pending`){let{at:n,...r}=e;if((0,X.compareStructural)(r,t))return e}return{...t,at:n}}const uQ=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`]),dQ=[[`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`]],fQ=[[`workspace.added_dirs`,`string-list`]];function pQ(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of dQ){let i=gQ(n,e);if(i==null)t.missingRequired.push(e);else{let n=mQ(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of fQ){let i=gQ(n,e),a=i===void 0?r:hQ(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))uQ.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function mQ(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function hQ(e){return Array.isArray(e)&&e.every(e=>mQ(e)===`string`)?`string-list`:mQ(e)}function gQ(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 _Q(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 vQ(e){let t=_Q(e);if(!t.ok)throw Error(`session id ${t.problem}`);return t.id}const yQ=[`session`,`today`,`context`,`metrics`,`activity`,`cache`,`speed`,`autocompact`];var bQ=class{bySession=X.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:L(n,`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,X.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};new Set(YK);function xQ(e,t){let n=Object.keys(e.history);return e.revision===t.revision&&e.back===t.back&&n.every(n=>e.history[n]===t.history[n])&&SQ(e.values,t.values)}new Set(yQ);function SQ(e,t){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>e[n]===t[n])}function CQ(e){return{hookData:e.hookData,cwd:e.cwd,hints:e.hints}}function wQ(e){let t=e.kind===`recording`?{kind:e.kind,v:7,session:e.session,home:e.home}:e.kind===`facts`?{kind:e.kind,at:e.at,facts:e.facts}:e.kind===`draw`?{kind:e.kind,at:e.at,drawing:e.drawing,feeds:e.feeds,state:{...e.state,idleSince:e.state.idleSince??null},diagnostics:e.diagnostics}:e.kind===`state`?{kind:e.kind,state:e.state}:e.kind===`turn`?{kind:e.kind,held:e.held,at:e.document.at,facts:e.document.facts,...CQ(e.request),state:e.state}:{kind:e.kind,...e.kind===`request`&&{at:e.at},...CQ(e.request)};return`${JSON.stringify(t)}\n`}function TQ(e,t){let n=new Map,r=!1,i=e=>{for(let t of e.watching)t();e.watching.clear()},a=(e,t,r)=>{let a=n.get(e);a===void 0||!a.delete(t)||(a.size===0&&n.delete(e),i(t),t.sink.end(r))},o=(e,n,r)=>{if(!(r.kind===`declared`&&r.request===n.declaration))try{n.sink.write(r),r.kind===`facts`&&(n.document=r.facts),r.kind===`turn`&&(n.document=r.document.facts),(r.kind===`state`||r.kind===`draw`||r.kind===`turn`)&&(n.state=r.state),(r.kind===`request`||r.kind===`declared`||r.kind===`turn`)&&(n.declaration=r.request)}catch(r){t(`error`,`recording sid=${JSON.stringify(e)}: ${O(r)}`),a(e,n,{kind:`failed`,error:r})}},s=(e,t,n)=>o(e,t,n),c=(e,t,r,i)=>{if(i.facts===t.document)return;let a=r.source.state();(t.state===null||!xQ(t.state,a))&&s(e,t,{kind:`state`,state:a}),n.get(e)?.has(t)&&o(e,t,{kind:`facts`,...i})},l=(e,t,n)=>{let r=n.source.held();t.turn?.view===n&&t.turn.held===r||(t.turn={view:n,held:r},s(e,t,{kind:`turn`,held:r,...n.source.turn()}))},u=(t,r,i,{view:a,state:o,drawing:u,feeds:d,diagnostics:f})=>{let p=e.sessionView(t),m={at:i,drawing:u,feeds:d,state:o,diagnostics:f},h=[()=>l(t,r,a),()=>c(t,r,a,a.followed.stamped()),()=>s(t,r,{kind:`declared`,request:a.facts()}),()=>s(t,r,{kind:`draw`,...m}),...p===null?[]:[()=>l(t,r,p)]];for(let e of h)n.get(t)?.has(r)&&e()},d=(t,r)=>{let i=e.sessionView(t);if(i===null)return;let a=(e,i)=>{if(!n.get(t)?.has(r))return;let a=(0,X.reaction)(e,i,{fireImmediately:!0});n.get(t)?.has(r)?r.watching.add(a):a()};a(()=>i.source.held(),()=>l(t,r,i)),a(()=>i.followed.stamped(),e=>c(t,r,i,e))};return{record(t,i){if(r)throw Error(`the daemon is closing: it records nothing more`);let o=e.sessionView(t);if(o===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 c={sink:i,watching:new Set,document:null,declaration:null,state:null,turn:null},l=n.get(t)??new Set;return n.set(t,l.add(c)),s(t,c,{kind:`recording`,session:t,home:o.source.home()}),l.has(c)&&d(t,c),()=>a(t,c,{kind:`stopped`})},moved(e){for(let t of n.get(e)??[])i(t),d(e,t)},arrived(e,t){let r=new Set;for(let i of n.get(e)??[])s(e,i,{kind:`request`,...t}),r.add(i);return{at:t.at,noted:r}},drew(e,{at:t,noted:r},i){let a=[...n.get(e)??[]].filter(e=>r.has(e));if(a.length===0)return;let o=i();for(let n of a)u(e,n,t,o)},fed(e,t,r){let i=[...n.get(e)??[]];if(i.length===0)return;let a=r();for(let n of i)u(e,n,t,a)},close(){r=!0;for(let[e,t]of n)for(let n of t)a(e,n,{kind:`closed`})}}}function EQ(e,t){let n=null,r=TQ({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 DQ(e,t,n){let r=e.arrived(t.sessionId,{at:n,request:t.facts()});return{...t.settle(n),arrival:r}}const OQ=(e,t)=>({view:e,state:{...e.source.state(),idleSince:t.idleSince},...t.handed});function kQ(e,t,n,r){let i=r();return e.drew(t.sessionId,n,()=>OQ(t,i)),i}function AQ(e,t,n,r){let i=r();return e.fed(t.sessionId,n,()=>OQ(t,i)),i}var jQ=class extends Error{name=`RecordingFailed`};function MQ(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={request:0,feed:0},d=()=>{},f=t.after(i*1e3,()=>d()),p=()=>d(),m={write:e=>{h(c,wQ(e)),l++,e.kind===`draw`&&u[e.drawing.by]++},end:e=>{f(),a.removeEventListener(`abort`,p);let t=e.kind===`failed`?e.error:null;try{g(c),u.request+u.feed===0&&ee(r)}catch(e){t??=e}t===null?o({path:r,lines:l,answers:u.request,frames:u.feed,daemonClosed:e.kind===`closed`}):s(new jQ(`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),ee(r),s(e)}})}const NQ=()=>{},PQ=e=>({ok:!1,error:e instanceof Error?e.message:O(e),code:`RENDER_FAILED`,daemonV:3}),FQ={ansi:e=>({ok:!0,output:Ine(e)}),frame:e=>({ok:!0,frame:e})};function IQ(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.monotonic(),s=[[`sid`,t]];try{try{var c=Oo();let i=c.u(UQ(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=AQ(e.recorder,i.view,r,()=>GQ(e,i,{by:`feed`,fps:n})),p=FQ.ansi(o.body),m=$Q(e.links.to,t,o,nQ(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}=sQ(`render`,s,{kind:`threw`,error:e},Qe(i,o)),r=PQ(e);return{bar:Ane(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:NQ,failure:{level:t,line:`frame ${n}`}}}}function LQ(e,t,n){let{sessionState:r}=e;return cJ(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function RQ(e,t){try{var n=Oo();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:aJ(i.view.source.effective(),Mc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function zQ(e,t,n){let r=e.frameFeeds.latest(n);return BQ(e,t,n,r===null||Mc(r.hints.tmux))}function BQ(e,t,n,r){try{var i=Oo();return aJ(LQ(e,n,i.u(e.renderCache.hold(t)).state),r)}catch(e){i.e=e}finally{i.d()}}function VQ(e,t,n,r){iQ(n,{renderer:r,at:t.toFixed(3)});let i=e.hints,a=Pr(e,i),o=Fr(a);return iQ(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`,pane:ul(e.pane),rateLimits:e.rateLimits}),o}function HQ(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:_ee(e.watcherRegistry.filesystem,a)}}},c=VQ(o,n,r,e.rendererName);iQ(r,{encoding:o.encoding});let l=o.requested;return WQ(i.holdSession(l,o),o,c,n,r)}function UQ(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=VQ(o,n,r,e.rendererName)}catch(e){throw a[Symbol.dispose](),e}return WQ(a,o,s,n,r)}function WQ(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 GQ(e,t,n){let{sessionState:r,frameFeeds:i,renderCache:a,updateWatch:o,linkIds:s,links:c,fileEvents:l,renderWarnings:u,payloadProviders:d,effectSessions:f,menuIdle:p,launcher:m,mismatchRuns:h}=e,{req:g,at:_,facts:v,sessionId:y,entry:b,state:x,view:S,hintsError:C}=t,w=S.source.payload(),T=S.source.effective(),E=S.source.failure(),ee=LZ(S.source);iQ(v,{lanes:Qc.filter(e=>ee[e]).join(`,`)||`-`}),iQ(v,{width:String(w.term.cols)});let D=XZ(r,y,_,n.by),te=o.notice({to:c.to,sessionId:y,dismissed:r.get(y,xz),enabled:T.updateNotice}),O=DU(b.repos,y,c),k=(e,t)=>({about:e,text:t,copy:t}),ne=e=>k(e??``,e),A=[ne(Lr(g.refusedArgs)),ne(C),k(`session-pane`,dl(g.pane,ee,h.lasted(g.sessionId,g.pane))),k(`load`,b.lastError),k(`update-act`,o.error()),k(`link-ids`,s.error()),...x.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),...ZZ(D).map(e=>k(`click\0${e.at}\0${e.text}`,e.text))].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),re=b.watch===null?null:dj(`config watch`,b.watch,null),ie=m.launcherWarnings(_,n.by),ae=ie.find(e=>e.kind===`launch-pipes`),oe=ae?.event??null,se=[...qc(l.delivery(),e.watcherRegistry.namesPolled),...ie,...re===null?[]:[{kind:`config-watch`,message:re}],...b.lastWarning===null?[]:[{kind:`load`,message:b.lastWarning}],...E===null?[]:[{kind:`facts`,message:E.cause===`inputs`?`the bar is held on the last turn taken: ${E.reason}`:`the bar is drawn from the last facts that were read; the next could not be stamped: ${E.reason}`}],...S.source.foreign().map(KQ)],ce={config:x.config},le=iU(c.to,y,n.by,A,[...te,...O],[...se.map(e=>({about:qQ(e),message:e.message})),...u.ofSession(y,n.by,ce).map(e=>({about:`${e.kind}\0${e.message}`,message:e.message}))].map(e=>({about:e.about,text:e.message,copy:e.message}))),ue=S.source.facts(),de={drawing:n,feeds:i.feedsOf(y,_),diagnostics:le},fe=To(w.metrics)?void 0:w.metrics;iQ(v,{builtins:Hq(Object.keys(ue.builtins)),...Uq(ue.sources)}),iQ(v,Wq(ue.runs)),iQ(v,{factsSeq:String(ue.seq),prompts:String(fe?.messageCount??`-`),nonPrompts:String(fe?.nonPrompts??`-`),pr:tq(w.git),feeds:VZ(de.feeds)});let pe=[],me=f.of(y),{body:he,viewing:ge,geometry:_e,evaluated:ve,cellBreaks:ye,rules:be,idleSince:xe}=p.drawn(y,_,T.menuTimeout,e=>RZ(S,de,_,me,e,r.get(y,jS),c.to,e=>pe.push(e))),Se=oU(le),Ce=new Map(le.map((e,t)=>[Se[t],e.copy])),we=()=>a.delivered(y,n.by,Ce),Te=p.since(y,_);iQ(v,{menuIdle:Te===void 0?`-`:`${(_-Te).toFixed(1)}s/${T.menuTimeout}s`});let Ee=u.drawn(y,n.by,ce,pe),De=d.gitProvider.getStats(),Oe=d.usageStore.getStats(),ke=me.lastFrame(),Ae=ke.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,je=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,Me=e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`file-events`:return`${e.kind}:${e.state}`;case`domain`:return`domain:${e.key}`;case`load`:case`facts`:case`config-watch`:case`lifeline`:case`launch-pipes`:case`when`:return e.kind}},Ne=[...se,...pe].map(Me).join(`,`)||`-`;return iQ(v,{git:`${De.size}/${De.hits}h/${De.misses}m`,usage:`${Oe.size}/${Oe.hits}h/${Oe.misses}m`,effect:ke.effect,effectT:ke.t.toFixed(3),speed:`${ke.speed}x`,effectRows:`${ke.made}made/${ke.reused}reused`,effectOwn:Ae,fadeBasis:ke.basis,stateRev:String(ke.revision),fades:je(ke.fades),leaves:je(ke.leaves),motion:he.motion,evaluated:String(ve),cellBreaks:String(ye),pending:he.pending.join(`,`)||`-`,rules:[...be].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:A.length>0?`Y`:`N`,clickError:D.map(({hold:e})=>e).join(`,`)||`-`,pipeEvent:ae?.hold??`-`,upd:String(te.length),ask:String(O.length),warn:Ne,diag:String(le.length),warnRecord:Ee?`new`:`kept`,viewer:ge===null?`-`:`${ge.index}/${le.length}p${ge.page+1}`}),{drawn:{body:he,viewerOpen:ge!==null,diagnostics:le,geometry:_e},evaluated:ve,cellBreaks:ye,answersClick:QZ(D),pipeShown:oe,delivered:we,lanes:ee,idleSince:xe,handed:de}}const KQ=({key:e,held:t,admits:n})=>({kind:`domain`,key:e,message:`"${e}" holds ${JSON.stringify(t)}, which this config does not admit (it admits ${n}), so the bar ignores it and draws as if nothing were picked`}),qQ=e=>e.kind===`domain`?`${e.kind}\0${e.key}`:e.kind;function JQ(e,t){let{laneSetups:n,tmuxStatusLines:r}=e,i=BQ(e,t.requested,t.sessionId,Mc(t.hints.tmux));return r.observe(t.sessionId,t.pane,i.tmuxStatus),n.noted(t.sessionId,i)}function YQ(e,t,n){return kQ(e.recorder,t.view,n,()=>GQ(e,t,el))}function XQ(e){return{sessionId:e.hookData.session_id,hints:e.hints,origin:e.requested,transcript:e.hookData.transcript_path,answered:xF(e.hookData)}}function ZQ(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);return s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,cl(s.hints,t,e.heldSession),r.tmuxStatus),a.clicked(t,n,r)}async function QQ(e,t,n,r,i){try{var a=Oo();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(HQ(e,t,n,i)),u=DQ(e.recorder,l.view,n),d=o.monotonic(),f=r-d;iQ(i,{deadline:`${t.deadline.kind}:${Math.round(f)}ms`});let p=await Nj(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)}: ${O(e)}`),o.after),m=o.monotonic();iQ(i,{waited:`${Math.round(m-d)}ms`,ended:p,refreshed:lq(u.refreshed)});let{drawn:h,answersClick:g,pipeShown:_,delivered:v,lanes:y}=YQ(e,l,u.arrival),b=t.sessionId,x=nQ(y,s.following(b)),S=SF(t.hints.client??null)===`statusline`,C=FQ[t.encoding](S?$Q(e.links.to,b,h,x):h.body);return iQ(i,{handoff:(S?x:[]).join(`,`)||`-`,drew:`${Qe(o,m)}ms`}),{resp:C,motion:h.body.motion,answersClick:g,pipeShown:_,delivered:v}}catch(e){a.e=e}finally{a.d()}}function $Q(e,t,n,r){let[i,...a]=r;return i===void 0||n.viewerOpen?n.body:rF(n.body,vU(rQ(e,t,[i,...a]),n.diagnostics,e,t,n.geometry))}const e$=/^─{20,}/,t$=/^❯(\s|$)/,n$=/›\s*stashed$/;function r$(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>e$.test(e)?[t]:[]).at(-2);return n===void 0||!t$.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function i$(e){if(e.inMode)return{kind:`in-mode`};let t=r$(e);return t===null?{kind:`no-prompt`}:n$.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function a$(e){return/^❯\s*\S/u.test(r$(e)?.prompt??``)}const o$=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function s$(e){return e.screen.some(e=>o$.test(e))}const c$={"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 l$(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 u$(e,t,n){let r=i$(await e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:c$[r.kind]};let i=await e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}async function d$(e,t,n,r,i){let a=await sc(e,t,n,r,i);if(a.kind===`failed`)throw Error(a.reason);return a}async function f$(e,t){let n=await d$(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 p$(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 m$(e,t,n){let r=await d$(e,t,`claude-input.type`,p$(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 h$(e){return{read:t=>f$(e,t),type:(t,n)=>m$(e,t,n)}}const g$={launch:({what:e})=>`launch:${e}`,"type-slash":({line:e})=>`type-slash:${e}`,"apply-update":()=>`apply-update`,run:({run:e})=>`run:${e.action}`,"lane-setup":({lane:e,on:t})=>`lane-setup:${e}-${t?`on`:`off`}`,doctor:({step:e})=>`doctor:${e.kind}`};function _$(e){let t=g$[e.kind];return t(e)}const v$=`render-origin`,y$=`client-hints`,b$=(e,t)=>Ze(e,t)>10*1e3;function x$(e,t,n,r){e.delete(n),e.set(n,r),e.size>t&&e.delete(e.keys().next().value)}var S$=class{processes=new Map;constructor(e){this.turns=e}record(e,t,n){if(this.turns.inTurn()===null)throw Error(`mismatch runs: a write of ${JSON.stringify(e)} outside any turn`);switch(t.kind){case`runs`:{let r=sl(t.claude),i=this.processes.get(r)?.confirmed;return x$(this.processes,64,r,{confirmed:i?.sessionId===e?i:{sessionId:e,since:n},runs:new Map}),null}case`unconfirmed`:return null;case`mismatched`:{let r=sl(t.claude),i=this.processes.get(r)??{confirmed:null,runs:new Map};x$(this.processes,64,r,i);let a=i.confirmed;if(a?.sessionId===t.held&&!b$(a.since,n))return i.runs.delete(e),null;let o=Math.min(i.runs.get(e)?.since??n,n),s={since:o,lasted:b$(o,n)};return x$(i.runs,4,e,s),s}}}of(e,t){return t.kind===`unconfirmed`?null:this.processes.get(sl(t.claude))?.runs.get(e)??null}lasted(e,t){return this.of(e,t)?.lasted??!1}};const C$=(e,t)=>e===null?`-`:`${e.lasted?`lasted `:``}${Ze(e.since,t)}ms`;function w$(e,t){return{get:(n,r)=>{let i=e.get(n,r);return i===null||t(n)?.verdict(r,i).kind===`foreign`?null:i},revision:t=>e.revision(t)}}function T$(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?Gy:Ky;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const E$=Object.entries(bx),D$=new Set(Sx.map(e=>e.sessionKey)),O$=()=>!1;function k$(e,t){return cJ(e,e=>D$.has(e)?t(e):null,O$)}const A$=[`preset`,`theme`];function j$(e,t,n){let r=new Set(A$.slice(0,n).map(e=>bx[e].sessionKey));return cJ(e,e=>r.has(e)?t(e):null,O$)}function M$(e,t){let n=Array.from({length:A$.length+1},(n,r)=>j$(e,t,r));return e=>{let t=A$.indexOf(e);return n[t===-1?A$.length:t]}}function N$(e,t,n,r){return e.flatMap(([e,i])=>{let a=T$(t,e);return a===null||a===T$(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function P$(e,t,n){return T$(k$(e,t),n)}function F$(e,t){let n=k$(e,t);return N$(E$,n,M$(e,t),t=>I$(e,n.preset,t.configKey))}function I$(e,t,n){return n in(iS(e.presets,t).globals??{})?BN(t,n):n}function L$(e,t,n){let r=rS(t(bx.preset.sessionKey),e.globals.preset,e.presets),i=VN(n);return{key:i?.scope===`globals`?I$(e,r,i.field):n,globals:cS(e,r)}}function R$(e,t){let{preset:n}=k$(e,t);return V$(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:Db(a,s);return c===void 0||Eb(c)===Eb(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function z$(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return nS(e.presets).flatMap(n=>{let i=V$(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 wb(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:Db(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const B$=new WeakMap;function V$(e,t){let n=B$.get(e)??new Map;B$.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...ob(aS(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Sb(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=k$(e,t);return{from:n.preset,globals:iS(e.presets,n.preset).globals??{},picks:N$(E$.filter(([e])=>e!==`preset`),n,M$(e,t),e=>e.configKey),placements:R$(e,t)}}function U$(e,t){return cJ({...e,globals:{palette:t},presets:{}},()=>null,O$)}function W$(e,t){let n=k$(e,t),r=T$(n,`theme`);if(r===null)return{kind:`rule`};let i=U$(e,r),a=cS(e,n.preset),o=Object.fromEntries(px.map(e=>[e,T$(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:px.some(e=>o[e]!==T$(i,e))}}function G$(e){return{sessionKeys:Sx.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...vN(e)?BK.map(t=>BN(t,e)):[],...zN(e)?gy().map(t=>RN(t,e)):[]]}}function K$(e){return new Set(Sx.map(e=>e.configKey).filter(t=>G$(t).fileKeys.some(t=>Y$(e,J$(t)))))}function q$(e,t,n){let r=F$(e,n),i=new Set(r.map(e=>e.configKey)),a=Dx(e=>i.has(bx[e].configKey)||t.has(bx[e].configKey)),o=W$(e,n);return{unsaved:r.length+R$(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function J$(e){let t=VN(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return HN(t)}function Y$(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&Y$(e[n],r)}function X$(e,t,n){let r=Ox.get(n);if(r!==void 0)return P$(e,t,r);for(let[,t]of vb(e))if(t.key===n)return t.default??null;return null}function Z$(e,t){let n=MN(e).get(t);return n===void 0?null:String(n)}const Q$={inside:()=>[],defaultOf:()=>ma,menus:[]},$$=e=>`${e.key}\0${e.member}`;function e1(e){let t=new Map,n=n=>{let r=`${n.name}\0${nb(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:tG(a,nb(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))??new Map;n.set($$(t),t),o.set($$(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($$(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 nS(e.presets))d(aS(e,t).node,[]);for(let t of Object.values(e.actions)){let e=Oa(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));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get($$(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),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const t1=new WeakMap;function n1(e){let t=t1.get(e);if(t!==void 0)return t;let n=e1(e);return t1.set(e,n),n}function r1(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 i1(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 a1(e,t,n,r){let i=t(e),a=(t,a,o)=>{let s=r1(n(t),e=>i.get(t,e),a);(0,X.runInAction)(()=>{o();for(let n of s)e.clear(t,n)}),s.length>0&&r(`close-nested: folded=${s.join(`,`)} (session=${t})`)},o=(t,n)=>a(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)=>o(e,[{key:t,value:n}]),setBatch:o,clear:(t,r)=>a(t,[{key:r,value:n(t).defaultOf(r)}],()=>e.clear(t,r))}}const o1=new Set([`1`,`true`]),s1=new Set([`0`,`false`,``]);function c1(e,t){let n=N1(e),r=n.scope===`segment-palette`?`string`:_x(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(o1.has(t))return`true`;if(s1.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function l1(e,t){try{return e.readFileSync(t)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function u1(e,t,n,r){try{if(n===null){e.rmSync(vr(e,t));return}Cr(e,t,n)}catch(e){let n=`config write failed (${t}): ${e.message}`;throw r(`error`,n),Error(n)}}function d1(e){return/^\s*$/.test(e)?null:Fa(e)}function f1(e,t){return e!==null&&La(e,t)!==void 0}function p1(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(p1),...i}}return e}function m1(e){if(!Hx(e))return p1(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,p1(t)])),...n}}const h1=LK,g1=h1.segments,_1=h1.presets,v1=h1.root;function y1(e,t,n,r){if(!f1(e,t)&&n===void 0)throw new R(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function b1(e,t){let n=HN(t);return t.scope===`segment-palette`&&y1(e,[`segments`,t.segment],g1[t.segment],n.join(`.`)),n}function x1(e){return Fa(Ga(e))}function S1(){return Object.entries(v1.rows).map(([e,t])=>{let n=p1(t);return{path:[`root`],fragment:x1({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function C1(e,t){let n=e===null?void 0:La(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function w1(e,t){if(t===void 0)return null;let n=m1(t);return{path:e,fragment:x1(n),unit:{path:e,value:n}}}function T1(e,t){let n=[`presets`,t],r=[...n,`root`],i=_1[t];y1(e,n,i,r.join(`.`));let a=C1(e,r)??w1(r,i?.root);return a!==null&&fo(a.fragment)?a:null}function E1(e,t){let n=uo(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 D1(e,t){return[...S1(),C1(e,[`root`]),T1(e,t)].filter(e=>e!==null).reduce(E1,new Map)}function O1(e,t,n){for(let{node:r,...i}of D1(e,t).values())if(mo(r,n))return i;throw new R(`${k1(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 k1(e,t){return T1(e,t)?.path??[`root`]}function A1(e,t){return t.scope===`preset-root`?k1(e,t.preset):HN(t)}function j1(e,{unit:t}){return t===null?e:io(e,t.path,Ga(t.value),Ua)}function M1(e){let t=VN(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function N1(e){let t=M1(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function P1(e,t,n,r,i){let a=K1(t,r),o,s=()=>(o??={chain:z1(t,n)}).chain;q1(t,s,a),i(t,s,a),u1(t.disk,t.path,r,e.logger),e.record(t.path,n,r)}function F1(e,t,n){let r=R1(e,t(),n);if(r.length>0)throw new R(`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 I1=()=>{};function L1(e,t){try{return t()}catch(t){throw!(t instanceof R)||e.above.length===0?t:new R(`${t.message} — or it is declared by ${e.above.map(e=>e.path).join(`, `)}, which the bar does not edit`)}}function R1(e,t,n){if(t===null)return[];let r=new Set(W1(U1(t),U1(n)));return W1(H1(e,t),H1(e,n)).filter(e=>!r.has(e))}function z1(e,t){try{return B1(e,t)}catch(e){if(e instanceof kb)return null;throw e}}function B1(e,t){return pK(t===null?e.disk:V1(e.disk,e.path,t),e.memo,e.locs,t===null?e.above:[RH(e.path),...e.above],zK,{warned:()=>{}},{repo:e.repo,cwd:e.cwd})}function V1(e,t,n){return{readFileSync:r=>r===t?n:e.readFileSync(r),readdirSync:t=>e.readdirSync(t),statSync:t=>e.statSync(t),lstatSync:t=>e.lstatSync(t),realpathSync:t=>e.realpathSync(t)}}function H1(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function U1(e){return e.layers.at(-1)?.config??e.base}function W1(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=>W1(e[r],t[r],n===``?r:`${n}.${r}`))}function G1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function K1(e,t){try{return B1(e,t)}catch(e){throw e instanceof kb?new R(`refused: the config file would not load after this click — ${e.message}`):e}}function q1(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 R(`refused: this click would leave a placement of a segment nothing declares — ${o.map(({file:e,issue:t})=>new kb(e,[t]).message).join(`
209
+ `)}`)}function J1(e,t){let n=N1(t),r=d1(l1(e.disk,e.path)??``),i=r===null?void 0:La(r,HN(n));return i!==void 0&&`value`in i?i.value:void 0}function Y1(e,t,n){X1(e,t,n,[])}function X1(e,t,n,r){let i=l1(t.disk,t.path),a=n.reduce((e,[t,n])=>io(e,b1(d1(e),N1(t)),c1(t,n),Ua),i??``);P1(e,t,i,L1(t,()=>Z1(a,t.path,r,e=>e)),F1)}function Z1(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=O1(d1(s),n,i),l=vo(j1(s,c),c.path,i,a,Ga(o));if(l===null)throw new R(`${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 Q1(e,t,n){let r=d1(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of D1(r,t)){if(!mo(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?za(e,c):Ga(s.value);if(a!==`#`)return io(e,[...i,`rows`,a],l,Ua);if(T1(r,t)!==null)throw new R(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return io(e,i,l,Ua)}return e}function $1(e,t){return oo(e,t,t[0]===`presets`&&t.length>2&&!VK(t[1])?2:0)}function e0(e,t,n){let r=n.map(M1),i=l1(t.disk,t.path);if(i===null)return;let a=r.reduce((e,t)=>$1(e,A1(d1(e),t)),i);a!==i&&P1(e,t,i,a,I1)}function t0(e){let t=e===null?void 0:La(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function n0(e,t){let n=new Set([...BK,...t0(e),...t.above.flatMap(e=>Object.keys(Na.default.parse(t.disk.readFileSync(e.path)).presets??{}))].map(MM));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(MM(e)))}function r0(e,t,n,r,i,a){let o=l1(t.disk,t.path),s=d1(o??``),c=n0(s,t),l=[`presets`,c],u=L1(t,()=>T1(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?za(o??``,u.fragment):Ga(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Ga(r)]]],f=i.map(([e,t])=>{let n=BN(c,e);return[b1(s,N1(n)),c1(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>io(e,t,n,Ua),io(o??``,l,`{}`,Ua));return P1(e,t,o,L1(t,()=>Z1(p,t.path,a.map(e=>({...e,preset:c})),Q1)),F1),c}function i0(e,t,n,r){let i=l1(t.disk,t.path);P1(e,t,i,io(i??``,[`themeDefaults`,n],Ga(r),Ua),F1)}function a0(e,t,n){if(VK(n))throw new R(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=l1(t.disk,t.path),a=d1(i??``);if(i===null||a===null||La(a,r)===void 0)throw new R(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=La(a,[`globals`,`preset`]);P1(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>$1(e,t),i),I1)}function o0(e,t,n,r){let i=M1(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=l1(t.disk,t.path),o=r.op===`remove`?r.target:r.anchor,s=L1(t,()=>O1(d1(a??``),i.preset,o)),c=j1(a??``,s),{after:l,placed:u}=s0(c,s.path,r,()=>{let e=K1(t,c).config;return nS(e.presets).map(t=>aS(e,t).node)});if(l===null)throw new R(`${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 P1(e,t,a,l,F1),u}function s0(e,t,n,r){switch(n.op){case`remove`:return{after:go(e,t,n.target),placed:null};case`insert`:{let i=GR(n.segment,n.anchor,r());return{after:_o(e,t,i,n.anchor,n.relation),placed:i}}}}const c0={inTurn:()=>`single-run`};function l0(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 u0={load:()=>({}),save:()=>{},flush:()=>{}};var d0=class{sessions;storage;head=0;atom=(0,X.createAtom)(`SessionState`);constructor(e,t=u0,n=256){this.turns=e,this.maxSessions=n,this.storage=t,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){this.held(e),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.held(e),this.commit(e,e=>{e.values.delete(t)&&(e.revision=++this.head)})}restore(e,t,n){this.held(e),(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,X.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()})}held(e){if(this.turns.inTurn()===null)throw Error(`session state: a write of ${JSON.stringify(e)} outside any turn`)}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=u0}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 f0(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 p0(e,t){return _0(e.dir,t)??m0(e,t)}function m0(e,t){let n=e.onDisk(e.dir);for(let r of h0(t)){let i=g0(n,e.onDisk(r));if(i!==null)return s.join(i,s.relative(r,t))}return null}function h0(e){let t=s.dirname(e);return t===e?[]:[t,...h0(t)]}function g0(e,t){let n=s.relative(e,t);return n===`..`||n.startsWith(`..${s.sep}`)||s.isAbsolute(n)?null:n}function _0(e,t){let n=g0(e,t);return n===``?null:n}function v0(e,t){let n=p0(e,t);return n===null?{kind:`world`,path:t}:{kind:`home`,path:n}}var y0=class extends Error{};function b0(e,t){if(typeof t==`string`){if(!s.isAbsolute(t))throw new y0(`an older build's stored path ${JSON.stringify(t)} is not absolute`);return x0(e,t)}if(typeof t!=`object`||!t)throw new y0(`stored path is not an object: ${JSON.stringify(t)}`);let{kind:n,path:r}=t;if(typeof r!=`string`)throw new y0(`stored path has no path: ${JSON.stringify(t)}`);if(n===`home`){let t=s.join(e.dir,r);if(s.isAbsolute(r)||_0(e.dir,t)!==r)throw new y0(`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 y0(`stored world path ${JSON.stringify(r)} is not absolute`);if(_0(e.dir,r)!==null)throw new y0(`stored world path ${r} lies under the home's root ${e.dir}; a home's file is stored relative to it`);return x0(e,r)}throw new y0(`stored path has no kind of home or world: ${JSON.stringify(t)}`)}function x0(e,t){let n=p0(e,t);return n===null?t:s.join(e.dir,n)}const S0={load:()=>({}),save:()=>{}},C0=new Set(Sx.map(e=>e.sessionKey)),w0=e=>C0.has(e)||e.startsWith(eP),T0=8*1024*1024,E0={past:[],future:[]},D0=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var O0=class{held=X.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,X.runInAction)(()=>this.held.replace(e))}constructor(e,t,n,r=S0){this.disk=e,this.sessionState=t,this.logger=n,this.storage=r,this.state=new Map(Object.entries(r.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??E0;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??E0}begin(){let e=new Map,t=!1,n=(n,r)=>{t=!0;let i=e.get(n)??new Map,a=i.get(D0(r));i.set(D0(r),a===void 0?r:{...r,before:a.before}),e.set(n,i)},r=new Map;return{sessionState:l0(this.sessionState,()=>!0,(e,i,a,o)=>{if(t=!0,!(!w0(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:I0(i,r),o=n.get(e),s=o===void 0?a:B0(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 R(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,R0(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new R(`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(D0)),a=n.net.filter(e=>!i.has(D0(e))),o=j0(V0(z0(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new R(`rewind: ${r.map(U0).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 R(`redo: nothing to redo`);let a=[...n,i],o=j0(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...N0(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(D0)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:V0(n,t),future:V0(i,t),...a!==void 0&&{savepoint:{at:V0([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(D0(e))),below:V0(a.below,t)}}}),new R(`${r}: ${o.map(U0).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):l1(this.disk,t.file)}write(e,t,n){t.kind===`file`?u1(this.disk,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||k0(n)>T0;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,A0(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${T0} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function k0(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 A0({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...N0(n,1,[])}:{past:e,future:t.slice(1),...N0(n,0,[])}}function j0(e){return e.slice(-50)}const M0=e=>e===nP.member;function N0(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:P0(e.net,n),below:e.below}}}function P0(e,t){let n=new Map(e.map(e=>[D0(e),e]));for(let e of t){let t=n.get(D0(e));n.set(D0(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const F0=e=>e.map(e=>({...e,before:e.after,after:e.before}));function I0(e,t){let n=[...e.past,t],r=j0(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...N0(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...L0(e.future,a),...i.below]},n.length-r.length,t)}}function L0(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function R0(e,t){return{past:e.past.slice(0,-1),future:j0([...e.future,t]),...N0(e.savepoint,0,F0(t))}}function z0(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...L0(r,t.at-i.length),...t.below]}function B0(e,t){if(M0(t.after)&&!M0(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!M0(t.after)&&M0(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function V0(e,t){return e.map(e=>e.filter(e=>!t.has(D0(e)))).filter(e=>e.length>0)}function H0(e){return e.map(U0).join(`, `)}function U0(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function W0(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 G0(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(W0))}function K0(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(W0)&&G0(t.below)}function q0(e){if(typeof e!=`object`||!e)return!1;let t=e;return G0(t.past)&&G0(t.future)&&(t.savepoint===void 0||K0(t.savepoint))}function J0(e,t){let n=e=>e.kind===`file`||w0(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 X0(e,t,n,r){return{load:()=>{let i;try{i=e.readFileSync(t)}catch(e){let t=e.code;return t!==`ENOENT`&&r(`warn`,`settings-history read failed (${t}); starting empty`),{}}let a;try{a=JSON.parse(i)}catch{a=null}if(typeof a!=`object`||!a||Array.isArray(a)||!Object.values(a).every(q0))return r(`warn`,`settings-history load: unexpected shape, starting empty`),{};let o=f0(n),s;try{s=Object.entries(a).map(([e,t])=>[e,Y0(t,(t,n)=>{try{return b0(o,t)}catch(t){throw t instanceof y0?new y0(`session ${e}'s ${n}: ${t.message}`):t}})])}catch(e){if(!(e instanceof y0))throw e;return r(`warn`,`settings-history load: ${e.message}; starting empty`),{}}let c=new Set,l=Object.fromEntries(s.map(([e,t])=>[e,J0(t,c)]));return c.size>0&&r(`warn`,`settings-history load: dropped the changes to ${[...c].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),l},save:i=>{let a=f0(n),o=Object.fromEntries(Object.entries(i).map(([e,t])=>[e,Y0(t,e=>v0(a,e))]));try{Cr(e,t,JSON.stringify(o),384)}catch(e){let t=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw r(`error`,t),Error(t)}}}}const Z0=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function Q0(e){return{...Object.fromEntries(Z0.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 $0=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function e2(e){let t=e=>({kind:`failed`,reason:e});if(!$0(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!$0(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!FF.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${FF.join(` or `)}`)}return{kind:`ok`,value:e}}function t2(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const n2=(e,t)=>Ez(e,t,`doctor-marks.json`,{},e2),r2=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},i2=(e,t)=>e.includes(t)?e:[...e,t],a2=(e,t)=>Ez(e,t,`doctor-clicked-terminals.json`,[],r2);var o2=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const s2=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},c2=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),l2=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=c2(e,t);return r===void 0?n:r.projectDir},u2=(e,t)=>c2(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function d2(e){let t=new Map;for(let n of e.split(`
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*f2(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 p2={pullRequests:e=>Bq(e).has(`pr`),rateLimits:e=>[...e].some(e=>PU(`block`,e)||PU(`weekly`,e))};function m2(e,t){let n=new Map;for(let r of ob(aS(e,t).node)){if(r.kind!==`segment`)continue;let e=n.get(r.name)??[];r.when&&e.push(r.when),n.set(r.name,e)}let r=[...n.keys()].filter(t=>_b(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,RU(e,t,n.get(t))])),a=e=>r.filter(t=>p2[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}const h2=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function g2(e){if(typeof e==`string`)return h2.exec(e)?.[1]}function _2(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 v2(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 y2(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=_2(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`?g2(v2(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 b2(e,t){return e===void 0?[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>v(e)):[e]}async function x2(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await S2(No(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function S2(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function C2(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await No(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 zo(t,void 0,void 0);if(s.kind!==`ok`){Pe(`Failed to check agent file ${t}`);continue}i=j2(i,t,s.value);let c=O2(Bo(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){Pe(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function w2(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(E2(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=v2(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||T2.test(r)?`claude-code`:`prompt`}const T2=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function E2(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function D2(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=w2(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:y2(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 O2(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 k2(e){let t=O2(e);if(t.kind===`unparsed`)return Pe(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return D2(t.value)}catch(e){return Pe(`Failed to project JSONL line: ${e}`),null}}function A2(e){let t=[];for(let n of e.split(`
211
211
  `)){let e=k2(n);e&&t.push(e)}return t}function j2(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function M2(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function N2(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await zo(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=j2(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=r(o,Bo(c,e=>A2(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return F({folded:{cursor:a,value:o},longLines:i})}}
212
212
  /*!
213
213
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -490,25 +490,25 @@ function run(argv) {
490
490
  `)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
491
491
  `)){let t=O2(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function U4(e){let t=Wo(e,IF+1);return t.kind===`ok`?F(H4(t.value.buf,t.value.fromStart)):t}function W4(e,t){if(t.kind===`failed`)return t;let n=new Map;for(let{path:e,answered:r}of t.value)n.set(e,r||(n.get(e)??!1));return{kind:`ok`,value:[...n].map(([t,n])=>({path:t,answered:n,read:e.transcript(t)}))}}const G4={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};async function K4(e,t,n){if(yc(t,n)===void 0)return{kind:`ok`,value:null};let r=aW(await e.launch({bin:`git`,args:[...iW],cwd:n,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(r.kind===`failed`)return r;let i=uW(r.value);if(i===null)return{kind:`ok`,value:null};let a=rW(i);if(a===null)return{kind:`ok`,value:null};let o=QU[a],s=G4[a],c=s.loginHost(nW(i)),l=await e.launch({bin:o,args:[...s.args(c)],cwd:n,timeoutMs:2e3,category:`doctor.forge`});return q4(o,c,s.nonZero,l)}function q4(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):$U(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:YU(r.stderr)}):{kind:`failed`,reason:JU(e,r)}}function J4(e,t){let n={layers:e.layers,target:t,warnings:e.warning===null?[]:e.warning.split(`
492
492
  `),repos:e.repos};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const Y4=e=>E4(()=>uee(e));function X4(e,t){let n=e=>JSON.stringify([e.managedDir,e.projectDir,e.userFile]),r=n(e),i=[],a=new Map;for(let o of t){let t={managedDir:e.managedDir,projectDir:o.projectDir,userFile:Jo(o.claudeConfigDir)},s=n(t);if(s===r)i.push(o);else{let e=a.get(s)??{at:t,bars:[]};e.bars.push(o),a.set(s,e)}}let o=(e,t)=>({at:e,sources:Y4(e),bars:t.map(({role:e,frame:t})=>({role:e,frame:t}))});return{origin:o(e,i),elsewhere:[...a.values()].map(({at:e,bars:t})=>o(e,t))}}async function Z4(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:await e.probeTmux(t)}}function Q4(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:nre(t),tmuxClient:null};case`inside`:{if(e.client.kind===`failed`)return{kind:`unasked`,reason:e.client.reason};let t=e.client.value;return t===null?{kind:`unasked`,reason:`tmux has no client attached to the pane's session`}:{kind:`seen`,identified:tre(t),tmuxClient:t}}}}async function $4(e,t,n,r){if(t.kind!==`seen`)return t;let{identified:i,tmuxClient:a}=t,o=n.terminalEnv;if(i.kind!==`known`)return i;let{name:s,version:c}=i.terminal;if(Xne(s))return{kind:`bundling`,name:s,version:c};if(!Zne(s))return{kind:`unread`,name:s,version:c};let{ITERM_PROFILE:l,...u}=o??{},d=a===null?{kind:`ok`,value:n.ssh===!0}:await e.remoteLogin(a.pid);return{kind:`configured`,name:s,version:c,font:d.kind===`failed`?{kind:`failed`,reason:`whether the terminal is remote could not be asked: ${d.reason}`}:d.value?{kind:`failed`,reason:`the terminal is on the far side of a remote login, so its font is on the machine it runs on`}:await e.fontInUse({name:s,version:c},a===null?o??{}:u,r)}}function e3(e){switch(e.via){case`link`:return{kind:`arrived`,delivery:e.delivery};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}async function t3(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:await t()}}async function n3(e,t,n,r){return{pullRequests:await t3(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:await t3(t.rateLimits,()=>r)}}function r3(e,t){let n=t.find(e=>e.role===`statusline`);return n===void 0?{kind:`failed`,reason:`the daemon holds no statusline render of session ${e} — none since it started, or dropped for newer sessions' renders, or only a frames display draws it, which reports no width — so no width a statusline client measured is known; run this again once the statusline has redrawn`}:{kind:`ok`,value:{columns:n.termCols,of:{kind:`session`,sessionId:e}}}}async function i3(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=cJ(d.config,r,()=>!1),p=await Z4(e,t.tmux),m=Q4(p,t.terminalEnv),h=[...new Set([...Vne(f),...vF(JSON.stringify(d.config))])].join(``),[g,_,v]=await Promise.all([h===``?{kind:`none`}:$4(e,m,t,h).then(e=>({kind:`glyphs`,glyphs:h,terminal:e})),e.daemons(),n3(e,m2(d.config,f.preset),n,a)]);return{tmux:p,width:l,terminal:m,nerdFont:g,marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:_,read:u.postMortemsRead},config:J4(d,n.target),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:v,transcripts:W4(e,o),claudeSettings:X4({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Jo(qo(t.claudeConfigDir,e.home))},c.kind===`ok`?c.value:[])}}function a3(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;wr(e,io(Zo(e),t.path,JSON.stringify(t.value),Wa));let r=e=>({...e,sources:Y4(e.at)}),{origin:i,elsewhere:a}=n.claudeSettings;return{kind:`ok`,value:{...n,claudeSettings:{origin:r(i),elsewhere:a.map(r)}}}}case`post-mortems-read`:{let r=e.postMortemsRead.update(e=>e.through===null||Fi(t.through,e.through)?{through:t.through}:e);return r.kind===`failed`?r:{kind:`ok`,value:{...n,daemon:{...n.daemon,read:r}}}}default:return t}}const o3={entries:0,held:0,refreshes:{},failures:0,abandoned:0,lastMs:null},s3=16384;var c3=class e{startedAt;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;constructor(e){this.clock=e,this.startedAt=new Date(e.now())}firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;dirWatchesOpened=0;dirWatchesClosed=0;subprocessTotal=0;subprocessInFlight=0;subprocessDraining=0;subprocessDrainedBytes=0;subprocessDrainsCut=0;subprocessPipeErrors=0;subprocessRefusals=new Map;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;get subprocessRefused(){return this.subprocessRefusals}launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)},onRefused:e=>{this.subprocessRefusals.set(e,(this.subprocessRefusals.get(e)??0)+1)},onDrainOpen:()=>{this.subprocessDraining++},onDrainRead:(e,t)=>{this.subprocessDrainedBytes+=t},onDrainClose:(e,t)=>{this.subprocessDraining--,t===`cut`&&this.subprocessDrainsCut++},onPipeError:()=>{this.subprocessPipeErrors++}};recordRollingNow(){let e=this.clock.monotonic();if(this.rollingTimestamps.length<s3){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%s3}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=this.clock.monotonic()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,refused:Object.fromEntries(this.subprocessRefused),draining:this.subprocessDraining,drainedBytes:this.subprocessDrainedBytes,drainsCut:this.subprocessDrainsCut,pipeErrors:this.subprocessPipeErrors,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e({now:()=>0,monotonic:()=>0}).snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},fileEvents:{delivery:{kind:`delivering`,unreported:[],missedSince:null},stalls:0,catchUps:0,probes:0,probeFailures:0},sourceRuns:{shell:o3,file:o3,watches:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0},journalTurns:{gathers:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0,queued:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},linkIds:{minted:0,reused:0,evicted:0,reservations:0,faults:0},watchersActive:0,dirWatchesActive:0,dirsPolled:0,handlerProbes:[],clients:[],bundle:`/`,sourceDigest:null,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:Rn,sourceDigest:e.sourceDigest,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((this.clock.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,fileEvents:e.fileEvents,sourceRuns:e.sourceRuns,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,journalTurns:e.journalTurns,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,linkIds:e.linkIds,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors,dirs:{active:e.dirWatchesActive,opened:this.dirWatchesOpened,closed:this.dirWatchesClosed},polled:e.dirsPolled},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};const l3={connectMs:200,budgetMs:500};async function u3(e,t){return d3(await f3(e),t.includes(`--json`))}function d3(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`daemon-stats: ${ui(e)}\n`,code:1};let n=t?JSON.stringify(e.value,null,2)+`
493
- `:null,r=p3(e.value);return r===null?{stdout:n??w3(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function f3(e){return ri(e,()=>({kind:`stats`}),l3,e=>`stats`in e?e.stats:void 0)}function p3(e,t=_3){let n=c3.referenceSnapshot(),r=v3(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let{theirs:i,mine:a}=h3(e);return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}function m3(e){return e.version===`1.212.1`&&g3(e)===Vn()?null:h3(e)}function h3(e){return{theirs:b3(e.version,g3(e)),mine:b3(Rn,Vn())}}const g3=e=>e.sourceDigest??null,_3=Object.keys(c3.referenceSnapshot());function v3(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!y3(e))return[];if(!y3(t))return[n||`<snapshot>`];if(`kind`in e)return[];let r=[];for(let i of Object.keys(e)){let a=n===``?i:`${n}.${i}`;i in t?r.push(...v3(e[i],t[i],a)):r.push(a)}return r}function y3(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function b3(e,t){return`${e} [${t===null?`no digest`:Ln(t)}]`}function x3(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function S3(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function C3(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${e%60}s`:`${Math.floor(e/3600)}h${Math.floor(e%3600/60)}m`}function w3(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${b3(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${C3(e.uptimeSec)}`),t.push(` rss ${x3(e.rssBytes)}`),t.push(` heapUsed ${x3(e.heapUsedBytes)}`),t.push(` heapTotal ${x3(e.heapTotalBytes)}`),t.push(` external ${x3(e.externalBytes)}`),t.push(` arrayBuffers ${x3(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(` unknownFields ${e.unknownHookFields.map(e=>JSON.stringify(e)).join(`, `)||`-`}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${S3(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` changes ${e.gitCache.changes}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${S3(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`sources`);for(let n of e.sources.records){let e=Object.entries(n.refreshes).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` ${`${n.scope}/${n.name}`.padEnd(24)} failures=${n.failures} last=${n.lastMs===null?`-`:`${n.lastMs}ms`} refreshes ${e}`)}let n=Object.entries(e.sources.homes).map(([e,t])=>`${e}:${t}`).join(` `),r=Object.entries(e.sources.held).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` homes ${n}`),t.push(` held ${r}`);let i=e.sources.pluginStorage,a=Object.entries(i.faults).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` plugin storage folders=${i.folders} lost=${i.lost} faults ${a}`),t.push(` fileEvents ${Jc(e.fileEvents)}`);for(let n of[`shell`,`file`]){let r=e.sourceRuns[n];t.push(` runs.${n.padEnd(8)} entries=${r.entries} held=${r.held} failures=${r.failures} abandoned=${r.abandoned} last=${r.lastMs===null?`-`:`${r.lastMs}ms`}`)}t.push(` runs.watches ${e.sourceRuns.watches}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${x3(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${x3(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` views ${e.renderCache.views}`),t.push(` pinned ${e.renderCache.pinned}`),t.push(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${x3(e.renderCache.accountedBytes)} / ${x3(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`menuIdle`),t.push(` sessions ${e.menuIdle.sessions}`),t.push(` armed ${e.menuIdle.armed}`),t.push(``),t.push(`journalTurns`),t.push(` gathers ${e.journalTurns.gathers}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` refused ${e.watchers.refused}`),t.push(` errors ${e.watchers.errors}`),t.push(` dirs ${e.watchers.dirs.active} open (${e.watchers.dirs.opened} opened, ${e.watchers.dirs.closed} closed)`,` polled ${e.watchers.polled} dirs`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`),t.push(` draining ${e.subprocesses.draining} (${e.subprocesses.drainedBytes} bytes dropped, ${e.subprocesses.drainsCut} cut)`),t.push(` pipeErrors ${e.subprocesses.pipeErrors}`);let o=Object.entries(e.subprocesses.byCategory),s=Object.entries(e.subprocesses.refused).map(([e,t])=>[`${e} refused`,t]),c=[...o,...s].reduce((e,[t])=>Math.max(e,t.length),13);for(let[n,r]of o){let i=e.subprocesses.p50DurationMs[n],a=e.subprocesses.p99DurationMs[n],o=i!==void 0&&a!==void 0?` (p50 ${i}ms · p99 ${a}ms)`:``;t.push(` ${n.padEnd(c)} ${r}${o}`)}for(let[e,n]of s)t.push(` ${e.padEnd(c)} ${n}`);return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
493
+ `:null,r=p3(e.value);return r===null?{stdout:n??w3(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function f3(e){return ri(e,()=>({kind:`stats`}),l3,e=>`stats`in e?e.stats:void 0)}function p3(e,t=_3){let n=c3.referenceSnapshot(),r=v3(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let{theirs:i,mine:a}=h3(e);return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}function m3(e){return e.version===`1.212.2`&&g3(e)===Vn()?null:h3(e)}function h3(e){return{theirs:b3(e.version,g3(e)),mine:b3(Rn,Vn())}}const g3=e=>e.sourceDigest??null,_3=Object.keys(c3.referenceSnapshot());function v3(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!y3(e))return[];if(!y3(t))return[n||`<snapshot>`];if(`kind`in e)return[];let r=[];for(let i of Object.keys(e)){let a=n===``?i:`${n}.${i}`;i in t?r.push(...v3(e[i],t[i],a)):r.push(a)}return r}function y3(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function b3(e,t){return`${e} [${t===null?`no digest`:Ln(t)}]`}function x3(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function S3(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function C3(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${e%60}s`:`${Math.floor(e/3600)}h${Math.floor(e%3600/60)}m`}function w3(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${b3(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${C3(e.uptimeSec)}`),t.push(` rss ${x3(e.rssBytes)}`),t.push(` heapUsed ${x3(e.heapUsedBytes)}`),t.push(` heapTotal ${x3(e.heapTotalBytes)}`),t.push(` external ${x3(e.externalBytes)}`),t.push(` arrayBuffers ${x3(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(` unknownFields ${e.unknownHookFields.map(e=>JSON.stringify(e)).join(`, `)||`-`}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${S3(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` changes ${e.gitCache.changes}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${S3(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`sources`);for(let n of e.sources.records){let e=Object.entries(n.refreshes).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` ${`${n.scope}/${n.name}`.padEnd(24)} failures=${n.failures} last=${n.lastMs===null?`-`:`${n.lastMs}ms`} refreshes ${e}`)}let n=Object.entries(e.sources.homes).map(([e,t])=>`${e}:${t}`).join(` `),r=Object.entries(e.sources.held).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` homes ${n}`),t.push(` held ${r}`);let i=e.sources.pluginStorage,a=Object.entries(i.faults).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` plugin storage folders=${i.folders} lost=${i.lost} faults ${a}`),t.push(` fileEvents ${Jc(e.fileEvents)}`);for(let n of[`shell`,`file`]){let r=e.sourceRuns[n];t.push(` runs.${n.padEnd(8)} entries=${r.entries} held=${r.held} failures=${r.failures} abandoned=${r.abandoned} last=${r.lastMs===null?`-`:`${r.lastMs}ms`}`)}t.push(` runs.watches ${e.sourceRuns.watches}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${x3(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${x3(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` views ${e.renderCache.views}`),t.push(` pinned ${e.renderCache.pinned}`),t.push(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${x3(e.renderCache.accountedBytes)} / ${x3(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`menuIdle`),t.push(` sessions ${e.menuIdle.sessions}`),t.push(` armed ${e.menuIdle.armed}`),t.push(``),t.push(`journalTurns`),t.push(` gathers ${e.journalTurns.gathers}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` refused ${e.watchers.refused}`),t.push(` errors ${e.watchers.errors}`),t.push(` dirs ${e.watchers.dirs.active} open (${e.watchers.dirs.opened} opened, ${e.watchers.dirs.closed} closed)`,` polled ${e.watchers.polled} dirs`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`),t.push(` draining ${e.subprocesses.draining} (${e.subprocesses.drainedBytes} bytes dropped, ${e.subprocesses.drainsCut} cut)`),t.push(` pipeErrors ${e.subprocesses.pipeErrors}`);let o=Object.entries(e.subprocesses.byCategory),s=Object.entries(e.subprocesses.refused).map(([e,t])=>[`${e} refused`,t]),c=[...o,...s].reduce((e,[t])=>Math.max(e,t.length),13);for(let[n,r]of o){let i=e.subprocesses.p50DurationMs[n],a=e.subprocesses.p99DurationMs[n],o=i!==void 0&&a!==void 0?` (p50 ${i}ms · p99 ${a}ms)`:``;t.push(` ${n.padEnd(c)} ${r}${o}`)}for(let[e,n]of s)t.push(` ${e.padEnd(c)} ${n}`);return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
494
494
  `)+`
495
- `}const T3=e=>({kind:`ok`,value:e}),E3=e=>({kind:`failed`,reason:e});var D3=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const O3=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function k3(e){return O3.test(e)?e:null}function A3(e,t){let n=e.opener(t);if(n.kind===`failed`)return n;if(n.value===null)return T3(null);let r=n.value;return T3({app:r,forwarder:e.exists(vs(r))})}async function j3(e,t){let n=e.monotonic()+5e3;for(;e.monotonic()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,delivery:r.delivery}}return null}async function M3(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own}; the URL handler delivers a link naming ${e.name} to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=jte(e.name,n),i=e.open(r);return(i===null?await j3(e,n):null)??{kind:`lost`,unopened:i,opener:A3(e,r),otherBuild:t.value.otherBuild}}function N3(e,t,n,r){let i=e.launchSync({bin:n,args:[...r],category:t,timeoutMs:5e3});return i.ok?T3(i.stdout):E3(gt(i))}const P3=e=>`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString(${JSON.stringify(e)}));u.isNil() ? "" : u.path.js`;async function F3(e){let t=await f3(e);if(t.kind!==`ok`)return E3(ui(t).split(`
496
- `).join(` — `));let n=p3(t.value,[`handlerProbes`]);if(n!==null)return E3(n);let r=[];for(let e of t.value.handlerProbes){let t=I3(e);if(t===null)return E3(`the daemon lists its probe arrivals without who delivered them, so it is from a build before the forwarder app — restart it to run the installed one`);r.push(t)}return T3({arrivals:r,otherBuild:m3(t.value)})}function I3(e){if(typeof e!=`object`||!e)return null;let{nonce:t,delivery:n}=e;if(typeof t!=`string`||typeof n!=`object`||!n)return null;let{kind:r,urlV:i}=n;return r===`cli`?{nonce:t,delivery:{kind:`cli`}}:r===`forwarder`&&typeof i==`number`?{nonce:t,delivery:{kind:`forwarder`,urlV:i}}:null}function L3(e,t){let{home:n,clock:r}=t;return{platform:process.platform,name:n.name,sockets:{own:$n(n),handler:er(n.name)},monotonic:()=>r.monotonic(),nonce:ce,daemon:()=>F3(t),open:t=>{let n=N3(e,`doctor.open`,`/usr/bin/open`,[`-g`,t]);return n.kind===`ok`?null:n.reason},pause:()=>et(r,100),opener:t=>{let n=N3(e,`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,P3(t)]);if(n.kind===`failed`)return n;let r=n.value.trim();return T3(r===``?null:r)},exists:m.existsSync}}const R3=5e3;function z3(e,t,n){if(e.reason===`rate-limited`){n(`warn`,gt(e));return}throw e.reason===`aborted`?new uc(t):Error(`${t} failed (${gt(e)})`)}async function B3(e,t,n,r,i,a){let o=x(s.join(a,`cc-candybar-handoff-`));try{let a={stdout:`/dev/null`,stderr:s.join(o,`stderr`),status:s.join(o,`status`)},c=e.launchJobSync(t,a);if(!c.ok){z3({...c,stdout:``,stderr:``,exitCode:null,signal:null},n,r);return}c.release();let l=e.clock.monotonic()+i;for(;;){let o=e.jobGroupAlive(c.pid),s=qt(a.status);if(s!==null){if(s.kind===`exit`&&s.code===0)return;z3(s.kind===`exit`?{ok:!1,reason:`non-zero`,stdout:``,stderr:C(a.stderr,`utf8`),exitCode:s.code,signal:null}:{ok:!1,reason:`timeout`,stdout:``,stderr:``,exitCode:null,signal:null},n,r);return}if(!o)throw Error(`${n} failed (lost): the opener ended with no verdict`);if(e.clock.monotonic()>=l){r(`info`,`${t.category} handed off at ${i}ms, pid ${c.pid}`);return}await et(e.clock,50)}}finally{T(o,{recursive:!0,force:!0,maxRetries:3})}}function V3(e,t){H3(t,{bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`)}function H3(e,t,n){e.effect({kind:`launch`,spec:t,what:n})}const U3=(e,[t=``],n)=>{V3(t,n)},W3=new Set([`request`,`feed`]);function G3(e){if(!W3.has(e))throw new R(`unknown renderer ${JSON.stringify(e)}`);return e}const K3=(e,t,n)=>{let[r=``,i=``]=t,a=n.diagnosticCopy(e,G3(r),i);if(a===void 0)throw new R(`that message is no longer listed in session ${e}'s diagnostics — open ⚠ again and copy from there`);V3(a,n)},q3=(e,[t=``],n)=>{H3(n,{bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,t],category:`click.open`},`open -a "Visual Studio Code"`)},J3=(e,t,n)=>{c6(n,n.navigating).get(e,`toolbar-expanded`)?n.navigating.clear(e,`toolbar-expanded`):n.navigating.set(e,`toolbar-expanded`,`1`)},Y3=(e,t,n)=>{let r=n.gates.state.gateFor(s6(n,e));if(t.length===0)throw new R(`set-state: <key>/<value> is required (have keys: ${r.listKeys().join(`, `)})`);if(t.length%2!=0)throw new R(`set-state: expected even-count <key>/<value> pairs, got ${t.length} segment(s) after session id (have keys: ${r.listKeys().join(`, `)})`);let i=[];for(let e=0;e<t.length;e+=2){let n=t[e],a=t[e+1];if(!n)throw new R(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let o=r.validate(n,a);if(!o.ok)throw new R(`set-state: pair ${e/2+1}: ${o.reason}`);i.push({key:n,value:o.value})}$3(n,e,`set-state`,i),n.navigating.setBatch(e,i);let a=i.map(e=>`${e.key}=${e.value}`).join(` `);n.log(`info`,`set-state: ${a} (session=${e})`)},X3=/^-?\d+$/;function Z3(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const Q3=(e,t,n)=>{let[r=``,i=``]=t;if(!r)throw new R(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!X3.test(i))throw new R(`step-state: delta must be an integer, got "${i}"`);let a=parseInt(i,10),o=s6(n,e),s=n.gates.state.gateFor(o),c=s.rangeParamsFor(r);if(!c)throw new R(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${s.listKeys().join(`, `)})`);let l=l6(n,e),u=l(r),d=u===null?t6(`step-state`,r,c,X$(o,l,r)):parseInt(u,10),f=Z3(d,a,c.min,c.max),p=s.validate(r,String(f));if(!p.ok)throw new R(`step-state: ${p.reason}`);$3(n,e,`step-state`,[{key:r,value:p.value}]),n.navigating.set(e,r,p.value),n.log(`info`,`step-state: ${r} ${d}→${p.value} (by ${a}, session=${e})`)};function $3(e,t,n,r){let i=r.filter(e=>e.key.startsWith(eP));if(i.length===0)return;let a=z$(s6(e,t),l6(e,t),i);if(a.length>0)throw new R(`${n}: refused — ${a.join(`; `)}`)}function e6(e,t){return Math.max(e.min,Math.min(e.max,t))}function t6(e,t,n,r){if(r===null)return n.min;if(!X3.test(r))throw new R(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return e6(n,parseInt(r,10))}function n6(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function r6(e,t){let n;try{n=JSON.parse(e)}catch{throw new R(`render origin is not JSON: ${e}`)}if(typeof n!=`object`||!n)throw new R(`render origin is not an object: ${e}`);let{projectDir:r,cwd:i,configFile:a,source:o}=n;if(typeof r!=`string`||typeof i!=`string`||a===void 0)throw new R(`render origin has the wrong shape: ${e}`);let s;try{s=a===null?null:b0(t,a)}catch(e){throw e instanceof y0?new R(`render origin: ${e.message}`):e}return{projectDir:r,cwd:i,target:n6(o,s)}}function i6(e,t){let n=a6(e,t);if(n===null)throw new R(`session ${t} has not rendered yet — no config to act on`);return n}function a6(e,t){let n=e.sessionState.get(t,v$);return n===null?null:r6(n,e.storedRoot)}function o6(e,t,n){let r=a6(e,t);if(r===null)return;let{path:i}=f6(e,r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function s6(e,t){return e.configFor(i6(e,t))}function c6(e,t){return w$(t,t=>{let n=a6(e,t);return n===null?null:e.gates.state.gateFor(e.configFor(n))})}function l6(e,t){let n=c6(e,e.sessionState);return e=>n.get(t,e)}function u6(e,t){let n=a6(e,t);if(n===null)return null;let r=()=>e.lanes.of(n,t);return{sessionId:t,before:r(),read:r}}function d6(e,t){let n=a6(e,t);return n===null?Q$:n1(e.configFor(n))}function f6(e,t){return UH(e.filesystem,e.installedLayers,e.locations,ZH(e.filesystem,e.stateDir),t.projectDir,t.cwd,t.target.path)}function p6(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.log}}const m6=(e,t,n)=>{let[r=``,i=``]=t,a=i6(n,e),o=n.configFor(a),s=n.gates.config.gateFor(o);if(!r)throw new R(`set-config: <key>/<value> is required (have keys: ${s.listKeys().join(`, `)})`);let c=s.validate(r,i);if(!c.ok)throw new R(`set-config: ${c.reason}`);let l=f6(n,a),u=L$(o,l6(n,e),r);Y1(p6(n,e),l,[[u.key,c.value]]),n.reloadConfig(a),n.log(`info`,`set-config: ${u.key}=${c.value} → ${l.path} (session=${e})`)},h6=(e,t,n)=>{let[r=``,i=``]=t;if(!r)throw new R(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!X3.test(i))throw new R(`step-config: delta must be an integer, got "${i}"`);let a=parseInt(i,10),o=i6(n,e),s=n.configFor(o),c=n.gates.config.gateFor(s),l=c.rangeParamsFor(r);if(!l)throw new R(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${c.listKeys().join(`, `)})`);let u=f6(n,o),d=L$(s,l6(n,e),r),f=J1(u,d.key),p=typeof f==`number`?e6(l,f):t6(`step-config`,r,l,Z$(d.globals,r)),m=Z3(p,a,l.min,l.max),h=c.validate(r,String(m));if(!h.ok)throw new R(`step-config: ${h.reason}`);Y1(p6(n,e),u,[[d.key,h.value]]),n.reloadConfig(o),n.log(`info`,`step-config: ${d.key} ${p}→${h.value} (by ${a}) → ${u.path} (session=${e})`)},g6=(e,t,n)=>{let r=i6(n,e),i=n.configFor(r),a=l6(n,e),o=F$(i,a),s=R$(i,a);if(o.length+s.length===0){n.log(`info`,`save: nothing unsaved (session=${e})`);return}let c=n.gates.state.gateFor(i),l=o.map(e=>{let t=c.validate(e.sessionKey,e.value);if(!t.ok)throw new R(`save: ${t.reason}`);return[e.target,t.value]});v6(`save`,c,s);let u=f6(n,r);X1(p6(n,e),u,l,s),n.reloadConfig(r);for(let t of[...o.map(e=>e.sessionKey),...s.map(e=>e.key)])n.sessionState.clear(e,t);n.log(`info`,`save: ${[...l.map(([e,t])=>`${e}=${t}`),...s.map(_6)].join(` `)} → ${u.path} (session=${e})`)},_6=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Db(e.value)}`;function v6(e,t,n){for(let r of n){let n=t.validate(r.key,Db(r.value));if(!n.ok)throw new R(`${e}: ${n.reason}`)}}const y6=(e,t,n)=>{let r=i6(n,e),i=n.configFor(r),a=H$(i,l6(n,e)),o=n.gates.state.gateFor(i),s=a.picks.map(e=>{let t=o.validate(e.sessionKey,e.value);if(!t.ok)throw new R(`save-preset: ${t.reason}`);return[e.configKey,t.value]});v6(`save-preset`,o,a.placements);let c=f6(n,r),l=r0(p6(n,e),c,a.from,a.globals,s,a.placements);n.reloadConfig(r);for(let t of[...Cx.map(e=>e.sessionKey),...a.placements.map(e=>e.key)])n.sessionState.clear(e,t);n.sessionState.set(e,xx.preset.sessionKey,l),n.log(`info`,`save-preset: ${[`${l} from=${a.from}`,...s.map(([e,t])=>`${e}=${t}`),...a.placements.map(_6)].join(` `)} → ${c.path} (session=${e})`)},b6=(e,t,n)=>{let r=i6(n,e),i=W$(n.configFor(r),l6(n,e));if(i.kind===`rule`)throw new R(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let a=f6(n,r);i0(p6(n,e),a,i.theme,i.look),n.reloadConfig(r);let o=new Set(F$(n.configFor(r),t=>n.sessionState.get(e,t)).map(e=>e.sessionKey)),s=mx.map(e=>xx[e].sessionKey).filter(e=>!o.has(e));for(let t of s)n.sessionState.clear(e,t);n.log(`info`,`save-theme-default: ${i.theme} ${mx.map(e=>`${e}=${i.look[e]}`).join(` `)} → ${a.path} (session=${e})`)},x6=(e,t,n)=>{let[r=``]=t;if(!r)throw new R(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let i=i6(n,e),a=f6(n,i);a0(p6(n,e),a,r),n.reloadConfig(i);let o=xx.preset.sessionKey;n.sessionState.get(e,o)===r&&n.sessionState.clear(e,o),n.log(`info`,`delete-preset: ${r} ← ${a.path} (session=${e})`)},S6=(e,t,n)=>{let r=t,i=i6(n,e),a=n.gates.config.gateFor(n.configFor(i)).listKeys(),o=r.length===0?[``]:r.filter(e=>!a.includes(e));if(o.length>0)throw new R(`reset-config: unknown config key "${o.join(`", "`)}" (have: ${a.join(`, `)})`);let s=f6(n,i),c=r.map(G$),l=c.flatMap(e=>e.fileKeys),u=c.flatMap(e=>e.sessionKeys);e0(p6(n,e),s,l),n.reloadConfig(i);for(let t of u)n.sessionState.clear(e,t);n.log(`info`,`reset-config: ${[...l,...u.map(e=>`session:${e}`)].join(` `)} ← ${s.path} (session=${e})`)};function C6(e,t){let n=(e,t)=>[...sb(oS(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(rS(t.presets).flatMap(e=>n(t,e).map(t=>tP(MM(e),rb(t)))));return rS(e.presets).flatMap(t=>n(e,t).map(e=>({member:tP(MM(t),rb(e)),node:e})).filter(({member:e})=>!r.has(e)))}function w6(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[ZN]:[]])}const T6=(e,t,n)=>{let[r=``,i=``]=t,a=i6(n,e),o=n.configFor(a),s=n.gates.config.gateFor(o);if(!r)throw new R(`apply-layout-op: <key>/<op> is required (have: ${s.listKeys().join(`, `)})`);let c=s.validate(r,i);if(!c.ok)throw new R(`apply-layout-op: ${c.reason}`);let l=WR(c.value);if(l===null)throw new R(`apply-layout-op: "${c.value}" is not a layout op token`);let u=f6(n,a),d=o0(p6(n,e),u,r,l);n.reloadConfig(a);let f=w6(C6(o,n.configFor(a)),n.sessionState.get(e,ZN)).filter(t=>n.sessionState.get(e,t)!==null);for(let t of f)n.sessionState.clear(e,t);n.log(`info`,`apply-layout-op: ${r} ${c.value} → ${u.path} placed=${JSON.stringify(d)} released=${JSON.stringify(f)} (session=${e})`)},E6=(e,t,n)=>{n.journal.commit();let r=n.history.undo(e);n.journal.wrote(),o6(n,e,r),n.log(`info`,`undo: restored ${H0(r)} (session=${e})`)},D6=(e,t,n)=>{let{step:r,discarded:i}=n.navigation.back(e,n.sessionState,n.gates.state.gateFor(s6(n,e))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);n.log(`info`,`back: ${a} discarded=${i} (session=${e})`)},O6=(e,t,n)=>{n.journal.commit(),n.journal.wrote();let r=n.history.rewind(e);o6(n,e,r),n.log(`info`,`rewind: put back ${H0(r)||`nothing`} as edit mode found it (session=${e})`)},k6=(e,t,n)=>{n.journal.commit();let r=n.history.redo(e);n.journal.wrote(),o6(n,e,r),n.log(`info`,`redo: re-applied ${H0(r)} (session=${e})`)},A6=(e,t,n)=>{n.effect({kind:`apply-update`})};function j6(e,t){let n=e.sessionState.get(t,y$);if(n===null)throw new R(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new R(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new R(`client hints record is not an object: ${n}`);return Nr(r)}function M6(e,t,n){let r=tI(n);e.sessionState.setBatch(t,Zre(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${Rre(n.config)} ${Yre(n.nerdFont,n.marks)} ${zre(n.terminal,n.clicked)} ${Bre(n.terminal,n.width)} ${Vre(n.install)} ${Ure(n.daemon)} ${Wre(n.data)} ${Jre(n.transcripts)} ${Gre(n.frames,n.claudeSettings)} ${qre(n.claudeSettings.origin.sources)} (session=${t})`)}function N6(e,t,n){e.effect({kind:`doctor`,session:t,step:n,arrival:e.arrival})}function P6(e,t){let n=e=>{throw Error(`doctor: the gather ${e}; a gather writes nothing`)};return{get:(n,r)=>{let i=e.get(n,r);return t.set(JSON.stringify([n,r]),{what:r,value:i,again:e=>e.get(n,r)}),i},values:()=>n(`read every key; a gather reads keys by name`),revision:t=>e.revision(t),set:(e,t)=>n(`set ${t}`),setBatch:()=>n(`wrote a batch`),clear:(e,t)=>n(`cleared ${t}`)}}function F6(e,t,n){for(let{what:t,value:r,again:i}of n.reads)if(i(e.sessionState)!==r)return t;let r=e.doctor.loadConfig(i6(e,t));return r.config===n.load.config&&r.error===n.load.error&&r.warning===n.load.warning&&I6(r.repos,n.load.repos)?null:`config`}const I6=(e,t)=>BP(e).join(`
495
+ `}const T3=e=>({kind:`ok`,value:e}),E3=e=>({kind:`failed`,reason:e});var D3=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const O3=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function k3(e){return O3.test(e)?e:null}function A3(e,t){let n=e.opener(t);if(n.kind===`failed`)return n;if(n.value===null)return T3(null);let r=n.value;return T3({app:r,forwarder:e.exists(vs(r))})}async function j3(e,t){let n=e.monotonic()+5e3;for(;e.monotonic()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,delivery:r.delivery}}return null}async function M3(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own}; the URL handler delivers a link naming ${e.name} to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=Mte(e.name,n),i=e.open(r);return(i===null?await j3(e,n):null)??{kind:`lost`,unopened:i,opener:A3(e,r),otherBuild:t.value.otherBuild}}function N3(e,t,n,r){let i=e.launchSync({bin:n,args:[...r],category:t,timeoutMs:5e3});return i.ok?T3(i.stdout):E3(gt(i))}const P3=e=>`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString(${JSON.stringify(e)}));u.isNil() ? "" : u.path.js`;async function F3(e){let t=await f3(e);if(t.kind!==`ok`)return E3(ui(t).split(`
496
+ `).join(` — `));let n=p3(t.value,[`handlerProbes`]);if(n!==null)return E3(n);let r=[];for(let e of t.value.handlerProbes){let t=I3(e);if(t===null)return E3(`the daemon lists its probe arrivals without who delivered them, so it is from a build before the forwarder app — restart it to run the installed one`);r.push(t)}return T3({arrivals:r,otherBuild:m3(t.value)})}function I3(e){if(typeof e!=`object`||!e)return null;let{nonce:t,delivery:n}=e;if(typeof t!=`string`||typeof n!=`object`||!n)return null;let{kind:r,urlV:i}=n;return r===`cli`?{nonce:t,delivery:{kind:`cli`}}:r===`forwarder`&&typeof i==`number`?{nonce:t,delivery:{kind:`forwarder`,urlV:i}}:null}function L3(e,t){let{home:n,clock:r}=t;return{platform:process.platform,name:n.name,sockets:{own:$n(n),handler:er(n.name)},monotonic:()=>r.monotonic(),nonce:ce,daemon:()=>F3(t),open:t=>{let n=N3(e,`doctor.open`,`/usr/bin/open`,[`-g`,t]);return n.kind===`ok`?null:n.reason},pause:()=>et(r,100),opener:t=>{let n=N3(e,`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,P3(t)]);if(n.kind===`failed`)return n;let r=n.value.trim();return T3(r===``?null:r)},exists:m.existsSync}}const R3=5e3;function z3(e,t,n){if(e.reason===`rate-limited`){n(`warn`,gt(e));return}throw e.reason===`aborted`?new uc(t):Error(`${t} failed (${gt(e)})`)}async function B3(e,t,n,r,i,a){let o=x(s.join(a,`cc-candybar-handoff-`));try{let a={stdout:`/dev/null`,stderr:s.join(o,`stderr`),status:s.join(o,`status`)},c=e.launchJobSync(t,a);if(!c.ok){z3({...c,stdout:``,stderr:``,exitCode:null,signal:null},n,r);return}c.release();let l=e.clock.monotonic()+i;for(;;){let o=e.jobGroupAlive(c.pid),s=qt(a.status);if(s!==null){if(s.kind===`exit`&&s.code===0)return;z3(s.kind===`exit`?{ok:!1,reason:`non-zero`,stdout:``,stderr:C(a.stderr,`utf8`),exitCode:s.code,signal:null}:{ok:!1,reason:`timeout`,stdout:``,stderr:``,exitCode:null,signal:null},n,r);return}if(!o)throw Error(`${n} failed (lost): the opener ended with no verdict`);if(e.clock.monotonic()>=l){r(`info`,`${t.category} handed off at ${i}ms, pid ${c.pid}`);return}await et(e.clock,50)}}finally{T(o,{recursive:!0,force:!0,maxRetries:3})}}function V3(e,t){H3(t,{bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`)}function H3(e,t,n){e.effect({kind:`launch`,spec:t,what:n})}const U3=(e,[t=``],n)=>{V3(t,n)},W3=new Set([`request`,`feed`]);function G3(e){if(!W3.has(e))throw new R(`unknown renderer ${JSON.stringify(e)}`);return e}const K3=(e,t,n)=>{let[r=``,i=``]=t,a=n.diagnosticCopy(e,G3(r),i);if(a===void 0)throw new R(`that message is no longer listed in session ${e}'s diagnostics — open ⚠ again and copy from there`);V3(a,n)},q3=(e,[t=``],n)=>{H3(n,{bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,t],category:`click.open`},`open -a "Visual Studio Code"`)},J3=(e,t,n)=>{c6(n,n.navigating).get(e,`toolbar-expanded`)?n.navigating.clear(e,`toolbar-expanded`):n.navigating.set(e,`toolbar-expanded`,`1`)},Y3=(e,t,n)=>{let r=n.gates.state.gateFor(s6(n,e));if(t.length===0)throw new R(`set-state: <key>/<value> is required (have keys: ${r.listKeys().join(`, `)})`);if(t.length%2!=0)throw new R(`set-state: expected even-count <key>/<value> pairs, got ${t.length} segment(s) after session id (have keys: ${r.listKeys().join(`, `)})`);let i=[];for(let e=0;e<t.length;e+=2){let n=t[e],a=t[e+1];if(!n)throw new R(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let o=r.validate(n,a);if(!o.ok)throw new R(`set-state: pair ${e/2+1}: ${o.reason}`);i.push({key:n,value:o.value})}$3(n,e,`set-state`,i),n.navigating.setBatch(e,i);let a=i.map(e=>`${e.key}=${e.value}`).join(` `);n.log(`info`,`set-state: ${a} (session=${e})`)},X3=/^-?\d+$/;function Z3(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const Q3=(e,t,n)=>{let[r=``,i=``]=t;if(!r)throw new R(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!X3.test(i))throw new R(`step-state: delta must be an integer, got "${i}"`);let a=parseInt(i,10),o=s6(n,e),s=n.gates.state.gateFor(o),c=s.rangeParamsFor(r);if(!c)throw new R(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${s.listKeys().join(`, `)})`);let l=l6(n,e),u=l(r),d=u===null?t6(`step-state`,r,c,X$(o,l,r)):parseInt(u,10),f=Z3(d,a,c.min,c.max),p=s.validate(r,String(f));if(!p.ok)throw new R(`step-state: ${p.reason}`);$3(n,e,`step-state`,[{key:r,value:p.value}]),n.navigating.set(e,r,p.value),n.log(`info`,`step-state: ${r} ${d}→${p.value} (by ${a}, session=${e})`)};function $3(e,t,n,r){let i=r.filter(e=>e.key.startsWith(eP));if(i.length===0)return;let a=z$(s6(e,t),l6(e,t),i);if(a.length>0)throw new R(`${n}: refused — ${a.join(`; `)}`)}function e6(e,t){return Math.max(e.min,Math.min(e.max,t))}function t6(e,t,n,r){if(r===null)return n.min;if(!X3.test(r))throw new R(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return e6(n,parseInt(r,10))}function n6(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function r6(e,t){let n;try{n=JSON.parse(e)}catch{throw new R(`render origin is not JSON: ${e}`)}if(typeof n!=`object`||!n)throw new R(`render origin is not an object: ${e}`);let{projectDir:r,cwd:i,configFile:a,source:o}=n;if(typeof r!=`string`||typeof i!=`string`||a===void 0)throw new R(`render origin has the wrong shape: ${e}`);let s;try{s=a===null?null:b0(t,a)}catch(e){throw e instanceof y0?new R(`render origin: ${e.message}`):e}return{projectDir:r,cwd:i,target:n6(o,s)}}function i6(e,t){let n=a6(e,t);if(n===null)throw new R(`session ${t} has not rendered yet — no config to act on`);return n}function a6(e,t){let n=e.sessionState.get(t,v$);return n===null?null:r6(n,e.storedRoot)}function o6(e,t,n){let r=a6(e,t);if(r===null)return;let{path:i}=f6(e,r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function s6(e,t){return e.configFor(i6(e,t))}function c6(e,t){return w$(t,t=>{let n=a6(e,t);return n===null?null:e.gates.state.gateFor(e.configFor(n))})}function l6(e,t){let n=c6(e,e.sessionState);return e=>n.get(t,e)}function u6(e,t){let n=a6(e,t);if(n===null)return null;let r=()=>e.lanes.of(n,t);return{sessionId:t,before:r(),read:r}}function d6(e,t){let n=a6(e,t);return n===null?Q$:n1(e.configFor(n))}function f6(e,t){return UH(e.filesystem,e.installedLayers,e.locations,ZH(e.filesystem,e.stateDir),t.projectDir,t.cwd,t.target.path)}function p6(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.log}}const m6=(e,t,n)=>{let[r=``,i=``]=t,a=i6(n,e),o=n.configFor(a),s=n.gates.config.gateFor(o);if(!r)throw new R(`set-config: <key>/<value> is required (have keys: ${s.listKeys().join(`, `)})`);let c=s.validate(r,i);if(!c.ok)throw new R(`set-config: ${c.reason}`);let l=f6(n,a),u=L$(o,l6(n,e),r);Y1(p6(n,e),l,[[u.key,c.value]]),n.reloadConfig(a),n.log(`info`,`set-config: ${u.key}=${c.value} → ${l.path} (session=${e})`)},h6=(e,t,n)=>{let[r=``,i=``]=t;if(!r)throw new R(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!X3.test(i))throw new R(`step-config: delta must be an integer, got "${i}"`);let a=parseInt(i,10),o=i6(n,e),s=n.configFor(o),c=n.gates.config.gateFor(s),l=c.rangeParamsFor(r);if(!l)throw new R(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${c.listKeys().join(`, `)})`);let u=f6(n,o),d=L$(s,l6(n,e),r),f=J1(u,d.key),p=typeof f==`number`?e6(l,f):t6(`step-config`,r,l,Z$(d.globals,r)),m=Z3(p,a,l.min,l.max),h=c.validate(r,String(m));if(!h.ok)throw new R(`step-config: ${h.reason}`);Y1(p6(n,e),u,[[d.key,h.value]]),n.reloadConfig(o),n.log(`info`,`step-config: ${d.key} ${p}→${h.value} (by ${a}) → ${u.path} (session=${e})`)},g6=(e,t,n)=>{let r=i6(n,e),i=n.configFor(r),a=l6(n,e),o=F$(i,a),s=R$(i,a);if(o.length+s.length===0){n.log(`info`,`save: nothing unsaved (session=${e})`);return}let c=n.gates.state.gateFor(i),l=o.map(e=>{let t=c.validate(e.sessionKey,e.value);if(!t.ok)throw new R(`save: ${t.reason}`);return[e.target,t.value]});v6(`save`,c,s);let u=f6(n,r);X1(p6(n,e),u,l,s),n.reloadConfig(r);for(let t of[...o.map(e=>e.sessionKey),...s.map(e=>e.key)])n.sessionState.clear(e,t);n.log(`info`,`save: ${[...l.map(([e,t])=>`${e}=${t}`),...s.map(_6)].join(` `)} → ${u.path} (session=${e})`)},_6=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Eb(e.value)}`;function v6(e,t,n){for(let r of n){let n=t.validate(r.key,Eb(r.value));if(!n.ok)throw new R(`${e}: ${n.reason}`)}}const y6=(e,t,n)=>{let r=i6(n,e),i=n.configFor(r),a=H$(i,l6(n,e)),o=n.gates.state.gateFor(i),s=a.picks.map(e=>{let t=o.validate(e.sessionKey,e.value);if(!t.ok)throw new R(`save-preset: ${t.reason}`);return[e.configKey,t.value]});v6(`save-preset`,o,a.placements);let c=f6(n,r),l=r0(p6(n,e),c,a.from,a.globals,s,a.placements);n.reloadConfig(r);for(let t of[...Sx.map(e=>e.sessionKey),...a.placements.map(e=>e.key)])n.sessionState.clear(e,t);n.sessionState.set(e,bx.preset.sessionKey,l),n.log(`info`,`save-preset: ${[`${l} from=${a.from}`,...s.map(([e,t])=>`${e}=${t}`),...a.placements.map(_6)].join(` `)} → ${c.path} (session=${e})`)},b6=(e,t,n)=>{let r=i6(n,e),i=W$(n.configFor(r),l6(n,e));if(i.kind===`rule`)throw new R(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let a=f6(n,r);i0(p6(n,e),a,i.theme,i.look),n.reloadConfig(r);let o=new Set(F$(n.configFor(r),t=>n.sessionState.get(e,t)).map(e=>e.sessionKey)),s=px.map(e=>bx[e].sessionKey).filter(e=>!o.has(e));for(let t of s)n.sessionState.clear(e,t);n.log(`info`,`save-theme-default: ${i.theme} ${px.map(e=>`${e}=${i.look[e]}`).join(` `)} → ${a.path} (session=${e})`)},x6=(e,t,n)=>{let[r=``]=t;if(!r)throw new R(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let i=i6(n,e),a=f6(n,i);a0(p6(n,e),a,r),n.reloadConfig(i);let o=bx.preset.sessionKey;n.sessionState.get(e,o)===r&&n.sessionState.clear(e,o),n.log(`info`,`delete-preset: ${r} ← ${a.path} (session=${e})`)},S6=(e,t,n)=>{let r=t,i=i6(n,e),a=n.gates.config.gateFor(n.configFor(i)).listKeys(),o=r.length===0?[``]:r.filter(e=>!a.includes(e));if(o.length>0)throw new R(`reset-config: unknown config key "${o.join(`", "`)}" (have: ${a.join(`, `)})`);let s=f6(n,i),c=r.map(G$),l=c.flatMap(e=>e.fileKeys),u=c.flatMap(e=>e.sessionKeys);e0(p6(n,e),s,l),n.reloadConfig(i);for(let t of u)n.sessionState.clear(e,t);n.log(`info`,`reset-config: ${[...l,...u.map(e=>`session:${e}`)].join(` `)} ← ${s.path} (session=${e})`)};function C6(e,t){let n=(e,t)=>[...ob(aS(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(nS(t.presets).flatMap(e=>n(t,e).map(t=>tP(MM(e),nb(t)))));return nS(e.presets).flatMap(t=>n(e,t).map(e=>({member:tP(MM(t),nb(e)),node:e})).filter(({member:e})=>!r.has(e)))}function w6(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[ZN]:[]])}const T6=(e,t,n)=>{let[r=``,i=``]=t,a=i6(n,e),o=n.configFor(a),s=n.gates.config.gateFor(o);if(!r)throw new R(`apply-layout-op: <key>/<op> is required (have: ${s.listKeys().join(`, `)})`);let c=s.validate(r,i);if(!c.ok)throw new R(`apply-layout-op: ${c.reason}`);let l=WR(c.value);if(l===null)throw new R(`apply-layout-op: "${c.value}" is not a layout op token`);let u=f6(n,a),d=o0(p6(n,e),u,r,l);n.reloadConfig(a);let f=w6(C6(o,n.configFor(a)),n.sessionState.get(e,ZN)).filter(t=>n.sessionState.get(e,t)!==null);for(let t of f)n.sessionState.clear(e,t);n.log(`info`,`apply-layout-op: ${r} ${c.value} → ${u.path} placed=${JSON.stringify(d)} released=${JSON.stringify(f)} (session=${e})`)},E6=(e,t,n)=>{n.journal.commit();let r=n.history.undo(e);n.journal.wrote(),o6(n,e,r),n.log(`info`,`undo: restored ${H0(r)} (session=${e})`)},D6=(e,t,n)=>{let{step:r,discarded:i}=n.navigation.back(e,n.sessionState,n.gates.state.gateFor(s6(n,e))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);n.log(`info`,`back: ${a} discarded=${i} (session=${e})`)},O6=(e,t,n)=>{n.journal.commit(),n.journal.wrote();let r=n.history.rewind(e);o6(n,e,r),n.log(`info`,`rewind: put back ${H0(r)||`nothing`} as edit mode found it (session=${e})`)},k6=(e,t,n)=>{n.journal.commit();let r=n.history.redo(e);n.journal.wrote(),o6(n,e,r),n.log(`info`,`redo: re-applied ${H0(r)} (session=${e})`)},A6=(e,t,n)=>{n.effect({kind:`apply-update`})};function j6(e,t){let n=e.sessionState.get(t,y$);if(n===null)throw new R(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new R(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new R(`client hints record is not an object: ${n}`);return Nr(r)}function M6(e,t,n){let r=tI(n);e.sessionState.setBatch(t,Zre(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${Rre(n.config)} ${Yre(n.nerdFont,n.marks)} ${zre(n.terminal,n.clicked)} ${Bre(n.terminal,n.width)} ${Vre(n.install)} ${Ure(n.daemon)} ${Wre(n.data)} ${Jre(n.transcripts)} ${Gre(n.frames,n.claudeSettings)} ${qre(n.claudeSettings.origin.sources)} (session=${t})`)}function N6(e,t,n){e.effect({kind:`doctor`,session:t,step:n,arrival:e.arrival})}function P6(e,t){let n=e=>{throw Error(`doctor: the gather ${e}; a gather writes nothing`)};return{get:(n,r)=>{let i=e.get(n,r);return t.set(JSON.stringify([n,r]),{what:r,value:i,again:e=>e.get(n,r)}),i},values:()=>n(`read every key; a gather reads keys by name`),revision:t=>e.revision(t),set:(e,t)=>n(`set ${t}`),setBatch:()=>n(`wrote a batch`),clear:(e,t)=>n(`cleared ${t}`)}}function F6(e,t,n){for(let{what:t,value:r,again:i}of n.reads)if(i(e.sessionState)!==r)return t;let r=e.doctor.loadConfig(i6(e,t));return r.config===n.load.config&&r.error===n.load.error&&r.warning===n.load.warning&&I6(r.repos,n.load.repos)?null:`config`}const I6=(e,t)=>BP(e).join(`
497
497
  `)===BP(t).join(`
498
- `);function L6(e,t){let{tmux:n,claudeConfigDir:r,terminalEnv:i,ssh:a}=j6({sessionState:e},t);return{tmux:n,claudeConfigDir:r,terminalEnv:i,ssh:a}}async function R6(e,t,n,r){let i=new Map,a={...e,sessionState:P6(e.sessionState,i)},o=e=>JSON.stringify(L6(e,t)),s=L6(e.sessionState,t);i.set(`hints`,{what:y$,value:JSON.stringify(s),again:o});let c=r.loadConfig(i6(a,t)),l={kind:`clicked`,sessionId:t,via:n.via},u=e.clients.ofSession(t,e.now()),d;try{d=await i3({...r,loadConfig:()=>c},s,i6(a,t),e=>a.sessionState.get(t,e),{kind:`ok`,value:e.serving()},{kind:`ok`,value:u.map(e=>e.rateLimits)},{kind:`ok`,value:u.map(e=>e.transcript)},l,{kind:`ok`,value:u2(l,u)},r3(t,u),A4(e.doctorStores))}catch(e){throw e instanceof o2?new R(e.message):e}return{facts:d,install:O4(r.install,e.bundle,u.map(e=>e.client)),stamp:{load:c,reads:[...i.values()]}}}async function z6(e,t){let n=j4(e.doctor),r=t.session;return e.journalTurns.gathering(async()=>{let i=await R6(e,r,t.arrival,n);return F6(e,r,i.stamp)===null?i:R6(e,r,t.arrival,n)})}function B6(e,t,n,{facts:r,install:i}){let a=A4(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:e3(n),install:i,clicked:V6(e,n,o)}}function V6(e,t,{terminal:n,clicked:r}){let i=n.kind===`seen`?jF(n.identified):null;if(i===null||t.via!==`link`)return r;try{return e.doctorStores.clicked.update(e=>i2(e,i))}catch(t){return e.log(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(i)}: ${t instanceof Error?t.message:String(t)}`),r}}const H6={run:(e,t,n,r)=>M6(e,t,r),fix:(e,t,{check:n},r)=>{let i=n.probe(r);if(i.ok||i.fix===void 0)throw new R(`doctor-fix: ${n.label} — ${i.ok?`nothing to fix`:i.reason}`);let a=a3(e.doctorStores,i.fix,r);if(a.kind===`failed`)throw new R(`doctor-fix: ${n.label} — ${a.reason}`);e.log(`info`,`doctor-fix: ${n.name} → ${cre(i.fix)} (session=${t})`),M6(e,t,a.value)},mark:(e,t,{check:n,mark:r},i)=>{let a=n.probe(i);if(a.ok||a.sighting===void 0)throw new R(`doctor-mark: ${n.label} — ${a.ok?`nothing to mark`:`shows nothing to look at`}`);let o=e.doctorStores.marks.update(e=>t2(e,n.name,a.sighting.id,r));if(o.kind===`failed`)throw new R(`doctor-mark: ${o.reason}`);e.log(`info`,`doctor-mark: ${n.name} ${r} on ${a.sighting.id} (session=${t})`),M6(e,t,{...i,marks:o})}};function U6(e,t,n){let r=t.session,i=F6(e,r,n.stamp);if(i!==null)throw new R(`doctor: the session's ${i} changed during the doctor's probes — click again`);W6(e,r,t.step,B6(e,r,t.arrival,n))}function W6(e,t,n,r){let i=H6[n.kind];i(e,t,n,r)}const G6=(e,t,n)=>{N6(n,e,{kind:`run`})},K6=(e,t)=>{if(!e.ok)throw new R(`probe: ${e.problem}`);let n=e.value;if(t.arrival.via!==`link`)throw new R(`probe: a probe arrives only as a link`);let{delivery:r}=t.arrival;t.probes.arrive({nonce:n,delivery:r}),t.log(`info`,`probe: arrived nonce=${n} delivery=${r.kind}`)},q6=(e,t,n)=>{let[r=``]=t,i=nI(r);if(i===void 0)throw new R(`doctor-fix: unknown check "${r}"`);N6(n,e,{kind:`fix`,check:i})},J6=(e,t,n)=>{let[r=``,i=``]=t,a=nI(r);if(a===void 0)throw new R(`doctor-mark: unknown check "${r}"`);if(!FF.includes(i))throw new R(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${FF.join(` or `)}`);N6(n,e,{kind:`mark`,check:a,mark:i})},Y6=(e,t,n)=>{let[r=``]=t,i=Object.values(n.configFor(i6(n,e)).actions).filter(e=>`slash`in e),a=i.find(e=>e.slash===r);if(a===void 0)throw new R(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(i.map(e=>e.slash))].join(`, `)||`none`})`);let o=l$(j6(n,e).tmux);if(o.kind===`refused`)throw new R(`${r} was not typed: ${o.reason}`);n.effect({kind:`type-slash`,pane:o.hint,line:a.slash})};function X6(e,[t=``,n=``,r=``],i){let a=i6(i,e),o=i.configFor(a).actions,s=Object.hasOwn(o,t)?o[t]:void 0;if(s===void 0||!(`run`in s))throw new R(`"${t}" is not a run action this session's config declares`);let c=vS(s);if(!i.links.signer.verify({sessionId:e,action:t,declaration:c,evaluated:n},r))throw new R(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let l;try{l=JSON.parse(n)}catch{throw new R(`run ${t}: what the link carries is not JSON`)}let[u,...d]=l.run;if(u===void 0||u===``)throw new R(`run ${t}: the program evaluated to nothing`);let f=i.sourcesFor(a);return{sessionId:e,action:t,argv:[u,...d],envOverlay:{...Q0({sessionId:e,projectDir:a.projectDir,claudeConfigDir:j6(i,e).claudeConfigDir}),...l.env},cwd:s.cwd??i.locations.homeDir,refreshes:s.refreshes.map(e=>({name:e,storage:f.get(e)}))}}const Z6=new Map([[LS,U3,[1,1]],[RS,q3,[1,1]],[FS,Y3,[0,1/0]],[IS,Q3,[2,2]],[BS,m6,[2,2]],[VS,h6,[2,2]],[KS,S6,[0,1/0]],[HS,g6,[0,0]],[US,y6,[0,0]],[WS,b6,[0,0]],[GS,x6,[1,1]],[qS,T6,[2,2]],[JS,E6,[0,0]],[YS,k6,[0,0]],[XS,D6,[0,0]],[ZS,O6,[0,0]],[zS,J3,[0,0]],[QS,A6,[0,0]],[$S,G6,[0,0]],[eC,q6,[1,1]],[tC,J6,[2,2]],[iC,Y6,[1,1]],[`run`,(e,t,n)=>{let r=X6(e,t,n);n.effect({kind:`run`,id:n.runs.superseded(r),run:r})},[3,3]],[aC,(e,t,n)=>{let[r=``,i=``,a=``]=t,o=i;if(!n.links.signer.verify(EU(e,r,o),a))throw new R(`the answer's signature does not match what it carries: it was not drawn by this daemon`);let s=TU(n.filesystem,n.stateDir,r,o);if(s.kind===`failed`)throw Error(`${r} was not ${o}: ${s.reason}`);n.journal.wrote();let{superseded:c,absent:l,unchecked:u}=s.value;n.log(`info`,`repo-config: ${r} ${o} superseded=${c.join(`,`)||`-`} absent=${l.join(`,`)||`-`} unchecked=${u.length===0?`-`:JSON.stringify(u)} (session=${e})`),n.reloadConfig(i6(n,e))},[3,3]],[oC,K3,[2,2]]].map(([e,t,n])=>[e,{handler:t,takes:n}]));new Set(Z6.keys());function Q6(e,t,n){let[r=``,...i]=n.split(`/`);return{verb:e,leaf:t,session:$6(r),args:fc(()=>i.map(decodeURIComponent))}}function $6(e){let t=fc(()=>decodeURIComponent(e));return t.ok?_Q(t.value):{ok:!1,problem:`has ${t.problem}`}}function e8({verb:e,value:t}){let n=Z6.get(e);return n===void 0?{verb:e,leaf:n}:Q6(e,n,t)}function t8(e){return e.find(e=>e.leaf!==void 0)?.session??null}function n8(e,t){return`${e}: ${t}`}function $re(e){return`unknown effect verb "${e}"`}function r8(e,t){return{kind:`refused`,reason:t,problem:n8(e,t)}}function eie(e){let t=$re(e);return{kind:`refused`,reason:t,problem:t}}function i8({verb:e},t,n){return{ok:!1,verb:e,args:t,refusal:r8(e,n)}}function tie(e,t){if(e.leaf===void 0)return{ok:!1,verb:e.verb,args:[],refusal:eie(e.verb)};let{verb:n,leaf:r,session:i,args:a}=e,o=a.ok?a.value:[];if(!i.ok)return i8(e,o,`session id ${i.problem}`);if(!t?.ok)return i8(e,o,`its click's own session is refused, so no step of it runs`);if(t.id!==i.id)return i8(e,o,`names session ${i.id}, not the session its click is in`);if(!a.ok)return i8(e,o,a.problem);let[s,c]=r.takes;return a.value.length<s||a.value.length>c?i8(e,o,`reads ${s===c?s:`${s} to ${c}`} after its session, and the link carries ${a.value.length}`):{ok:!0,verb:n,leaf:r,sid:i.id,args:a.value}}function nie(e){let t=fc(()=>decodeURIComponent(e));if(!t.ok)return t;let n=k3(t.value);return n===null?{ok:!1,problem:`the value is not a probe nonce`}:{ok:!0,value:n}}const rie={[PS]:e=>{let t=gC(mC(e)).map(e8),n=t8(t);return{kind:PS,steps:t.map(e=>tie(e,n)),session:n}},[nC]:e=>({kind:nC,nonce:nie(e)})};function iie(e,t){return wte(e)?rie[e](t):null}function a8(e){return e.kind===`dispatch`&&e.session?.ok?e.session.id:null}function aie(e,t){let n=[];try{e.leaf.handler(e.sid,e.args,{...t,effect:e=>void n.push(e)})}catch(t){let n=t instanceof Error?t.message:String(t);return t instanceof R?r8(e.verb,n):{kind:`failed`,problem:n8(e.verb,n)}}for(let e of n)t.effect(e);return{kind:`ran`}}const oie=new Map([[`run`,(e,{sid:t,args:[n],reason:r})=>e.runs.refused(t,n||`-`,r)]]);function sie(e,t,n){let r=[],i=!1;for(let a of e){let e=a.ok?aie(a,n):a.refusal;e.kind!==`ran`&&(e.kind===`refused`?oie.get(a.verb)?.(n,{sid:t?.ok?t.id:`-`,args:a.args,reason:e.reason}):i=!0,r.push(e.problem))}if(r.length>0){t?.ok&&qZ(n.sessionState,t.id,r.join(`
499
- `),n.now());let e=`dispatch: ${r.join(`; `)}`;throw i?Error(e):new R(e)}}function cie(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}function o8(e,t,n){let r=e===null?null:u6(t,e),i=t.history.begin(),a=t.navigation.begin(i.sessionState),o=[],s=e=>a1(e,e=>c6(t,e),e=>d6(t,e),e=>t.log(`info`,e)),c=[];try{n({...t,sessionState:s(i.sessionState),journal:i,navigating:s(a.sessionState),effect:e=>void c.push(e)})}catch(e){o.push(e)}for(let e of[a,i])try{e.commit()}catch(e){o.push(e)}if(r!==null)try{let e=r.read();c.push(...t.lanes.clicked(r.sessionId,i.written()?r.before:e,e))}catch(e){o.push(e)}t.described(c),cie(o)}function lie(e,t){if(t.gone())throw new dc(PS);let n=a8(e);t.journalTurns.take(PS,()=>o8(n,t,r=>{try{sie(e.steps,e.session,r)}finally{n!==null&&t.clickLanded(n)}}))}function uie(e,t){switch(e.kind){case PS:return lie(e,t);case nC:return K6(e.nonce,t);default:return e}}function die(e,t,n){n.journalTurns.take(`menu-idle`,()=>o8(e,n,n=>{if(!t.stillIdle()){n.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}t.closed();let r=c6(n,n.navigating),i=i1(d6(n,e),t=>r.get(e,t));n.navigating.setBatch(e,i.map(({key:e})=>({key:e,value:ma}))),n.log(`info`,`menu-idle: closed=${i.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)}))}const s8=[],fie={request:({req:e,arrived:t,facts:n},{verbCtx:r})=>{let i=r.journalTurns.take(`request`,()=>{hie(r.sessionState,e);let n=r.mismatchRuns.record(e.sessionId,e.pane,t);return{effects:r.lanes.arrived(e),revision:r.sessionState.revision(e.sessionId),mismatch:n}});return iQ(n,{revision:String(i.revision),effects:i.effects.map(e=>_$(e)).join(`,`)||`-`,mismatch:C$(i.mismatch,t)}),{answer:void 0,effects:i.effects,facts:[]}},click:({click:e,arrival:t,gone:n},{verbCtx:r})=>{let i=[],a=null;try{uie(e,{...r,arrival:t,gone:n,described:e=>void i.push(...e)})}catch(e){a={error:e}}return{answer:a,effects:i,facts:[]}},"menu-idle":({session:e,idle:t},{verbCtx:n})=>{let r=[];return die(e,t,{...n,described:e=>void r.push(...e)}),{answer:void 0,effects:r,facts:[]}},"effect-done":({of:e,done:t},n)=>{let{verbCtx:r}=n;return{answer:r.journalTurns.take(`effect-done`,()=>{let i=mie(t,n);return i.kind===`failed`&&e.session!==null&&qZ(r.sessionState,e.session,i.said,r.now()),i}),effects:s8,facts:[]}},answered:({session:e,errors:t},{verbCtx:n})=>(n.journalTurns.take(`answered`,()=>JZ(n.sessionState,e,t)),{answer:void 0,effects:s8,facts:[]})},c8=({outcome:e})=>e,pie={launch:c8,"type-slash":c8,"apply-update":c8,run:c8,"lane-setup":c8,doctor:({effect:e,outcome:t},n)=>t.kind===`failed`?t:(U6(n,e,t.gathered),cc)};function mie(e,t){let n=pie[e.effect.kind];try{return n(e,t.verbCtx)}catch(n){return l8(e.effect,n,t.log)}}function l8(e,t,n){return t instanceof R||t instanceof uc||n(`error`,`apply: ${_$(e)} threw: ${O(t)}`),lc(t instanceof Error?t.message:String(t))}function hie(e,t){let{client:n,configEnv:r,...i}=t.hints,a=[{key:y$,value:JSON.stringify(i)},{key:v$,value:t.originRecord}];e.setBatch(t.sessionId,a.filter(({key:n,value:r})=>e.get(t.sessionId,n)!==r))}async function u8(e,t){let n=fie[e.kind],r=n(e,t),i=xie(e),a=yie[e.kind],o=a(e,r);return o!==null&&t.log(o.level,cQ(`apply`,[[`kind`,e.kind],[`verb`,i.verb],[`sid`,i.session??`-`],...o.facts,...r.facts,[`effects`,r.effects.map(e=>_$(e)).join(`,`)||`-`],[`revision`,i.session===null?`-`:String(t.verbCtx.sessionState.revision(i.session))]])),{answer:r.answer,performed:r.effects.length===0?d8:Die(t,i,r.effects)}}const d8=Promise.resolve();async function gie(e,t){return await u8(e,t),t.draw(e.req,e.at,e.waitEndsAt,e.facts)}const f8={level:`info`,facts:[[`outcome`,`ok`]]},_ie=({error:e})=>({level:`info`,facts:[[`outcome`,`refused`],[`said`,e instanceof Error?e.message:String(e)]]}),vie={ok:`info`,failed:`warn`},yie={request:()=>null,click:(e,{answer:t})=>t===null?f8:_ie(t),"menu-idle":()=>f8,answered:()=>f8,"effect-done":({done:e},{answer:t})=>({level:vie[t.kind],facts:[[`effect`,_$(e.effect)],[`outcome`,t.kind],[`said`,t.said||`-`]]})},bie={request:({req:e})=>({verb:`request`,session:e.sessionId}),click:({click:e})=>({verb:e.kind,session:a8(e)}),"menu-idle":({session:e})=>({verb:`menu-idle`,session:e}),"effect-done":({of:e})=>e,answered:({session:e})=>({verb:`answered`,session:e})};function p8(e,t,n,r){e(r instanceof uc?`info`:`error`,`apply: ${t} not applied (${n}): ${O(r)}`)}function m8(e,t,n){return u8(e,t).then(()=>void 0,r=>p8(t.log,e.kind,n,r))}function xie(e){let t=bie[e.kind];return t(e)}const Sie={launch:({spec:e,what:t},{verbCtx:n})=>Cie(n.launcher,e,t),"type-slash":async({pane:e,line:t},{verbCtx:n})=>{let r=await u$(n.claudeInput,e,t);return r.kind===`typed`?{kind:`ok`,said:`typed into ${r.pane}`}:lc(`${t} was not typed: ${r.reason}`)},"apply-update":async(e,{verbCtx:t})=>(await t.applyUpdate(),cc),run:({id:e,run:t},{verbCtx:n})=>n.runs.run(e,t),"lane-setup":(e,{verbCtx:t})=>t.lanes.setup(e),doctor:async(e,{verbCtx:t})=>({kind:`gathered`,gathered:await z6(t,e)})};async function Cie(e,t,n){let r=await e.launch({...t,timeoutMs:R3});return r.ok?cc:lc(`${n} failed (${gt(r)})`)}async function wie(e,t){let n=Sie[e.kind],r;try{r=await n(e,t)}catch(n){r=l8(e,n,t.log)}return{effect:e,outcome:r}}const h8={launch:{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1},"type-slash":{key:({pane:e})=>({kind:`pane`,tmux:e}),paneWhenReached:!1},"apply-update":{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1},run:{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1},"lane-setup":{key:({sessionId:e,lane:t})=>({kind:`lane`,session:e,lane:t}),paneWhenReached:!0},doctor:{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1}};function Tie(e,t){return h8[e.kind].key(e,t)}function Eie(e,t,n,r){let i=e=>h8[e.kind].paneWhenReached,a=[...n.filter(e=>!i(e)),...n.filter(i)],o=d8;for(let n of a){let i=o;o=e.performing(Tie(n,t),async()=>{await i,await r(n)})}return o}function Die(e,t,n){return Eie(e.verbCtx.journalTurns,t,n,async n=>{let r=await wie(n,e);await m8({kind:`effect-done`,of:t,done:r},e,`${_$(n)} ${r.outcome.kind}${`said`in r.outcome?`: ${r.outcome.said}`:``}`)})}function Oie({projectDir:e,cwd:t,target:n},r){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path===void 0?null:v0(r,n.path),source:n.source})}function kie(e,t,n){let{tokens:r}=k({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:EP(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function Aie(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=jr.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${jr.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function jie(e,t,n,r,i,a){let{report:o}=pQ(e.hookData),s=[];for(let e of o.missingRequired)s.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of o.typeMismatches)s.push(`field '${e}' expected ${t}, got ${n}`);let c=_Q(e.hookData?.session_id);c.ok||s.push(`field 'session_id' ${c.problem}`),(typeof e.cwd!=`string`||!u(e.cwd))&&s.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&s.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let l=Aie(e.encoding);l.ok||s.push(l.problem);let d=di(e.deadline);if(d.kind===`refused`)return{ok:!1,problems:[...s,d.problem]};if(s.length>0||!c.ok||!l.ok)return{ok:!1,problems:s};for(let e of o.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let f=Nr(e),{configFile:p,refusedArgs:m}=kie(e.args,e.cwd,r),h=f0(i),g=kP(p,f.configEnv),_={projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:g.source===`search`?g:{...g,path:x0(h,g.path)}};return{ok:!0,req:{...e,deadline:d,encoding:l.encoding,sessionId:c.id,hints:f,rateLimits:qne(e.hookData),requested:_,originRecord:Oie(_,h),refusedArgs:m,pane:cl(f,c.id,a)}}}function Mie(e,t){switch(e){case`vars`:return{what:e,vars:Nie(t)};case`segments`:return{what:e,segments:Lie(t)};case`config`:return{what:e,config:Vie(t)}}}function Nie(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=Iie(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=Pie(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:Fie(r.lastUpdatedMs(),t.clock)})}return o}function Pie(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 Fie(e,t){return e===null?null:Math.max(0,t.now()-e)}function Iie(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,g8(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}`,g8(i));return t}function g8(e){return e.kind}function Lie(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=zie(n),o=Rie(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:Bie(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function Rie(e){let t=new Map;for(let n of rS(e.presets))for(let r of sb(oS(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=rb(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function zie(e){let t=[],n=new Set;for(let r of sb(Gx(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 Bie(e,t,n){let r=new Set([...UC(e,t).keys()].flatMap(e=>ow(e,n)));return Array.from(r).sort()}function Vie(e){return e===null?null:e.config}const _8=[`vars`,`segments`,`config`];function Hie(e){return typeof e==`string`&&_8.includes(e)}const v8=e=>({resp:e,exitAfterFlush:null,delivered:NQ}),y8=e=>({kind:`reply`,...e}),Uie={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},b8=(e,t)=>y8(v8({ok:!1,error:t,code:e,daemonV:3}));function Wie(e){let t=_Q(e.sessionId);if(!t.ok)return b8(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return b8(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Qc.join(`, `)}): it predates the lane toggles — update it`);let n=ol(e.lane);return n===null?b8(`BAD_REQUEST`,`subscribe needs a lane, one of ${Qc.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}function Gie(e){let{session:t,path:n,seconds:r}=e,i=_Q(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=Jr(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 Kie(e,t){let n=Gie(t);if(!n.ok)return b8(`BAD_REQUEST`,n.problem);let{session:r,path:i,seconds:a}=n;return{kind:`held`,start:t=>MQ(e.recorder,e.clock,r,i,a,t).then(e=>v8({ok:!0,recorded:e}),e=>v8({ok:!1,error:e instanceof Error?e.message:String(e),code:e instanceof jQ?`RENDER_FAILED`:`BAD_REQUEST`,daemonV:3}))}}function qie(e,t,n){return e.v===n?null:(e.v>n?t(`info`,`version mismatch: client=${e.v} > daemon=${n}; binary likely upgraded — exiting after the response flushes`):t(`info`,`version mismatch: client=${e.v} < daemon=${n}; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v${n})`,code:`VERSION_MISMATCH`,daemonV:n},exitAfterFlush:e.v>n?0:null,delivered:NQ})}async function Jie(e,t,n,r,i){if(t.kind===`url`)return y8(v8(await eae(e,t.frame,n,r,i)));let a=t.req;if(!a||typeof a!=`object`||typeof a.v!=`number`)return b8(`BAD_REQUEST`,`malformed request`);let o=qie(a,e.log,3);return o===null?a.kind===`subscribe`?Wie(a):a.kind===`record`?Kie(e,a):typeof a.kind!=`string`||!Object.hasOwn(Uie,a.kind)?b8(`BAD_REQUEST`,`unknown kind`):y8(await x8(e,a,n,r,i)):o}async function x8(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:w}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:NQ};if(t.kind===`pane-session`){let{socket:n,pane:r}=t;return v8(typeof n!=`string`||typeof r!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:s.newestWhere(ll({socket:n,pane:r},e.heldSession))})}if(t.kind===`stats`)return v8({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:Yie(e),fileEvents:d.stats(),sourceRuns:p.stats(),runs:f.stats(),transcriptReads:Io(),renderCache:c.stats,effectCache:m.getStats(),menuIdle:h.getStats(),journalTurns:g.getStats(),sessionState:{sessions:e.sessionState.size(),observers:e.sessionState.observers(),revision:e.sessionState.latestRevision()},frameFeeds:s.getStats(),tmuxStatus:_.stats(),linkIds:e.linkIds.stats(),watchersActive:v.size(),dirWatchesActive:v.dirWatches(),dirsPolled:v.polledDirs(),nextRestartReason:y.describeNextRestart(),handlerProbes:b.list(),clients:x.list(it(new Date(o.now()))),bundle:S,sourceDigest:C,daemon:y.serving(),doctorStores:A4(w)})});if(t.kind===`render`){let c=new Date(o.now()),l=it(c),u=o.monotonic(),d=Ze(r,u),f=[],p=++a.requestsTotal,m=jie(t,a,e.log,e.home,e.storedRoot,e.heldSession),h=(t,n)=>x.see(t.sessionId,{client:t.hints.client??null,termCols:t.hints.termCols??null,rateLimits:t.rateLimits,claudeConfigDir:qo(t.hints.claudeConfigDir,e.home),projectDir:t.requested.projectDir,transcript:Jne(t.hookData),frame:n},l,p);m.ok&&(iQ(f,{sid:m.req.sessionId}),h(m.req,`drawing`),s.note(m.req.sessionId,m.req,p));let g=m.ok?await gie({kind:`request`,req:m.req,at:l,arrived:r,waitEndsAt:Xe(u,fi(m.req.deadline,r,{epochMs:c.getTime(),monoMs:u})),facts:f},e).then(({resp:t,motion:n,answersClick:r,pipeShown:i,delivered:a})=>(h(m.req,n),{outcome:{kind:`ok`},resp:t,delivered:()=>{a(),r.length>0&&m8({kind:`answered`,session:m.req.sessionId,errors:r},e,`sid=${m.req.sessionId}`),i!==null&&e.launcher.answeredPipeEvent(i)}}),e=>(h(m.req,`failed`),{outcome:w8(e),resp:PQ(e),delivered:NQ})):sae(m.problems);g.outcome.kind!==`ok`&&a.requestsErrored++,iQ(f,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:_,line:v}=sQ(`render`,f,g.outcome,Qe(o,u));return e.log(_,v),{resp:g.resp,exitAfterFlush:null,delivered:g.delivered}}if(t.kind===`click`)return v8(await S8(e,r,n,i,(n,r)=>$ie(e,t,n,r)));if(t.kind===`debug`){if(!Hie(t.what))return v8({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${_8.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`?Qie(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??_x(`colorCompatibility`)):Zie};return v8({ok:!0,debug:Mie(t.what,n)})}throw Error(`no reply for request ${O(t)}`)}function Yie(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 Xie={endcaps:_x(`endcaps`),colorCompatibility:_x(`colorCompatibility`),wrap:_x(`autoWrap`),padding:_x(`padding`),width:1/0},Zie=new Map;function Qie(e,t){let n=new Map;for(let[r,i]of e)n.set(r,Une(i,{...Xie,colorCompatibility:t}));return n}async function S8(e,t,n,r,i){let{clock:a}=e,o=a.monotonic(),s=[[`queued`,`${Ze(t,o)}ms`]],c=await i(s,()=>n()||r());iQ(s,{timedOut:n()?`Y`:`N`,clientLeft:r()?`Y`:`N`});let{level:l,line:u}=sQ(`click`,s,c,Qe(a,o));return e.log(l,u),aae(c)}async function $ie(e,t,n,r){let i={via:`link`,delivery:{kind:`cli`}};iQ(n,{via:`cli`});let{url:a}=t;return typeof a==`string`?C8(()=>T8(e,a,i,n,r)):{kind:`bad-request`,problems:[`a click's link is a string, got ${typeof a}`]}}async function eae(e,t,n,r,i){return S8(e,r,n,i,async(n,r)=>{let{urlV:i,url:a}=t;if(iQ(n,{via:`forwarder`,urlV:String(i)}),typeof i!=`number`||!Gr.has(i))return{kind:`bad-request`,problems:[`the URL handler's frame version ${O(i)} is not one this daemon speaks (${[...Gr].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 C8(()=>T8(e,a,o,n,r))})}async function C8(e){try{return await e()}catch(e){return tae(e)}}function tae(e){return e instanceof R?{kind:`bad-request`,problems:[e.message]}:e instanceof dc?{kind:`abandoned`,error:e}:w8(e)}function w8(e){return e instanceof uc?{kind:`closing`,error:e}:{kind:`threw`,error:e}}const nae={link:`to`,"tmux-status":`linkTo`},rae={link:`verb`,"tmux-status":`linkVerb`};async function T8(e,t,n,r,i){let a=yC(t);if(!a.ok)return{kind:`bad-request`,problems:[a.problem]};iQ(r,{[nae[n.via]]:a.to});let o=e.links.to;return a.to===o?iae(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 iae(e,t,n,r,i,a){if(t===`range`)return r.via===`tmux-status`?{kind:`bad-request`,problems:[`a status-line link names another status-line click`]}:(iQ(i,{verb:t}),oae(e,n,i,a));let o=iie(t,n);if(o===null)return{kind:`bad-request`,problems:[`unknown click verb: ${t}`]};iQ(i,{[rae[r.via]]:t}),iQ(i,{sid:a8(o)??`-`});let{answer:s}=await u8({kind:`click`,click:o,arrival:r,gone:a},e);if(s!==null)throw s.error;return{kind:`ok`}}function aae(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 PQ(e.error)}}async function oae(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):(iQ(r,{link:s.url}),pa(s.url)?T8(e,s.url,{via:`tmux-status`},r,i):(await B3(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,R3,e.tmp),{kind:`ok`}))}const sae=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:NQ});function cae(e,t){let n=ae(`sha256`).update(t).digest(`hex`).slice(0,16);return s.join(e,`update-act`,n)}const lae=e=>({spentMs:0,lastSeen:e.started}),uae=(e,t,n)=>n===null?t??lae(e):t===null||n.spentMs>t.spentMs||n.spentMs===t.spentMs&&n.lastSeen>t.lastSeen?n:t,dae=(e,t,n)=>{let r=t-e.lastSeen;return{spentMs:e.spentMs+(r>=0&&r<=n?r:0),lastSeen:t}},E8={kind:`idle`};function D8(e){if(e===null)return E8;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 O8=e=>({stdout:s.join(e,`stdout`),stderr:s.join(e,`stderr`),status:s.join(e,`status`)}),k8=e=>s.join(e,`record.json`),fae=e=>s.join(e,`awake.json`);function A8(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 j8(e){let t=Wo(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 M8(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})}async function pae(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 N8(e){try{return m.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function mae(e){let t=N8(k8(e));return t===null?null:JSON.parse(t)}const hae=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function gae(e,t,n,r){let i=null;async function a(a){let o=s.join(e,String(a)),c=mae(o);if(c===null)return null;if((i===null||!hae(i.record,c))&&(i={record:c,job:{},ours:await pae(c,t,n,r.bootTime()),final:null}),i.final!==null)return i.final;i.ours=i.ours&&n.jobGroupAlive(c.pid);let l=O8(o),u=qt(l.status),d=u===null?null:j8(l.stderr)??j8(l.stdout);if(!m.existsSync(o))return null;let f={act:a,job:i.job,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=A8(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 _ae(e,t,n){m.mkdirSync(e,{recursive:!0});let r=m.mkdtempSync(s.join(e,`.claim-`));try{return m.writeFileSync(k8(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 vae(e,t,n,r,i,a,o,c){let l=(n??0)+1,u=s.join(t,String(l)),d=e.launchJobSync(i,O8(u));if(!d.ok)throw Error(`apply-update: ${d.error}`);let f=!1;try{let e=await c(d.pid);if(!_ae(t,u,{identity:r,pid:d.pid,startTime:e.kind===`start`?e.token:null,started:o,deadline:o+a}))return P8;if(A8(t).some(e=>e>l))return M8(t,l),P8;f=!0}finally{f?d.release():d.withdraw()}for(let e of A8(t).filter(e=>e<l))M8(t,e);return{ok:!0,act:l}}const P8={ok:!1,reason:`another act claimed this bundle first`};function yae(e){let t;try{t=N8(e)}catch(e){return{kind:`unread`,reason:e.message}}if(t===null)return{kind:`spend`,awake:null};let n;try{n=JSON.parse(t)}catch(e){return{kind:`unparsed`,reason:`${e.message}: ${t}`}}let{spentMs:r,lastSeen:i}=n??{};return typeof r==`number`&&typeof i==`number`&&r>=0&&Number.isFinite(r)&&Number.isFinite(i)?{kind:`spend`,awake:{spentMs:r,lastSeen:i}}:{kind:`unparsed`,reason:`not an act's spend: ${t}`}}function bae(e,t,n,r,i){let a=fae(s.join(e,String(t.act))),o=yae(a),c=dae(uae(t.record,o.kind===`spend`?o.awake:null,n),r,i);if(o.kind===`unread`)return{awake:c,fault:`${a}: ${o.reason}; left in place`};let l=[];if(o.kind===`unparsed`){let e=n===null?`its spend restarts`:`its spend carries on from this daemon's last look`;l.push(`${a}: ${o.reason}; ${e}`)}let u=ct(a);try{m.writeFileSync(u,JSON.stringify(c)),m.renameSync(u,a)}catch(e){m.existsSync(u)&&m.rmSync(u,{force:!0});let t=e.code;if(t===`ENOENT`)return null;l.push(`${a}: not written: ${t??e.message}`)}return{awake:c,fault:l.length===0?null:l.join(`; `)}}function xae(e,t,n){let r=O8(s.join(e,String(t.act))).status;return n.endJob(t.record.pid,r,{kind:`timeout`})}var F8=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 I8(e){return e.kind===`source`?e.newer.digest:rs(e.newer)}const L8=e=>`${e.version} [${Ln(e.digest)}]`;function R8(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:L8(e.newer),running:L8(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:rs(e.newer),running:rs(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${is}@${rs(e.newer)}`,`install`]}}}}function Sae(e,t,n){if(e===null)return[];let r=I8(e);if(!n.enabled||n.dismissed===r)return[];let i=R8(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(`
500
- `),c=t.kind===`running`?rU(`[${i.busy}]`,null):rU(`[${i.act}]`,fC(n.to,[{verb:QS,args:[n.sessionId]}])),l=[rU(a,null),c,rU(`[dismiss]`,fC(n.to,[{verb:FS,args:[n.sessionId,xz,r]}])),rU(`[disable]`,fC(n.to,[{verb:BS,args:[n.sessionId,Sz,`false`]},{verb:FS,args:[n.sessionId,Cz,`false`]}]))],u=o.map(e=>[rU(e,null)]);return[{severity:eU,about:`update\0${r}`,message:s,copy:s,lines:[l,...u]}]}function Cae(e,t){if(e.kind===`pending`)return e;let n=e.value;switch(n.kind){case`stale`:return F({kind:`source`,root:n.root,newer:n.source,running:n.running});case`current`:return I;case`unchecked`:return L(`build: unchecked: ${n.reason}`,`read`);case`not-source-checkout`:return wae(t)}}function wae(e){if(e.kind===`pending`)return e;let t=e.value;switch(t.kind){case`stale`:return F({kind:`release`,newer:t.latest,running:t.installed});case`current`:case`ahead`:return I;case`unchecked`:return L(`release: unchecked: ${t.reason}`,`read`)}}const z8=600*1e3,B8=2e3;5*B8;function Tae(e){switch(e.kind){case`current`:return[`info`,`build: current ${L8(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${L8(e.source)}, running ${L8(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function Eae(e){switch(e.kind){case`current`:return[`info`,`release: current ${rs(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${rs(e.latest)}, running ${rs(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${rs(e.installed)}, latest ${rs(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function Dae(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=So(`unread`),g=So(`unread`),_=async e=>{let t=await i.startTime(e);if(T)throw new uc(`apply-update`);return t},v=gae(s,_,r,n),y=null,b=null,x=Fe(m),S=Fe(m),C=new F8,w=e=>C.run(`acts`,e),T=!1,E=[],ee=(e,t)=>{E.push(n.every(t,e,{unref:!0}))},D=()=>{let e=t.get();return e.kind===`ok`?e.value:null};function te(){let e=D(),t=e===null?null:I8(e);(b===null?null:b.identity)!==t&&(b?.dispose(),b=t===null?null:{identity:t,dispose:f.state.register(xz,[t])})}function O(){let e=T?I:Cae(h,g),r=lQ(t.get(),e,st(n));(0,X.runInAction)(()=>t.set(r)),te()}function k(){let e=Un(a,()=>Bn(o));return h=F(e),x(Tae(e)),O(),e}async function ne(){let e=os(Rn,await as(is,d,u,n));g=F(e),S(Eae(e)),O()}let A=null,re=Fe(m),ie=e=>`update act files (${s}): ${e}`;async function ae(e){try{let t=await e();return A=null,{ok:!0,value:t}}catch(e){return e instanceof uc?{ok:!1,error:e.message}:(A=ie(e.message),re([`error`,A]),{ok:!1,error:A})}}let oe=null,se=null,ce=null,le=Fe(m);function ue(e){if(!e?.alive)return null;let t=bae(s,e,oe?.job===e.job?oe.awake:null,n.now(),1e4);return t===null?null:(oe={job:e.job,awake:t.awake},t.awake.spentMs>z8&&de(e),t.fault===null?null:ie(t.fault))}function de(e){let t=xae(s,e,r);if(t.verdict===`gone`){m(`error`,`apply-update: act ${e.act} timed out, but its files were removed before it could be ended; its group (pid ${e.record.pid}) was not signalled`);return}let n=t.signalled?`ending it`:`its group took no signal`;if(t.verdict!==`unrecorded`){let r=t.verdict===`stands`?`timed out`:`outlived its verdict`;m(`error`,`apply-update: act ${e.act} ${r}; ${n}`);return}let i=ie(`act ${e.act} timed out; its verdict could not be written: ${t.error}; ${n}`);m(`error`,`apply-update: ${i}`),se={job:e.job,reason:i}}async function fe(){let e=await ae(async()=>{let e=await v.read();return T||(ce=ue(e)),e});if(T||!e.ok)return;ce!==null&&le([`error`,ce]),se!==null&&e.value?.job!==se.job&&(se=null);let t=D8(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`),k(),p()),t.kind===`failed`&&m(`error`,`apply-update: act ${t.act} failed: ${t.reason}`)),y=t}let pe;async function me(){await w(fe),!T&&(pe=n.after(B8,()=>void me(),{unref:!0}))}return{arm(){let e=k();ee(k,c),E.push(()=>pe?.()),me(),e.kind===`not-source-checkout`&&(ne(),ee(()=>void ne(),l))},close(){T=!0,O(),E.forEach(e=>e())},notice:e=>Sae(D(),y??E8,e),running:()=>w(async()=>{let e=await ae(()=>v.read());return e.ok&&D8(e.value).kind===`running`}),error:()=>A??ce??se?.reason??null,act:()=>w(async()=>{if(T)throw new uc(`apply-update`);let e=await ae(()=>v.read());if(T)throw new uc(`apply-update`);if(!e.ok)throw new R(`apply-update: ${e.error}`);let t=D();if(t===null)throw new R(`apply-update: nothing newer is known to apply`);let i=R8(t),a=e.value;if(D8(a).kind===`running`)throw new R(`apply-update: already ${i.busy}`);let o=await vae(r,s,a===null?null:a.act,I8(t),{...i.command,category:`update.apply`},z8,n.now(),_);if(!o.ok)throw new R(`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},se=null})}}function Oae(){return X.observable.box(So(`unread`),{deep:!1})}function V8(e,t){try{return F(t.statSync(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?I:L(e.message,`read`)}}function kae(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function Aae(e){let{targets:t,intervalMs:n,filesystem:r,held:i,exit:a,log:o,clock:s}=e,c=Fe(o),l=t.map(e=>({path:e,stamp:V8(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=V8(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!kae(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 jae=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 H8=`pass`,U8={okMs:5*6e4,failedMs:45e3},Mae=U8.okMs;function W8({failures:e}){return Cj(U8,e,Mae)}function Nae(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function Pae(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function Fae(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function Iae(e,t,n,r){let i=[{path:n,filenames:[`HEAD`,`index`]},{path:s.join(r,`refs`,`heads`),recursive:!0}],a=i.map(t=>Lc(e,t.path));return{key:`git:${t}:${i.map((e,t)=>`${e.path}@${Rc(a[t])}`).join(`|`)}`,targets:{dirs:i},unbound:a.some(e=>typeof e==`string`||`unreadable`in e)}}function Lae(e){return e.find(e=>e.kind===`ok`)?.value.branch}function G8(e){e.missed=!0,Oj(e,`unread`)}function Rae(e,t){return e.missed&&e.reading.get().kind===`pending`&&Dj(e,t.size>0?L([...t].join(`; `),`read`):I),`unkeyed`}function zae(e,t){let n=jj(e);return t===null||n.kind!==`ok`?n:F({...n.value,pullRequest:jj(t)})}const Bae=L(`git cache closed`,`read`);function K8(e){return t=>L(`${e} threw: ${String(t)}`,`read`)}var Vae=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 Do(e.maxPrLookups??2),this.logger=e.logger??Ie;let t=e.ledger??new Hj(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 xj({filesystem:mn,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=L(`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 Fj(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>zae(a,o)}}asked(e,t,n,r){if(this.closed)return{kind:`settled`,outcome:Bae};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 jae,watch:this.followWatch(e,null).watch,period:new wj(()=>{n.refresh.share(H8,()=>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=Iae(this.watchers.filesystem,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(H8,()=>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&&G8(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(H8,()=>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:Tj(),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=Fae(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(Pae(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(K8(`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,Dj(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of KU(n.value))c.add(e)});let l=Lae(o),u=a===null||i.length===0?`-`:l===void 0?Rae(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}`,Nae(n),c.size===0?F(null):L([...c].join(`; `),`read`),Qe(this.clock,t))}prSource(e){let t={period:new wj(()=>{this.readPr(e,t,`period`)},this.clock),seen:new Map,holders:0,missed:!0,key:``,remote:I,reading:Tj(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(K8(`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?(G8(t),`owed`):(Oj(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,Dj(t,a.outcome),t.period.landed(W8(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(K8(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:I)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${z(r)}`,n,i,Qe(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||(Dj(t,i),t.period.landed(W8(s),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=L(`git state dropped: ${e.root}`,`read`);for(let n of e.values.values())kj(n,t);e.pr!==null&&kj(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 q8=`claude-sonnet-4-5-20250929`,Hae={"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}},J8=new n(`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`),Uae={okMs:1440*60*1e3,failedMs:3e4},Y8=e=>e===null?null:e.kind===`landed`?e:e.last,X8=(e,t)=>e===null?t:t===null||e.at>=t.at?e:t,Z8=e=>e.kind===`landed`?0:e.failures,Q8=e=>Cj(Uae,e,36e5),$8=(e,t)=>e.at+Q8(Z8(e))<=t;function Wae(e){let t=X.observable.box(null,{deep:!1}),n=(0,X.computed)(()=>Y8(t.get()),{equals:(e,t)=>e?.at===t?.at}),r=n=>n.then(e=>(0,X.runInAction)(()=>t.set(e))).catch(t=>{e.log(`error`,`pricing load rejected: ${String(t)}`)}),i=r(t5(e)),a=null,o=Fe(e.log);return{table:()=>n.get()?.table??Hae,ask:()=>{let n=t.get();!(n===null||$8(n,e.clock.now()))||e.closing.aborted||(a??=i.then(()=>r(Gae(e,t.get(),o))).finally(()=>{a=null}))}}}async function Gae(e,t,n){let r=await t5(e);if(r!==null&&!$8(r,e.clock.now()))return X8(r,Y8(t));let i=await Kae(e).catch(t=>(e.log(`error`,`pricing load threw: ${String(t)}`),null));if(i!==null)return i;if(e.closing.aborted)return t??r;let a={kind:`failed`,at:e.clock.now(),failures:(t===null?0:Z8(t))+1,last:X8(r,Y8(t))};return n([`warn`,`pricing table not loaded: priced by ${a.last===null?`the bundled rates`:`the last table`}; the next ask after ${Q8(a.failures)}ms tries again`]),a}const e5=e=>s.join(e,`usage`,`pricing.json`);async function Kae(e){let t=e.closing.aborted?null:await Jae(e.closing);if(t===null)return null;let n={kind:`landed`,table:t,at:e.clock.now()};return e.closing.aborted||await qae(e,n),n}async function t5(e){try{let{data:t,timestamp:n}=JSON.parse(await m.promises.readFile(e5(e.cacheRoot),`utf8`));return typeof n!=`number`||n>e.clock.now()||!n5(t)?null:{kind:`landed`,table:t,at:n}}catch(t){return t.code!==`ENOENT`&&e.log(`warn`,`pricing disk cache unreadable: ${String(t)}`),null}}async function qae(e,t){let n=e5(e.cacheRoot),r=ct(n);try{await m.promises.mkdir(s.dirname(n),{recursive:!0}),await m.promises.writeFile(r,JSON.stringify({data:t.table,timestamp:t.at}),`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 Jae(e){return new Promise(t=>{let n=ve({hostname:J8.hostname,path:J8.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3,agent:!1,signal:e},e=>{if(e.statusCode!==200){Pe(`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){Pe(`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);n5(i)?(Pe(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),Pe(`Pricing last updated: ${n?.updated||`unknown`}`),t(i)):(Pe(`Invalid pricing data structure`),t(null))}catch(e){Pe(`Failed to parse JSON:`,e),t(null)}}),e.on(`error`,e=>{Pe(`Response error:`,e),t(null)})});n.on(`error`,e=>{Pe(`Request error:`,e),t(null)}),n.on(`timeout`,()=>{Pe(`Request timeout`),n.destroy(),t(null)}),n.end()})}function n5(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 Yae(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[q8]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}function Xae(e,t,n){let r=Yae(t,e);return n.input/1e6*r.input+n.output/1e6*r.output+n.cacheCreation/1e6*r.cache_write_5m+n.cacheRead/1e6*r.cache_read}function Zae(e){return e.model||e.message?.model||q8}var r5=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 Qae(e,t){return{input:e.input+e.cacheCreation+e.cacheRead,output:e.output,total:HK(e),atMs:t}}const $ae={okMs:60*1e3,failedMs:10*1e3},eoe={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function i5(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-1),t.getTime()}function a5(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}function o5(e,t){e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function toe(e){return{input:e.input_tokens||0,output:e.output_tokens||0,cacheCreation:e.cache_creation_input_tokens||0,cacheRead:e.cache_read_input_tokens||0}}const s5={carried:{cost:0,tokens:a5()},unpriced:new Map};function c5(){return{carried:{cost:0,tokens:a5()},unpriced:new Map}}function l5(e,t){e.carried.cost+=t.carried.cost,o5(e.carried.tokens,t.carried.tokens);for(let[n,r]of t.unpriced){let t=e.unpriced.get(n);t===void 0?e.unpriced.set(n,{...r}):o5(t,r)}}function noe(e,t){let n=toe(t),r=e.costUSD??(HK(n)===0?0:void 0);return r===void 0?{carried:s5.carried,unpriced:new Map([[Zae(e.raw),n]])}:{carried:{cost:r,tokens:n},unpriced:s5.unpriced}}function u5(e){let t={...e.carried.tokens};for(let n of e.unpriced.values())o5(t,n);return t}function d5(e,t){let n=e.carried.cost;for(let[r,i]of e.unpriced)n+=Xae(t,r,i);return n}function roe(e,t){return{cost:d5(e,t),...u5(e)}}function f5(e,t){if(e===void 0||e.entries===0)return eoe;let n=u5(e.usage),r=d5(e.usage,t);return{cost:r,calculatedCost:r,officialCost:null,tokens:HK(n),tokenBreakdown:n}}const ioe={entries:0,usage:s5,days:new Map};function p5(e,t,n){let r=e.get(t);r===void 0&&(r=c5(),e.set(t,r)),l5(r,n)}function aoe(e,t,n){let r=e.entries,i=c5();l5(i,e.usage);let a=new Map;for(let[t,r]of e.days)t>=n&&p5(a,t,r);for(let e of t){let t=e.message?.usage;if(!t)continue;r++;let o=noe(e,t);l5(i,o);let s=GK(new Date(e.timestamp));s<n||p5(a,s,o)}return{entries:r,usage:i,days:a}}function ooe(e){let t=0,n=c5(),r=new Map;for(let{value:i}of e.values()){t+=i.entries,l5(n,i.usage);for(let[e,t]of i.days)p5(r,e,t)}return{entries:t,usage:n,days:r}}function m5(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function soe(e,t,n){let r=new Map;for(let{record:n}of e)if(!(n===void 0||!m5(n.transcriptPath,t)))for(let[e,t]of n.days)p5(r,e,t);return h5(r,n)}function h5(e,t){let n={};for(let[r,i]of e)n[r]=roe(i,t);return n}async function coe(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 g5(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function _5(e,t){(0,X.runInAction)(()=>e.set(t))}var loe=class{sessions=X.observable.map(void 0,{deep:!1});flight=new r5;scans;daySets=new Map;speedFlight=new r5;requestFlight=new r5;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??Ie,this.ledger=e.ledger??new Hj(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new Lj({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${z(e.join(`,`))}`,read:e=>this.scan(e),every:()=>e.rescan??$ae,watch:Ij,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=ko(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async e=>{let t=await r().record;return t.kind===`failed`?t:F(g5(f5(t.kind===`ok`?t.value:void 0,this.pricing.table()),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 So(`unread`);let r=n.failure.get();return r===null?F(g5(f5(n.record,this.pricing.table()),t)):L(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,Qe(this.clock,i)),_5(this.hold(e).failure,a.kind===`failed`?a.reason:null),this.holdsUnpriced()&&this.pricing.ask(),a})}holdsUnpriced(){for(let{record:e}of this.sessions.values())if(e!==void 0&&e.usage.unpriced.size>0)return!0;return!1}refreshToday(e){return this.request(e?.session_id??``,e?.transcript_path).today()}declareToday(e,t){if(this.closed)return Fj(L(`usage store closed`,`read`));let n=b2(t,this.host.home),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?F({roots:i.roots,sums:i.sums.read()}):e}}}daysOutside(e,t){let n=this.sessions.get(e);if(n===void 0)return I;let r=n.failure.get();if(r!==null)return L(r,`read`);let i=n.record;return i===void 0||m5(i.transcriptPath,t)?I:F(h5(i.days,this.pricing.table()))}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return I;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return _5(this.hold(e).speed,t),t;let r=Qae(t.kind===`ok`?u5(t.value.usage):a5(),n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=F({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return _5(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??So(`unread`):I}async ingest(e,t,n,r){if(!e)return I;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,F(i);if(!t)return i?F(i):I;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`,`read`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let{mainStamp:c,...l}=s.value,u={...l,transcriptStamp:c,transcriptPath:t},d=this.sessions.get(e)?.record;return d===o?(this.stored(e,u),F(u)):d===void 0?F(u):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,X.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:X.observable.box(null),speed:X.observable.box(void 0,{deep:!1})};return(0,X.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 Sw(`today over ${e.join(`,`)}`,()=>soe(this.sessions.values(),r,this.pricing.table()))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await C2(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of M2(r.longLines))this.log(`info`,e);let i=GK(new Date(i5(this.clock.now()))),a=new Map,o=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),s=await N2(e,r,ioe,(e,t)=>aoe(e,t,i));if(s.kind===`failed`)return s;if(s.kind===`absent`){r&&a.set(e,r);continue}let{folded:c,longLines:l}=s.value;for(let e of M2(l))this.log(`info`,e);a.set(e,c),e===t&&(o=c.cursor.stamp)}return F({files:a,...ooe(a),mainStamp:o})}async scan(e){try{let t=i5(this.clock.now()),n=await x2(e),r=[];for(let e of n){let n=await S2(No(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a=await S2(Po(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:Ao(a)})}}let i=[],a={hits:0,misses:0};return await coe(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?L(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`,`read`):F({sessions:r.length,read:a.misses})}catch(e){return L(`usage scan: ${e instanceof Error?e.message:String(e)}`,`read`)}}sweepStale(){let e=this.clock.now(),t=GK(new Date(e)),n=0,r=0,i=0;return(0,X.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,X.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},v5=class{values=X.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,X.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)}})}},y5=class{sessions;flight=new r5;constructor(e,t,n,r,i=Ie,a=256){this.empty=e,this.step=t,this.refreshes=n,this.clock=r,this.log=i,this.sessions=new v5(a)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=ko(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 N2(t,n,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${z(e)}`,`request`,i,Qe(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 M2(o))this.log(`info`,e);return this.store(e,a,{kind:`ok`,value:a.value})}answer(e){return this.sessions.get(e)?.answer??So(`unread`)}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function uoe(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 doe=class{fold;constructor(e){let t=e.logger??Ie;this.fold=new y5(void 0,uoe,(e.ledger??new Hj(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 Pe(`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);Pe(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){return this.contextFrom(await this.fold.read(e,t),n)}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t?F(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,b5(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return F(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,b5(e))}contextFrom(e,t){if(e.kind===`failed`)return L(`context transcript: ${e.reason}`,e.failedAt);let n=e.value;return n===void 0?(Pe(`No main chain entries with usage data found`),I):(Pe(`Most recent main chain context: ${n} tokens (limit: ${t})`),F({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function b5(e){return e.context_window?.context_window_size??2e5}const foe={messageCount:0,nonPrompts:0,recent:[]},poe=new Set([`turn`,`interrupt`,`claude-code`]);function moe(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!poe.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function hoe(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 goe=class{fold;constructor(e){let t=e.logger??Ie;this.fold=new y5(foe,moe,(e.ledger??new Hj(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getMetricsInfo(e,t){Pe(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?x5(e,n,await this.fold.read(e,t.transcript_path)):I}metricsOf(e,t){let n=t.cost;if(!n)return I;let r=this.fold.answer(e);return r.kind===`pending`?r:x5(e,n,r)}};function x5(e,t,n){return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`,n.failedAt):F({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:hoe(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 _oe={command:null,todos:[],pending:[],done:[]};function S5(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 voe(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 yoe(e,t){if(t.isSidechain)return e;let n=voe(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=S5(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 boe(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>S5(e,t.name),[]),done:e.done}}var xoe=class{fold;constructor(e){let t=e.logger??Ie;this.fold=new y5(_oe,yoe,(e.ledger??new Hj(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getActivityInfo(e,t){return C5(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:C5(e,t)}};function C5(e,t){return t.kind===`failed`?L(`activity (${e}): ${t.reason}`,t.failedAt):F(boe(t.value))}const w5=3e4;var Soe=class{names;constructor(e){let t=e.logger??Ie;this.names=new Lj({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${z(e.pane)} socket=${z(e.socket)}`,read:t=>Coe(e.launcher,t),every:()=>({okMs:w5,failedMs:w5}),watch:Ij,maxEntries:64,logger:t,ledger:e.ledger??new Hj(t),clock:e.clock})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function Coe(e,t){let n=await sc(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return L(n.reason,`read`);let r=n.stdout.trim();return r?F(r):I}const T5=6e4,woe={okMs:T5,failedMs:T5};function Toe(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function E5(e,t){try{let e=t();return Promise.resolve(e===``?I:F(e))}catch(t){return Promise.resolve(L(`host.${e}: ${String(t)}`,`read`))}}var Eoe=class{name;user;constructor(e){let t=e.logger??Ie,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:()=>woe,watch:Ij,maxEntries:1,logger:t,ledger:e.ledger??new Hj(t),clock:e.clock};this.name=new Lj({...n,name:`host.name`,read:()=>E5(`name`,()=>Toe(o.hostname()))}),this.user=new Lj({...n,name:`host.user`,read:()=>E5(`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()}},Doe=class{known=new v5(64);refreshes;constructor(e,t=Ie,n=new Hj(t)){this.clock=e,this.refreshes=n.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=Ooe(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=bI(e);return this.refreshes.recorded(`path=${z(e)} stamp=${z(t)}`,`request`,i,Qe(this.clock,r)),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??So(`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 Ooe(e){try{let t=m.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Ao(t)}catch(e){return`unread:${e.code??`error`}`}}const koe=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function Aoe(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 joe=class{known=new v5(256);refreshes;constructor(e,t=Ie,n=new Hj(t)){this.clock=e,this.refreshes=n.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=ko(t),r=this.known.get(e);if(r!==void 0&&n!==``&&r.stamp===n&&r.outcome.kind!==`failed`)return this.known.touch(e),r.outcome;let i=await this.read(e,t,n);return this.known.set(e,{stamp:n,outcome:i}),i}expiryOf(e){return this.known.get(e)?.outcome??So(`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 Moe(t);return this.refreshes.recorded(`sid=${z(e)} stamp=${z(n)}`,`request`,i,Qe(this.clock,r)),i}};async function Moe(e){let t=await Noe(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function Noe(e){for(let t of[65536,1048576]){let n=await Uo(e,t);if(n.kind!==`ok`)return n;let r=Poe(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function Poe(e,t){let n=e.toString(`utf8`).split(`
501
- `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!koe.test(t))continue;let r=Aoe(t);if(r!=null)return r}return null}const D5=e=>ZV(e),O5=e=>s.join(e.storage.folder,D5(e.sessionId)),k5=e=>JSON.stringify([e.folder,e.generation]),Foe=(e,t)=>e.folder===t.folder&&e.generation===t.generation,Ioe=(e,t,n)=>e.kind===`unusable`?{cause:`unusable`,reason:e.reason}:t===null?n===null?null:{cause:`error`,reason:n}:{cause:t.kind===`refused`?`refused`:`error`,reason:fj(t)};var Loe=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;fileEvents;clock;unsubscribe;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.fileEvents=e.fileEvents,this.clock=e.clock,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new Lj({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${z(O5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:()=>null,watch:Ij,maxEntries:256,logger:e.logger,ledger:e.ledger??new Hj(e.logger),clock:e.clock})}keyFor(e){let t=this.folders.get(e)??this.recorded(e);t.unusable=null;try{this.watchers.filesystem.mkdirSync(e)}catch(e){t.unusable=`could not be created: ${e.message}`}let n=t.unusable===null?this.statOf(e):{now:`gone`},r=`now`in n?n.now:null,i=t.lost||t.identity!==null&&r!==null&&(r===`gone`||!Fc(r,t.identity)),a=i?null:t.identity;return t.identity=r===null?a:r===`gone`?null:r,i&&(t.generation++,t.lost=!1,this.logger(`info`,`plugin storage generation folder=${z(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(k5(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.statOf(e.folder):{now:`gone`},i=e.generation===t.generation?t.identity:null,a=`now`in r?r.now:i??`unnamed`;e.generation===t.generation&&(t.identity=typeof a==`string`?null:a),n!==null&&(t.lost=!0);let o={key:e,folder:t,identity:a,holders:0,handle:this.watchers.acquire(`plugin-storage:${k5(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(o,e)),stopSweep:this.clock.every(864e5,()=>void this.sweep(e),{unref:!0}),health:n===null?{kind:`watching`}:{kind:`unusable`,reason:n},deafness:null,statFailure:`failed`in r?r.failed:null,reported:null};return this.watched.set(k5(e),o),this.heard(o),this.settled(o,()=>!1),this.sweep(e),o}closed(e){let t=k5(e.key);this.watched.delete(t),e.health={kind:`closed`},e.stopSweep(),e.handle.release()}invalidated(e,t){let{key:n}=e,r=s.join(n.folder,s.basename(n.folder));this.heard(e);let i;if(t.kind===`changed`&&!t.paths.has(r)){let{paths:e}=t;i=t=>e.has(O5(t))}else{let t=this.judged(e);i=(e,n)=>t===`lost`||t===`present`&&n===null}this.settled(e,i)}heard(e){e.deafness=e.handle.deaf[0]??null}judged(e){let{health:t}=e;if(t.kind!==`watching`)return`none`;let{key:n,folder:r}=e,i=this.statOf(n.folder);if(e.statFailure=`failed`in i?i.failed:null,`failed`in i)return`none`;let{now:a}=i,o=e.identity===`unnamed`?a:e.identity;return e.identity=o,n.generation===r.generation&&o!==`gone`&&(r.identity=o),a!==`gone`&&o!==`gone`&&Fc(a,o)?`present`:(e.health={kind:`lost`},n.generation===r.generation?(r.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${z(n.folder)} generation=${n.generation} now=${a===`gone`?`gone`:`replaced`}`),`lost`):`none`)}statOf(e){try{return{now:Pc(this.watchers.filesystem,e)}}catch(e){return{failed:`stat failed: ${e.message}`}}}settled(e,t){let{key:n}=e,r=this.reported(e),i=e.reported;this.sessions.changed(e=>Foe(e.storage,n)&&(r||t(e,i)))}reported(e){let{key:t}=e,n=e.reported,r=Ioe(e.health,e.deafness,e.statFailure);e.reported=r;let i=`folder=${z(t.folder)} generation=${t.generation}`;return r!==null&&(n===null||n.cause!==r.cause||n.reason!==r.reason)?(this.faultCounts[r.cause]++,this.logger(`warn`,`plugin storage fault ${i} cause=${r.cause} reason=${JSON.stringify(r.reason)}`),!0):r===null&&n!==null?(this.logger(`info`,`plugin storage fault cleared ${i} cause=${n.cause}`),!0):!1}noticed(e){switch(e.kind){case`period`:for(let e of[...this.watched.values()]){let t=this.judged(e)===`lost`;this.settled(e,()=>t)}return;case`moved`:case`caught-up`:this.sessions.changed(()=>!0);return}}standing(e){let t=this.watched.get(k5(e));if(t===void 0)return null;let n=t.reported;if(n?.cause===`unusable`)return`cannot refresh: ${e.folder} ${n.reason}; reload the config or restart the daemon`;let r=n?.reason??Gc(this.fileEvents.delivery(),t.handle);return r===null?null:`cannot refresh: ${e.folder}: ${r}`}async read(e){let t=this.standing(e.storage);if(t!==null)return L(t,`read`);let n=O5(e),r;try{r=await this.watchers.filesystem.readFile(n)}catch(e){let t=e;return t.code===`ENOENT`?I:L(`${n}: ${t.message}`,`read`)}if(r.trim()===``)return I;let i=Jj(r);return i.kind===`failed`?L(`${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=${Qe(this.clock,t)}ms`;try{let t=await this.watchers.filesystem.readdir(e.folder);for(let a of t){if(a.kind!==`file`||!a.name.endsWith(`.json`))continue;r++;let t=s.join(e.folder,a.name);try{let{mtimeMs:r}=await this.watchers.filesystem.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&D5(t.sessionId)===a.name);if(r>=n||o)continue;await this.watchers.filesystem.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 Roe(e){let{launcher:t,clock:n,logger:r,ledger:i}=e;return{home:e.host.home,hostService:new Eoe({clock:n,logger:r,ledger:i}),gitProvider:new Vae({inner:new bW(t,e.watchers.filesystem),watchers:e.watchers,clock:n,logger:r,ledger:i}),usageStore:new loe({host:e.host,pricing:e.pricing,clock:n,logger:r,ledger:i}),contextProvider:new doe({clock:n,logger:r,ledger:i}),metricsProvider:new goe({clock:n,logger:r,ledger:i}),activityProvider:new xoe({clock:n,logger:r,ledger:i}),tmuxService:new Soe({launcher:t,clock:n,logger:r,ledger:i}),autoCompact:new Doe(n,r,i),cacheExpiry:new joe(n,r,i),managedStorage:new Loe({watchers:e.watchers,fileEvents:e.fileEvents,clock:n,logger:r,ledger:i}),faults:new bQ,log:e.logger,clock:n}}function A5(e,t,n,r){let i=[];try{return{kind:`parsed`,loaded:pK(e,t,r.locs,r.layers,zK,{warned:e=>i.push(...e)},{repo:r.repo,cwd:n}),warnings:i}}catch(e){return e instanceof Ab&&i.push(...e.warnings),{kind:`failed`,cause:e,warnings:i}}}function zoe(e,t){let{locations:n,projectDir:r,cwd:i,configFile:a}=t,o=zH(e,n,ZH(e,t.stateDir),r,i,a),{repos:s}=o,c={layers:o.kind===`chain`?o.layers:[],home:o.home,repo:s.plugins,locs:n};return{cwd:i,chain:c,repos:s,advisories:[KH(e,n,r,i),WH(o),zP(s)],parsed:A5(e,t.memo,i,c)}}function*j5(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*Boe(e){for(let t of Object.keys(e.segments))yield*NU(e,t);for(let t of rS(e.presets))yield*FU(e,t);for(let[,t]of j5(e))for(let[,e]of gb(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of yS(t))yield e}function Voe(e,t,n){let r=MU(t),i=new Set,a=new Set,o=new Set;for(let e of Boe(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of qC(e,t.helpers))a.add(n);for(let n of ew(e,t.helpers))o.add(n)}for(let[,e]of j5(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 rS(t.presets))for(let n of sb(oS(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=>!OS(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(j5(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 Hoe(e){return Math.floor(Math.max(e/4,e*Li-67108864))}const Uoe={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function M5(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[XV(CC(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[CC(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>wC(e)(t)&&t!==XV(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${jP(e,`<default>`)}: projections=${[...bG(n).keys()].join(`,`)||`-`} instantSegments=${DZ(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 Woe=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},Goe=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${Woe(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function Koe(e,t,n){let r=e=>z(e.join(`,`)||`-`);return`config loaded projectDir=${z(e.origin.projectDir)} cwd=${z(e.origin.cwd)} cause=${z(Goe(t))} state=${n} files=${z(jP(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 qoe(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function N5({projectDir:e,cwd:t,target:n}){return{projectDir:e,cwd:t,target:{path:n.path}}}function P5(e){return JSON.stringify(N5(e))}function Joe(e,t){return new Set(rS(e.presets).filter(n=>oS(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function Yoe(e,t,n){let{loaded:r,dropped:i,unreached:a}=t.state.plugins,o=[...new Set([...t.state.plugins.roots,s.join(t.origin.projectDir,AH)])];return uj(e,{named:[...FH(n,t.origin.projectDir,t.origin.cwd,t.origin.target.path),...o,...r.map(e=>e.path),...[...i,...a].map(e=>e.path),...new Set([...t.state.sources.values()].map(e=>e.folder))],whole:o})}function Xoe(e){return e.filter(Boolean).join(`
502
- `)||null}const F5=e=>e instanceof Error?e.message:String(e);function I5(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function Zoe(e){let{loaded:t,chain:n}=e;return $y({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:I5(e.plugins),source:null,warnings:null})),base:t.base,installed:{...I5(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 Qoe(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 L5(e,t,n,r){let i={cwd:e,chain:t,loaded:n.loaded,sources:Qoe(n.loaded.config,r)};return{kind:`resolved`,...i,key:Zoe(i),warnings:n.warnings}}function R5(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??zK,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new Mw(t.clock),m=new bM(oM,p,o.globals.default_empty_value??``,w$(t.sessionState,()=>t.gates.state.gateFor(o))),h;try{h=xZ(o,m,n,t.compile??bZ(t.links),ese),f.push(...h.loadWarnings);let r=m.view(aM);f.push(...wZ(o,r,n,H5)),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 Ab&&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:Joe(l,u),fileHeldSettings:K$(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>Voe(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,builtins:Bq(zU(o))}}}function z5(e,t,n,r,i){let a={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:Qe(i,e.started)},o=t=>Xoe([...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:F5(r.cause),cause:r.cause}}}function $oe(e,t,n,r,i,a){if(r.kind===`failed`)return z5(e,n,[],r,i.clock);let o=L5(t,n,r,i.storage),s=a?.loadKey===o.key?{kind:`kept`,state:a}:R5(o,i);return z5(e,n,o.warnings,s,i.clock)}function B5({projectDir:e,cwd:t,target:n},r,i=null){let a=r.clock.monotonic(),o=zoe(r.filesystem,{locations:r.locations,stateDir:r.stateDir,projectDir:e,cwd:t,configFile:n.path,memo:r.memo});return $oe({repos:o.repos,advisories:o.advisories,started:a},o.cwd,o.chain,o.parsed,r,i)}function V5(e,t,n){let r={layers:[],home:``,repo:t,locs:n.locations},i=A5(n.filesystem,n.memo,e,r),a=i.kind===`failed`?i:R5(L5(e,r,i,n.storage),n);if(a.kind===`failed`)throw Error(`bundled default failed to load: ${F5(a.cause)}`,{cause:a.cause});return a.state}const ese=new Set([`directory`]),H5=new Set([`view`]);function tse(e,t,n,{facts:r,source:i,changed:a,log:o}){let{sessionId:s}=n,c={builtins:e.builtins,sources:e.sources},l=r.follow(n,c),u=e.registry.view(l.runs),d=X.observable.box({facts:n},{deep:!1}),f=e=>{e!==d.get().facts&&(0,X.runInAction)(()=>{l.follow(e,c),d.set({facts:e})})},p=[],m=()=>(0,X.runInAction)(()=>{for(let e of p)e();let e=u.dispose();return l.dispose(),e});try{wZ(e.config,u,t,H5)}catch(e){throw m(),e}let h;try{h=i({sessionId:s,state:e,store:u.variableStore,declared:()=>d.get(),followed:l,onDispose:e=>p.push(e)})}catch(e){throw m(),e}JX(e.compiled,u.variableStore,u,h);let g=(0,X.reaction)(()=>[h.payload(),h.selections(),u.published()],()=>a(s),{equals:X.compareShallow,fireImmediately:!0,onError:e=>o(`error`,`session view change threw sid=${JSON.stringify(s)}: ${String(e)}`)});return{sessionId:s,state:e,store:u.variableStore,registry:u,source:h,requested:f,facts:()=>d.get().facts,settle:e=>l.settle(e),followed:{stamped:l.stamped,failure:l.failure},lastRenderCellsBySegment:new Map,retire:g,dispose:()=>(g(),m())}}var nse=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,filesystem:e.watchers.filesystem,memo:new dK,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Ie,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},e.watchers.filesystem.mkdirSync(JH(e.stateDir));let{dir:n,name:r}=cj(e.watchers.filesystem,YH(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)??EZ(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){let t=P5(e),n=this.entries.get(t);if(n)return this.entries.delete(t),this.entries.set(t,n),n;let r=this.load(e,null);r.state!==null&&this.log(`info`,M5(r.layers,r.state,r.ms));let i={origin:N5(e),configLayers:[],configHome:``,repos:r.repos,lastError:r.error,lastWarning:r.warning,state:r.state??V5(e.cwd,r.repos.plugins,this.deps),watch:null};return this.serve(i.state),this.entries.set(t,i),this.fit(i),this.log(`info`,`render-cache entry projectDir=${e.projectDir} cwd=${e.cwd} compile=${i.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${P(this.accountedBytes())}/${P(this.budgetBytes())}MB`),this.refreshWatcher(i,r),this.observers.onReload?.(i,[],{kind:`open`},r.kind),i}hold(e){let t=this.getOrCreate(e);return this.holdState(t,t.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){let n=this.hold(e),r,i;try{r=this.viewOf(n.entry,n.state,t,`request`),i=this.leaseOf(r)}catch(e){throw n[Symbol.dispose](),e}return i.read=!0,this.holdViewOf(n,r,i)}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=tse(t,e.origin.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.origin.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){if(this.closed)throw Error(`render cache used after close`);return B5(e,this.deps,t)}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=${P(this.accountedBytes())}/${P(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`,qoe(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){this.reloadInto(this.getOrCreate(e),t)}reloadInto(e,t){let n=this.sessionsOn(e),r=e.state,i=this.load(e.origin,r);e.lastWarning=i.warning,e.lastError=i.error,i.state!==null&&this.log(`info`,M5(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=Yoe(this.deps.watchers.filesystem,e,this.deps.locations),{targets:r,unresolved:i}=n,a=`config:${P5(e.origin)}:${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.origin.projectDir} cwd=${e.origin.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.origin.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)}get installedLayers(){return this.deps.memo}stopDrawing(e,t){this.copies.get(e)?.delete(t)}};const rse=e=>!w0(e)&&!cI(e)&&e!==`update.dismissed`&&e!==MS;var ise=class{past=X.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&&n.verdict(e.key,e.before).kind===`held`))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:l0(e,rse,(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 R(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,X.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,X.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 U5=(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 W5(e,t,n,r,i){let a=(e,t)=>Object.fromEntries([...e].map(([e,n])=>[e,lQ(t?.[e],n,i)])),o=a(Object.entries(n.builtins),e?.builtins),s=a(n.sources,e?.sources),c=Object.fromEntries([...n.runs].map(([t,{reading:n,fault:r}])=>{let a=e?.runs[t],o=lQ(a?.reading,n,i);return[t,a!==void 0&&a.reading===o&&a.fault===r?a:{reading:o,fault:r}]})),l={builtins:o,sources:s,runs:c,update:r,diagnostics:n.faults};return e!==void 0&&U5(o,e.builtins)&&U5(s,e.sources)&&U5(c,e.runs)&&(0,X.compareStructural)({update:r,diagnostics:n.faults},{update:e.update,diagnostics:e.diagnostics})?e:{v:3,session:t,seq:e===void 0?1:e.seq+1,...l}}function ase(e,t,n){let r=Yj(e),i=(0,X.computed)(()=>t().runs[r]),a=(0,X.computed)(()=>{let e=i.get();return e===void 0?n(r):Dq(e.reading)},{equals:X.compareStructural});return{digest:r,current:()=>a.get(),fault:()=>i.get()?.fault??null}}function ose(e,t,n,r){if(t.kind===`failed`)return yo(e,t.reason);try{let i=W5(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 yo(e,`stamping the facts document: ${String(t)}`)}}function sse({providers:e,update:t,runs:n}){let{clock:r,log:i}=e;return{follow(a,o){let s=a.sessionId,c=new sj,l=X.observable.map(void 0,{deep:!1}),u=!1,d=(e,t)=>{if(!l.has(t))return L(`the run of ${Zj(e.read)} is not declared by this view`,`read`);let{failure:n}=y.get();return n===null?So(`unread`):L(`the run of ${Zj(e.read)} is in no document: ${n}`,`read`)},f=JSON.stringify(s),p=(t,n)=>{try{let{result:{lanes:r,faults:a},acquired:o,released:s}=c.declare(()=>Cq(e,c,t,n));for(let e of a)i(`error`,`session view declaration threw sid=${f} ${e}`);return o+s>0&&i(`info`,`session view declared sid=${f} builtins=${Hq(n.builtins)} acquired=${o} released=${s} held=${c.size}`),r}catch(e){return i(`error`,`session view declaration threw sid=${f}: ${O(e)}`),bq(L(`view declaration threw: ${String(e)}`,`read`),n)}},m=X.observable.box({facts:a,lanes:p(a,o)},{deep:!1}),h=(0,X.computed)(()=>{let{facts:t}=m.get();return{hookData:t.hookData,cwd:t.cwd,hints:t.hints,deps:{...e,lanes:()=>m.get().lanes}}}),g=(0,X.computed)(()=>wq(h.get())),_=(0,X.computed)(()=>new Map([...l].map(([e,{run:t}])=>[e,{reading:t.current(),fault:t.fault()}]))),v=(0,X.computed)(()=>({...g.get(),runs:_.get()})),y,b=(0,X.reaction)(()=>{try{return{kind:`read`,readings:v.get(),update:t()}}catch(e){return{kind:`failed`,reason:`reading the owners: ${String(e)}`}}},e=>(0,X.runInAction)(()=>{let t=y.get(),n=ose(t,e,st(r),s);n.failure!==null&&n!==t&&i(`error`,`session facts sid=${f}: ${n.failure}`),y.set(n)}),{onError:e=>i(`error`,`session facts threw sid=${f}: ${O(e)}`)});try{let e=st(r);y=X.observable.box({line:{at:e,facts:W5(void 0,s,v.get(),t(),e)},failure:null},{deep:!1})}catch(e){throw b(),c.close(),e}return{runs:{declare:(e,t)=>{if(u)throw Error(`the run of ${Zj(t.read)} was declared after its view's follow was disposed`);let r=Yj(t);return e.take(`facts.run:${r}`,()=>{let e=new sj,i=n.declare(e,t),a=ase(t,()=>y.get().line.facts,e=>d(t,e));return(0,X.runInAction)(()=>l.set(r,{run:i,held:e,lane:a})),()=>{(0,X.runInAction)(()=>l.delete(r)),e.close()}}),l.get(r).lane}},stamped:()=>y.get().line,failure:()=>y.get().failure,follow:(e,t)=>{let n=p(e,t);(0,X.runInAction)(()=>m.set({facts:e,lanes:n}))},settle:e=>{let t=new Map;return{refreshed:t,landed:Yq(h.get(),e,t)}},dispose:()=>{u=!0,b();for(let{held:e}of l.values())e.close();c.close()}}}}}function G5(e,t){return e===t||e?.cause===t?.cause&&e?.reason===t?.reason}function cse(e,t,n){if(t.kind===`failed`){let n={cause:`inputs`,reason:t.reason};return G5(e.failure,n)?e:{...e,failure:n}}let r=t.facts===null?null:{cause:`facts`,reason:t.facts};return G5(e.failure,r)&&t.stamped===e.stamped&&t.request===e.request&&t.compose===e.compose&&t.draw===e.draw?e:{stamped:t.stamped,request:t.request,picks:n(),compose:t.compose,draw:t.draw,failure:r}}function lse(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`,()=>cJ(n.config,s,e=>n.authoredRoots.has(e))),l=r.derive(`session.foreign`,`computed`,()=>{let r=e.stateGates.gateFor(n.config);return Object.entries(e.sessionState.values(t)).flatMap(([e,t])=>{let n=r.verdict(e,t);return n.kind===`foreign`?[{key:e,held:t,admits:n.admits}]:[]})}),u=r.derive(`session.compose`,`computed`,()=>{let{facts:t}=i();return{hookData:t.hookData,hints:t.hints,home:e.providers.home}}),d=r.derive(`session.draw`,`computed`,()=>({effective:c.read(),configFacts:{...q$(n.config,n.fileHeldSettings,s),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})),f=()=>({values:e.sessionState.values(t),revision:e.sessionState.revision(t)}),p=a.failure(),m=X.observable.box({stamped:a.stamped(),request:i().facts,picks:f(),compose:u.read(),draw:d.read(),failure:p===null?null:{cause:`facts`,reason:p}},{deep:!1});o((0,X.reaction)(()=>{try{return{kind:`read`,stamped:a.stamped(),facts:a.failure(),request:i().facts,compose:u.read(),draw:d.read()}}catch(e){return{kind:`failed`,reason:`reading the turn's inputs: ${String(e)}`}}},n=>(0,X.runInAction)(()=>{let r=m.get(),i=cse(r,n,f);n.kind===`failed`&&i!==r&&e.providers.log(`error`,`session turn sid=${JSON.stringify(t)}: ${n.reason}`),m.set(i)}),{onError:n=>e.providers.log(`error`,`session turn threw sid=${JSON.stringify(t)}: ${String(n)}`)}));let h=r.derive(`session.payload`,`computed`,()=>{let{stamped:e,compose:t,draw:n}=m.get();return Vq(e.facts,t,n)});return{payload:()=>h.read(),effective:()=>m.get().draw.effective,foreign:()=>l.read(),facts:()=>m.get().stamped.facts,turn:()=>{let{stamped:e,request:t,picks:n,draw:r}=m.get();return{document:e,request:t,state:{...n,history:r.history,back:r.back}}},held:()=>m.get().failure?.cause===`inputs`,home:()=>m.get().compose.home,hints:()=>m.get().compose.hints,failure:()=>m.get().failure,selections:()=>m.get().draw.effective,state:()=>({values:e.sessionState.values(t),revision:e.sessionState.revision(t),history:m.get().draw.history,back:m.get().draw.back})}}}const use=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function K5(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?use[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const dse={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 fse({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=K5(t),o=K5(n),s={};for(let e of r){let t=dse[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 pse(e){return{ok:!0,band:e.rows.map(e=>lF(e).map(fse))}}function mse(e){return aF(pse,e)}const hse=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function q5(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:hse[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 gse={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 _se(e){return e.replaceAll(`#`,`##`)}function vse({fg:e,bg:t,attrs:n=[]}){let r=n.map(e=>{let t=gse[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${q5(e)}`,`bg=${q5(t)}`,...r].join(`,`)}]`}function yse(e,t){let n={},r=e=>{let r=vse(e)+_se(e.text);if(e.link===void 0)return r;let i=t(e.link);return i===null?r:(n[i]=e.link,`#[range=user|${i}]${r}#[norange]`)};return{rows:e.rows.map(e=>lF(e).map(r).join(``)),links:n}}function bse(e,t){return t.frame(t=>aF(e=>yse(e,t),e))}var xse=class{ranges=new Map;constructor(e,t=256){this.source=e,this.cap=t}frame(e){let t=new Set,n=e(e=>(t.add(e),this.rangeOf(e)));for(let e of this.ranges.keys()){if(this.ranges.size<=this.cap||t.has(e))break;this.ranges.delete(e),this.source.evicted()}return n}rangeOf(e){let t=this.ranges.get(e);if(t!==void 0)return this.ranges.delete(e),this.ranges.set(e,t),this.source.reused(),t;let n=this.source.next();if(n===null)return null;let r=`ccb`+n.toString(36);return this.ranges.set(e,r),r}};function Sse(e){return{band:()=>e=>({json:JSON.stringify(mse(e)),value:null}),statusline:()=>(e,t)=>({json:t,value:null}),pane:()=>(e,t)=>({json:t,value:null}),tmuxStatus:()=>{let t=new xse(e);return e=>{let n=bse(e,t);return{json:JSON.stringify({ok:!0,tmuxStatus:n}),value:n}}}}}const Cse=/^\d{1,15}\n?$/,wse=10**15-1,J5=`remove it and a new one is made, starting again from 0 (a click on a status row drawn before then may run a link drawn since)`;function Tse(e){let{file:t,clock:n,retryMs:r,log:i}=e,a=0,o={kind:`ready`,next:0},s=0,c=0,l=0,u=0,d=0,f=()=>{try{let e=Math.max(Ese(t),a),n=e+1024;if(n>wse)throw Error(`${t} holds ${e}, too near the last count for another block: ${J5}`);return wr(t,`${n}\n`,384),a=n,u++,o.kind===`faulted`&&i(`info`,`link ids: ${t} reserved again`),{kind:`ready`,next:e}}catch(e){d++;let t=`link ids: ${e.message}`;return(o.kind!==`faulted`||o.reason!==t)&&i(`error`,t),{kind:`faulted`,reason:t,clear:n.after(r,()=>o=f(),{unref:!0})}}};return{next(){return o.kind===`ready`&&o.next===a&&(o=f()),o.kind===`ready`?(s++,o.next++):null},reused:()=>void c++,evicted:()=>void l++,error:()=>o.kind===`faulted`?o.reason:null,stats:()=>({minted:s,reused:c,evicted:l,reservations:u,faults:d}),close(){o.kind===`faulted`&&o.clear(),o={kind:`closed`}}}}function Ese(e){let t;try{t=m.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return 0;throw e}if(!Cse.test(t))throw Error(`${e} holds ${JSON.stringify(t.slice(0,40))}, not a count: ${J5}`);return Number(t.trim())}const Y5=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,X5=`#{session_id} #{client_control_mode} #{pane_id}`;function Z5(e){let t=new Set;for(let n of e.split(`
498
+ `);function L6(e,t){let{tmux:n,claudeConfigDir:r,terminalEnv:i,ssh:a}=j6({sessionState:e},t);return{tmux:n,claudeConfigDir:r,terminalEnv:i,ssh:a}}async function R6(e,t,n,r){let i=new Map,a={...e,sessionState:P6(e.sessionState,i)},o=e=>JSON.stringify(L6(e,t)),s=L6(e.sessionState,t);i.set(`hints`,{what:y$,value:JSON.stringify(s),again:o});let c=r.loadConfig(i6(a,t)),l={kind:`clicked`,sessionId:t,via:n.via},u=e.clients.ofSession(t,e.now()),d;try{d=await i3({...r,loadConfig:()=>c},s,i6(a,t),e=>a.sessionState.get(t,e),{kind:`ok`,value:e.serving()},{kind:`ok`,value:u.map(e=>e.rateLimits)},{kind:`ok`,value:u.map(e=>e.transcript)},l,{kind:`ok`,value:u2(l,u)},r3(t,u),A4(e.doctorStores))}catch(e){throw e instanceof o2?new R(e.message):e}return{facts:d,install:O4(r.install,e.bundle,u.map(e=>e.client)),stamp:{load:c,reads:[...i.values()]}}}async function z6(e,t){let n=j4(e.doctor),r=t.session;return e.journalTurns.gathering(async()=>{let i=await R6(e,r,t.arrival,n);return F6(e,r,i.stamp)===null?i:R6(e,r,t.arrival,n)})}function B6(e,t,n,{facts:r,install:i}){let a=A4(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:e3(n),install:i,clicked:V6(e,n,o)}}function V6(e,t,{terminal:n,clicked:r}){let i=n.kind===`seen`?jF(n.identified):null;if(i===null||t.via!==`link`)return r;try{return e.doctorStores.clicked.update(e=>i2(e,i))}catch(t){return e.log(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(i)}: ${t instanceof Error?t.message:String(t)}`),r}}const H6={run:(e,t,n,r)=>M6(e,t,r),fix:(e,t,{check:n},r)=>{let i=n.probe(r);if(i.ok||i.fix===void 0)throw new R(`doctor-fix: ${n.label} — ${i.ok?`nothing to fix`:i.reason}`);let a=a3(e.doctorStores,i.fix,r);if(a.kind===`failed`)throw new R(`doctor-fix: ${n.label} — ${a.reason}`);e.log(`info`,`doctor-fix: ${n.name} → ${cre(i.fix)} (session=${t})`),M6(e,t,a.value)},mark:(e,t,{check:n,mark:r},i)=>{let a=n.probe(i);if(a.ok||a.sighting===void 0)throw new R(`doctor-mark: ${n.label} — ${a.ok?`nothing to mark`:`shows nothing to look at`}`);let o=e.doctorStores.marks.update(e=>t2(e,n.name,a.sighting.id,r));if(o.kind===`failed`)throw new R(`doctor-mark: ${o.reason}`);e.log(`info`,`doctor-mark: ${n.name} ${r} on ${a.sighting.id} (session=${t})`),M6(e,t,{...i,marks:o})}};function U6(e,t,n){let r=t.session,i=F6(e,r,n.stamp);if(i!==null)throw new R(`doctor: the session's ${i} changed during the doctor's probes — click again`);W6(e,r,t.step,B6(e,r,t.arrival,n))}function W6(e,t,n,r){let i=H6[n.kind];i(e,t,n,r)}const G6=(e,t,n)=>{N6(n,e,{kind:`run`})},K6=(e,t)=>{if(!e.ok)throw new R(`probe: ${e.problem}`);let n=e.value;if(t.arrival.via!==`link`)throw new R(`probe: a probe arrives only as a link`);let{delivery:r}=t.arrival;t.probes.arrive({nonce:n,delivery:r}),t.log(`info`,`probe: arrived nonce=${n} delivery=${r.kind}`)},q6=(e,t,n)=>{let[r=``]=t,i=nI(r);if(i===void 0)throw new R(`doctor-fix: unknown check "${r}"`);N6(n,e,{kind:`fix`,check:i})},J6=(e,t,n)=>{let[r=``,i=``]=t,a=nI(r);if(a===void 0)throw new R(`doctor-mark: unknown check "${r}"`);if(!FF.includes(i))throw new R(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${FF.join(` or `)}`);N6(n,e,{kind:`mark`,check:a,mark:i})},Y6=(e,t,n)=>{let[r=``]=t,i=Object.values(n.configFor(i6(n,e)).actions).filter(e=>`slash`in e),a=i.find(e=>e.slash===r);if(a===void 0)throw new R(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(i.map(e=>e.slash))].join(`, `)||`none`})`);let o=l$(j6(n,e).tmux);if(o.kind===`refused`)throw new R(`${r} was not typed: ${o.reason}`);n.effect({kind:`type-slash`,pane:o.hint,line:a.slash})};function X6(e,[t=``,n=``,r=``],i){let a=i6(i,e),o=i.configFor(a).actions,s=Object.hasOwn(o,t)?o[t]:void 0;if(s===void 0||!(`run`in s))throw new R(`"${t}" is not a run action this session's config declares`);let c=_S(s);if(!i.links.signer.verify({sessionId:e,action:t,declaration:c,evaluated:n},r))throw new R(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let l;try{l=JSON.parse(n)}catch{throw new R(`run ${t}: what the link carries is not JSON`)}let[u,...d]=l.run;if(u===void 0||u===``)throw new R(`run ${t}: the program evaluated to nothing`);let f=i.sourcesFor(a);return{sessionId:e,action:t,argv:[u,...d],envOverlay:{...Q0({sessionId:e,projectDir:a.projectDir,claudeConfigDir:j6(i,e).claudeConfigDir}),...l.env},cwd:s.cwd??i.locations.homeDir,refreshes:s.refreshes.map(e=>({name:e,storage:f.get(e)}))}}const Z6=new Map([[IS,U3,[1,1]],[LS,q3,[1,1]],[PS,Y3,[0,1/0]],[FS,Q3,[2,2]],[zS,m6,[2,2]],[BS,h6,[2,2]],[GS,S6,[0,1/0]],[VS,g6,[0,0]],[HS,y6,[0,0]],[US,b6,[0,0]],[WS,x6,[1,1]],[KS,T6,[2,2]],[qS,E6,[0,0]],[JS,k6,[0,0]],[YS,D6,[0,0]],[XS,O6,[0,0]],[RS,J3,[0,0]],[ZS,A6,[0,0]],[QS,G6,[0,0]],[$S,q6,[1,1]],[eC,J6,[2,2]],[rC,Y6,[1,1]],[`run`,(e,t,n)=>{let r=X6(e,t,n);n.effect({kind:`run`,id:n.runs.superseded(r),run:r})},[3,3]],[iC,(e,t,n)=>{let[r=``,i=``,a=``]=t,o=i;if(!n.links.signer.verify(EU(e,r,o),a))throw new R(`the answer's signature does not match what it carries: it was not drawn by this daemon`);let s=TU(n.filesystem,n.stateDir,r,o);if(s.kind===`failed`)throw Error(`${r} was not ${o}: ${s.reason}`);n.journal.wrote();let{superseded:c,absent:l,unchecked:u}=s.value;n.log(`info`,`repo-config: ${r} ${o} superseded=${c.join(`,`)||`-`} absent=${l.join(`,`)||`-`} unchecked=${u.length===0?`-`:JSON.stringify(u)} (session=${e})`),n.reloadConfig(i6(n,e))},[3,3]],[aC,K3,[2,2]]].map(([e,t,n])=>[e,{handler:t,takes:n}]));new Set(Z6.keys());function Q6(e,t,n){let[r=``,...i]=n.split(`/`);return{verb:e,leaf:t,session:$6(r),args:fc(()=>i.map(decodeURIComponent))}}function $6(e){let t=fc(()=>decodeURIComponent(e));return t.ok?_Q(t.value):{ok:!1,problem:`has ${t.problem}`}}function e8({verb:e,value:t}){let n=Z6.get(e);return n===void 0?{verb:e,leaf:n}:Q6(e,n,t)}function t8(e){return e.find(e=>e.leaf!==void 0)?.session??null}function n8(e,t){return`${e}: ${t}`}function $re(e){return`unknown effect verb "${e}"`}function r8(e,t){return{kind:`refused`,reason:t,problem:n8(e,t)}}function eie(e){let t=$re(e);return{kind:`refused`,reason:t,problem:t}}function i8({verb:e},t,n){return{ok:!1,verb:e,args:t,refusal:r8(e,n)}}function tie(e,t){if(e.leaf===void 0)return{ok:!1,verb:e.verb,args:[],refusal:eie(e.verb)};let{verb:n,leaf:r,session:i,args:a}=e,o=a.ok?a.value:[];if(!i.ok)return i8(e,o,`session id ${i.problem}`);if(!t?.ok)return i8(e,o,`its click's own session is refused, so no step of it runs`);if(t.id!==i.id)return i8(e,o,`names session ${i.id}, not the session its click is in`);if(!a.ok)return i8(e,o,a.problem);let[s,c]=r.takes;return a.value.length<s||a.value.length>c?i8(e,o,`reads ${s===c?s:`${s} to ${c}`} after its session, and the link carries ${a.value.length}`):{ok:!0,verb:n,leaf:r,sid:i.id,args:a.value}}function nie(e){let t=fc(()=>decodeURIComponent(e));if(!t.ok)return t;let n=k3(t.value);return n===null?{ok:!1,problem:`the value is not a probe nonce`}:{ok:!0,value:n}}const rie={[NS]:e=>{let t=hC(pC(e)).map(e8),n=t8(t);return{kind:NS,steps:t.map(e=>tie(e,n)),session:n}},[tC]:e=>({kind:tC,nonce:nie(e)})};function iie(e,t){return Tte(e)?rie[e](t):null}function a8(e){return e.kind===`dispatch`&&e.session?.ok?e.session.id:null}function aie(e,t){let n=[];try{e.leaf.handler(e.sid,e.args,{...t,effect:e=>void n.push(e)})}catch(t){let n=t instanceof Error?t.message:String(t);return t instanceof R?r8(e.verb,n):{kind:`failed`,problem:n8(e.verb,n)}}for(let e of n)t.effect(e);return{kind:`ran`}}const oie=new Map([[`run`,(e,{sid:t,args:[n],reason:r})=>e.runs.refused(t,n||`-`,r)]]);function sie(e,t,n){let r=[],i=!1;for(let a of e){let e=a.ok?aie(a,n):a.refusal;e.kind!==`ran`&&(e.kind===`refused`?oie.get(a.verb)?.(n,{sid:t?.ok?t.id:`-`,args:a.args,reason:e.reason}):i=!0,r.push(e.problem))}if(r.length>0){t?.ok&&qZ(n.sessionState,t.id,r.join(`
499
+ `),n.now());let e=`dispatch: ${r.join(`; `)}`;throw i?Error(e):new R(e)}}function cie(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}function o8(e,t,n){let r=e===null?null:u6(t,e),i=t.history.begin(),a=t.navigation.begin(i.sessionState),o=[],s=e=>a1(e,e=>c6(t,e),e=>d6(t,e),e=>t.log(`info`,e)),c=[];try{n({...t,sessionState:s(i.sessionState),journal:i,navigating:s(a.sessionState),effect:e=>void c.push(e)})}catch(e){o.push(e)}for(let e of[a,i])try{e.commit()}catch(e){o.push(e)}if(r!==null)try{let e=r.read();c.push(...t.lanes.clicked(r.sessionId,i.written()?r.before:e,e))}catch(e){o.push(e)}t.described(c),cie(o)}function lie(e,t){if(t.gone())throw new dc(NS);let n=a8(e);t.journalTurns.take(NS,()=>o8(n,t,r=>{try{sie(e.steps,e.session,r)}finally{n!==null&&t.clickLanded(n)}}))}function uie(e,t){switch(e.kind){case NS:return lie(e,t);case tC:return K6(e.nonce,t);default:return e}}function die(e,t,n){n.journalTurns.take(`menu-idle`,()=>o8(e,n,n=>{if(!t.stillIdle()){n.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}t.closed();let r=c6(n,n.navigating),i=i1(d6(n,e),t=>r.get(e,t));n.navigating.setBatch(e,i.map(({key:e})=>({key:e,value:ma}))),n.log(`info`,`menu-idle: closed=${i.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)}))}const s8=[],fie={request:({req:e,arrived:t,facts:n},{verbCtx:r})=>{let i=r.journalTurns.take(`request`,()=>{hie(r.sessionState,e);let n=r.mismatchRuns.record(e.sessionId,e.pane,t);return{effects:r.lanes.arrived(e),revision:r.sessionState.revision(e.sessionId),mismatch:n}});return iQ(n,{revision:String(i.revision),effects:i.effects.map(e=>_$(e)).join(`,`)||`-`,mismatch:C$(i.mismatch,t)}),{answer:void 0,effects:i.effects,facts:[]}},click:({click:e,arrival:t,gone:n},{verbCtx:r})=>{let i=[],a=null;try{uie(e,{...r,arrival:t,gone:n,described:e=>void i.push(...e)})}catch(e){a={error:e}}return{answer:a,effects:i,facts:[]}},"menu-idle":({session:e,idle:t},{verbCtx:n})=>{let r=[];return die(e,t,{...n,described:e=>void r.push(...e)}),{answer:void 0,effects:r,facts:[]}},"effect-done":({of:e,done:t},n)=>{let{verbCtx:r}=n;return{answer:r.journalTurns.take(`effect-done`,()=>{let i=mie(t,n);return i.kind===`failed`&&e.session!==null&&qZ(r.sessionState,e.session,i.said,r.now()),i}),effects:s8,facts:[]}},answered:({session:e,errors:t},{verbCtx:n})=>(n.journalTurns.take(`answered`,()=>JZ(n.sessionState,e,t)),{answer:void 0,effects:s8,facts:[]})},c8=({outcome:e})=>e,pie={launch:c8,"type-slash":c8,"apply-update":c8,run:c8,"lane-setup":c8,doctor:({effect:e,outcome:t},n)=>t.kind===`failed`?t:(U6(n,e,t.gathered),cc)};function mie(e,t){let n=pie[e.effect.kind];try{return n(e,t.verbCtx)}catch(n){return l8(e.effect,n,t.log)}}function l8(e,t,n){return t instanceof R||t instanceof uc||n(`error`,`apply: ${_$(e)} threw: ${O(t)}`),lc(t instanceof Error?t.message:String(t))}function hie(e,t){let{client:n,configEnv:r,...i}=t.hints,a=[{key:y$,value:JSON.stringify(i)},{key:v$,value:t.originRecord}];e.setBatch(t.sessionId,a.filter(({key:n,value:r})=>e.get(t.sessionId,n)!==r))}async function u8(e,t){let n=fie[e.kind],r=n(e,t),i=xie(e),a=yie[e.kind],o=a(e,r);return o!==null&&t.log(o.level,cQ(`apply`,[[`kind`,e.kind],[`verb`,i.verb],[`sid`,i.session??`-`],...o.facts,...r.facts,[`effects`,r.effects.map(e=>_$(e)).join(`,`)||`-`],[`revision`,i.session===null?`-`:String(t.verbCtx.sessionState.revision(i.session))]])),{answer:r.answer,performed:r.effects.length===0?d8:Die(t,i,r.effects)}}const d8=Promise.resolve();async function gie(e,t){return await u8(e,t),t.draw(e.req,e.at,e.waitEndsAt,e.facts)}const f8={level:`info`,facts:[[`outcome`,`ok`]]},_ie=({error:e})=>({level:`info`,facts:[[`outcome`,`refused`],[`said`,e instanceof Error?e.message:String(e)]]}),vie={ok:`info`,failed:`warn`},yie={request:()=>null,click:(e,{answer:t})=>t===null?f8:_ie(t),"menu-idle":()=>f8,answered:()=>f8,"effect-done":({done:e},{answer:t})=>({level:vie[t.kind],facts:[[`effect`,_$(e.effect)],[`outcome`,t.kind],[`said`,t.said||`-`]]})},bie={request:({req:e})=>({verb:`request`,session:e.sessionId}),click:({click:e})=>({verb:e.kind,session:a8(e)}),"menu-idle":({session:e})=>({verb:`menu-idle`,session:e}),"effect-done":({of:e})=>e,answered:({session:e})=>({verb:`answered`,session:e})};function p8(e,t,n,r){e(r instanceof uc?`info`:`error`,`apply: ${t} not applied (${n}): ${O(r)}`)}function m8(e,t,n){return u8(e,t).then(()=>void 0,r=>p8(t.log,e.kind,n,r))}function xie(e){let t=bie[e.kind];return t(e)}const Sie={launch:({spec:e,what:t},{verbCtx:n})=>Cie(n.launcher,e,t),"type-slash":async({pane:e,line:t},{verbCtx:n})=>{let r=await u$(n.claudeInput,e,t);return r.kind===`typed`?{kind:`ok`,said:`typed into ${r.pane}`}:lc(`${t} was not typed: ${r.reason}`)},"apply-update":async(e,{verbCtx:t})=>(await t.applyUpdate(),cc),run:({id:e,run:t},{verbCtx:n})=>n.runs.run(e,t),"lane-setup":(e,{verbCtx:t})=>t.lanes.setup(e),doctor:async(e,{verbCtx:t})=>({kind:`gathered`,gathered:await z6(t,e)})};async function Cie(e,t,n){let r=await e.launch({...t,timeoutMs:R3});return r.ok?cc:lc(`${n} failed (${gt(r)})`)}async function wie(e,t){let n=Sie[e.kind],r;try{r=await n(e,t)}catch(n){r=l8(e,n,t.log)}return{effect:e,outcome:r}}const h8={launch:{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1},"type-slash":{key:({pane:e})=>({kind:`pane`,tmux:e}),paneWhenReached:!1},"apply-update":{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1},run:{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1},"lane-setup":{key:({sessionId:e,lane:t})=>({kind:`lane`,session:e,lane:t}),paneWhenReached:!0},doctor:{key:(e,{session:t})=>({kind:`session`,session:t}),paneWhenReached:!1}};function Tie(e,t){return h8[e.kind].key(e,t)}function Eie(e,t,n,r){let i=e=>h8[e.kind].paneWhenReached,a=[...n.filter(e=>!i(e)),...n.filter(i)],o=d8;for(let n of a){let i=o;o=e.performing(Tie(n,t),async()=>{await i,await r(n)})}return o}function Die(e,t,n){return Eie(e.verbCtx.journalTurns,t,n,async n=>{let r=await wie(n,e);await m8({kind:`effect-done`,of:t,done:r},e,`${_$(n)} ${r.outcome.kind}${`said`in r.outcome?`: ${r.outcome.said}`:``}`)})}function Oie({projectDir:e,cwd:t,target:n},r){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path===void 0?null:v0(r,n.path),source:n.source})}function kie(e,t,n){let{tokens:r}=k({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:EP(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function Aie(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=jr.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${jr.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function jie(e,t,n,r,i,a){let{report:o}=pQ(e.hookData),s=[];for(let e of o.missingRequired)s.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of o.typeMismatches)s.push(`field '${e}' expected ${t}, got ${n}`);let c=_Q(e.hookData?.session_id);c.ok||s.push(`field 'session_id' ${c.problem}`),(typeof e.cwd!=`string`||!u(e.cwd))&&s.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&s.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let l=Aie(e.encoding);l.ok||s.push(l.problem);let d=di(e.deadline);if(d.kind===`refused`)return{ok:!1,problems:[...s,d.problem]};if(s.length>0||!c.ok||!l.ok)return{ok:!1,problems:s};for(let e of o.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let f=Nr(e),{configFile:p,refusedArgs:m}=kie(e.args,e.cwd,r),h=f0(i),g=kP(p,f.configEnv),_={projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:g.source===`search`?g:{...g,path:x0(h,g.path)}};return{ok:!0,req:{...e,deadline:d,encoding:l.encoding,sessionId:c.id,hints:f,rateLimits:qne(e.hookData),requested:_,originRecord:Oie(_,h),refusedArgs:m,pane:cl(f,c.id,a)}}}function Mie(e,t){switch(e){case`vars`:return{what:e,vars:Nie(t)};case`segments`:return{what:e,segments:Lie(t)};case`config`:return{what:e,config:Vie(t)}}}function Nie(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=Iie(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=Pie(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:Fie(r.lastUpdatedMs(),t.clock)})}return o}function Pie(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 Fie(e,t){return e===null?null:Math.max(0,t.now()-e)}function Iie(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,g8(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}`,g8(i));return t}function g8(e){return e.kind}function Lie(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=zie(n),o=Rie(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:Bie(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function Rie(e){let t=new Map;for(let n of nS(e.presets))for(let r of ob(aS(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=nb(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function zie(e){let t=[],n=new Set;for(let r of ob(Wx(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 Bie(e,t,n){let r=new Set([...HC(e,t).keys()].flatMap(e=>aw(e,n)));return Array.from(r).sort()}function Vie(e){return e===null?null:e.config}const _8=[`vars`,`segments`,`config`];function Hie(e){return typeof e==`string`&&_8.includes(e)}const v8=e=>({resp:e,exitAfterFlush:null,delivered:NQ}),y8=e=>({kind:`reply`,...e}),Uie={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},b8=(e,t)=>y8(v8({ok:!1,error:t,code:e,daemonV:3}));function Wie(e){let t=_Q(e.sessionId);if(!t.ok)return b8(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return b8(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Qc.join(`, `)}): it predates the lane toggles — update it`);let n=ol(e.lane);return n===null?b8(`BAD_REQUEST`,`subscribe needs a lane, one of ${Qc.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}function Gie(e){let{session:t,path:n,seconds:r}=e,i=_Q(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=Jr(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 Kie(e,t){let n=Gie(t);if(!n.ok)return b8(`BAD_REQUEST`,n.problem);let{session:r,path:i,seconds:a}=n;return{kind:`held`,start:t=>MQ(e.recorder,e.clock,r,i,a,t).then(e=>v8({ok:!0,recorded:e}),e=>v8({ok:!1,error:e instanceof Error?e.message:String(e),code:e instanceof jQ?`RENDER_FAILED`:`BAD_REQUEST`,daemonV:3}))}}function qie(e,t,n){return e.v===n?null:(e.v>n?t(`info`,`version mismatch: client=${e.v} > daemon=${n}; binary likely upgraded — exiting after the response flushes`):t(`info`,`version mismatch: client=${e.v} < daemon=${n}; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v${n})`,code:`VERSION_MISMATCH`,daemonV:n},exitAfterFlush:e.v>n?0:null,delivered:NQ})}async function Jie(e,t,n,r,i){if(t.kind===`url`)return y8(v8(await eae(e,t.frame,n,r,i)));let a=t.req;if(!a||typeof a!=`object`||typeof a.v!=`number`)return b8(`BAD_REQUEST`,`malformed request`);let o=qie(a,e.log,3);return o===null?a.kind===`subscribe`?Wie(a):a.kind===`record`?Kie(e,a):typeof a.kind!=`string`||!Object.hasOwn(Uie,a.kind)?b8(`BAD_REQUEST`,`unknown kind`):y8(await x8(e,a,n,r,i)):o}async function x8(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:w}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:NQ};if(t.kind===`pane-session`){let{socket:n,pane:r}=t;return v8(typeof n!=`string`||typeof r!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:s.newestWhere(ll({socket:n,pane:r},e.heldSession))})}if(t.kind===`stats`)return v8({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:Yie(e),fileEvents:d.stats(),sourceRuns:p.stats(),runs:f.stats(),transcriptReads:Io(),renderCache:c.stats,effectCache:m.getStats(),menuIdle:h.getStats(),journalTurns:g.getStats(),sessionState:{sessions:e.sessionState.size(),observers:e.sessionState.observers(),revision:e.sessionState.latestRevision()},frameFeeds:s.getStats(),tmuxStatus:_.stats(),linkIds:e.linkIds.stats(),watchersActive:v.size(),dirWatchesActive:v.dirWatches(),dirsPolled:v.polledDirs(),nextRestartReason:y.describeNextRestart(),handlerProbes:b.list(),clients:x.list(it(new Date(o.now()))),bundle:S,sourceDigest:C,daemon:y.serving(),doctorStores:A4(w)})});if(t.kind===`render`){let c=new Date(o.now()),l=it(c),u=o.monotonic(),d=Ze(r,u),f=[],p=++a.requestsTotal,m=jie(t,a,e.log,e.home,e.storedRoot,e.heldSession),h=(t,n)=>x.see(t.sessionId,{client:t.hints.client??null,termCols:t.hints.termCols??null,rateLimits:t.rateLimits,claudeConfigDir:qo(t.hints.claudeConfigDir,e.home),projectDir:t.requested.projectDir,transcript:Jne(t.hookData),frame:n},l,p);m.ok&&(iQ(f,{sid:m.req.sessionId}),h(m.req,`drawing`),s.note(m.req.sessionId,m.req,p));let g=m.ok?await gie({kind:`request`,req:m.req,at:l,arrived:r,waitEndsAt:Xe(u,fi(m.req.deadline,r,{epochMs:c.getTime(),monoMs:u})),facts:f},e).then(({resp:t,motion:n,answersClick:r,pipeShown:i,delivered:a})=>(h(m.req,n),{outcome:{kind:`ok`},resp:t,delivered:()=>{a(),r.length>0&&m8({kind:`answered`,session:m.req.sessionId,errors:r},e,`sid=${m.req.sessionId}`),i!==null&&e.launcher.answeredPipeEvent(i)}}),e=>(h(m.req,`failed`),{outcome:w8(e),resp:PQ(e),delivered:NQ})):sae(m.problems);g.outcome.kind!==`ok`&&a.requestsErrored++,iQ(f,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:_,line:v}=sQ(`render`,f,g.outcome,Qe(o,u));return e.log(_,v),{resp:g.resp,exitAfterFlush:null,delivered:g.delivered}}if(t.kind===`click`)return v8(await S8(e,r,n,i,(n,r)=>$ie(e,t,n,r)));if(t.kind===`debug`){if(!Hie(t.what))return v8({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${_8.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`?Qie(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??gx(`colorCompatibility`)):Zie};return v8({ok:!0,debug:Mie(t.what,n)})}throw Error(`no reply for request ${O(t)}`)}function Yie(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 Xie={endcaps:gx(`endcaps`),colorCompatibility:gx(`colorCompatibility`),wrap:gx(`autoWrap`),padding:gx(`padding`),width:1/0},Zie=new Map;function Qie(e,t){let n=new Map;for(let[r,i]of e)n.set(r,Une(i,{...Xie,colorCompatibility:t}));return n}async function S8(e,t,n,r,i){let{clock:a}=e,o=a.monotonic(),s=[[`queued`,`${Ze(t,o)}ms`]],c=await i(s,()=>n()||r());iQ(s,{timedOut:n()?`Y`:`N`,clientLeft:r()?`Y`:`N`});let{level:l,line:u}=sQ(`click`,s,c,Qe(a,o));return e.log(l,u),aae(c)}async function $ie(e,t,n,r){let i={via:`link`,delivery:{kind:`cli`}};iQ(n,{via:`cli`});let{url:a}=t;return typeof a==`string`?C8(()=>T8(e,a,i,n,r)):{kind:`bad-request`,problems:[`a click's link is a string, got ${typeof a}`]}}async function eae(e,t,n,r,i){return S8(e,r,n,i,async(n,r)=>{let{urlV:i,url:a}=t;if(iQ(n,{via:`forwarder`,urlV:String(i)}),typeof i!=`number`||!Gr.has(i))return{kind:`bad-request`,problems:[`the URL handler's frame version ${O(i)} is not one this daemon speaks (${[...Gr].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 C8(()=>T8(e,a,o,n,r))})}async function C8(e){try{return await e()}catch(e){return tae(e)}}function tae(e){return e instanceof R?{kind:`bad-request`,problems:[e.message]}:e instanceof dc?{kind:`abandoned`,error:e}:w8(e)}function w8(e){return e instanceof uc?{kind:`closing`,error:e}:{kind:`threw`,error:e}}const nae={link:`to`,"tmux-status":`linkTo`},rae={link:`verb`,"tmux-status":`linkVerb`};async function T8(e,t,n,r,i){let a=vC(t);if(!a.ok)return{kind:`bad-request`,problems:[a.problem]};iQ(r,{[nae[n.via]]:a.to});let o=e.links.to;return a.to===o?iae(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 iae(e,t,n,r,i,a){if(t===`range`)return r.via===`tmux-status`?{kind:`bad-request`,problems:[`a status-line link names another status-line click`]}:(iQ(i,{verb:t}),oae(e,n,i,a));let o=iie(t,n);if(o===null)return{kind:`bad-request`,problems:[`unknown click verb: ${t}`]};iQ(i,{[rae[r.via]]:t}),iQ(i,{sid:a8(o)??`-`});let{answer:s}=await u8({kind:`click`,click:o,arrival:r,gone:a},e);if(s!==null)throw s.error;return{kind:`ok`}}function aae(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 PQ(e.error)}}async function oae(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):(iQ(r,{link:s.url}),pa(s.url)?T8(e,s.url,{via:`tmux-status`},r,i):(await B3(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,R3,e.tmp),{kind:`ok`}))}const sae=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:NQ});function cae(e,t){let n=ae(`sha256`).update(t).digest(`hex`).slice(0,16);return s.join(e,`update-act`,n)}const lae=e=>({spentMs:0,lastSeen:e.started}),uae=(e,t,n)=>n===null?t??lae(e):t===null||n.spentMs>t.spentMs||n.spentMs===t.spentMs&&n.lastSeen>t.lastSeen?n:t,dae=(e,t,n)=>{let r=t-e.lastSeen;return{spentMs:e.spentMs+(r>=0&&r<=n?r:0),lastSeen:t}},E8={kind:`idle`};function D8(e){if(e===null)return E8;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 O8=e=>({stdout:s.join(e,`stdout`),stderr:s.join(e,`stderr`),status:s.join(e,`status`)}),k8=e=>s.join(e,`record.json`),fae=e=>s.join(e,`awake.json`);function A8(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 j8(e){let t=Wo(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 M8(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})}async function pae(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 N8(e){try{return m.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function mae(e){let t=N8(k8(e));return t===null?null:JSON.parse(t)}const hae=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function gae(e,t,n,r){let i=null;async function a(a){let o=s.join(e,String(a)),c=mae(o);if(c===null)return null;if((i===null||!hae(i.record,c))&&(i={record:c,job:{},ours:await pae(c,t,n,r.bootTime()),final:null}),i.final!==null)return i.final;i.ours=i.ours&&n.jobGroupAlive(c.pid);let l=O8(o),u=qt(l.status),d=u===null?null:j8(l.stderr)??j8(l.stdout);if(!m.existsSync(o))return null;let f={act:a,job:i.job,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=A8(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 _ae(e,t,n){m.mkdirSync(e,{recursive:!0});let r=m.mkdtempSync(s.join(e,`.claim-`));try{return m.writeFileSync(k8(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 vae(e,t,n,r,i,a,o,c){let l=(n??0)+1,u=s.join(t,String(l)),d=e.launchJobSync(i,O8(u));if(!d.ok)throw Error(`apply-update: ${d.error}`);let f=!1;try{let e=await c(d.pid);if(!_ae(t,u,{identity:r,pid:d.pid,startTime:e.kind===`start`?e.token:null,started:o,deadline:o+a}))return P8;if(A8(t).some(e=>e>l))return M8(t,l),P8;f=!0}finally{f?d.release():d.withdraw()}for(let e of A8(t).filter(e=>e<l))M8(t,e);return{ok:!0,act:l}}const P8={ok:!1,reason:`another act claimed this bundle first`};function yae(e){let t;try{t=N8(e)}catch(e){return{kind:`unread`,reason:e.message}}if(t===null)return{kind:`spend`,awake:null};let n;try{n=JSON.parse(t)}catch(e){return{kind:`unparsed`,reason:`${e.message}: ${t}`}}let{spentMs:r,lastSeen:i}=n??{};return typeof r==`number`&&typeof i==`number`&&r>=0&&Number.isFinite(r)&&Number.isFinite(i)?{kind:`spend`,awake:{spentMs:r,lastSeen:i}}:{kind:`unparsed`,reason:`not an act's spend: ${t}`}}function bae(e,t,n,r,i){let a=fae(s.join(e,String(t.act))),o=yae(a),c=dae(uae(t.record,o.kind===`spend`?o.awake:null,n),r,i);if(o.kind===`unread`)return{awake:c,fault:`${a}: ${o.reason}; left in place`};let l=[];if(o.kind===`unparsed`){let e=n===null?`its spend restarts`:`its spend carries on from this daemon's last look`;l.push(`${a}: ${o.reason}; ${e}`)}let u=ct(a);try{m.writeFileSync(u,JSON.stringify(c)),m.renameSync(u,a)}catch(e){m.existsSync(u)&&m.rmSync(u,{force:!0});let t=e.code;if(t===`ENOENT`)return null;l.push(`${a}: not written: ${t??e.message}`)}return{awake:c,fault:l.length===0?null:l.join(`; `)}}function xae(e,t,n){let r=O8(s.join(e,String(t.act))).status;return n.endJob(t.record.pid,r,{kind:`timeout`})}var F8=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 I8(e){return e.kind===`source`?e.newer.digest:rs(e.newer)}const L8=e=>`${e.version} [${Ln(e.digest)}]`;function R8(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:L8(e.newer),running:L8(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:rs(e.newer),running:rs(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${is}@${rs(e.newer)}`,`install`]}}}}function Sae(e,t,n){if(e===null)return[];let r=I8(e);if(!n.enabled||n.dismissed===r)return[];let i=R8(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(`
500
+ `),c=t.kind===`running`?rU(`[${i.busy}]`,null):rU(`[${i.act}]`,dC(n.to,[{verb:ZS,args:[n.sessionId]}])),l=[rU(a,null),c,rU(`[dismiss]`,dC(n.to,[{verb:PS,args:[n.sessionId,xz,r]}])),rU(`[disable]`,dC(n.to,[{verb:zS,args:[n.sessionId,Sz,`false`]},{verb:PS,args:[n.sessionId,Cz,`false`]}]))],u=o.map(e=>[rU(e,null)]);return[{severity:eU,about:`update\0${r}`,message:s,copy:s,lines:[l,...u]}]}function Cae(e,t){if(e.kind===`pending`)return e;let n=e.value;switch(n.kind){case`stale`:return F({kind:`source`,root:n.root,newer:n.source,running:n.running});case`current`:return I;case`unchecked`:return L(`build: unchecked: ${n.reason}`,`read`);case`not-source-checkout`:return wae(t)}}function wae(e){if(e.kind===`pending`)return e;let t=e.value;switch(t.kind){case`stale`:return F({kind:`release`,newer:t.latest,running:t.installed});case`current`:case`ahead`:return I;case`unchecked`:return L(`release: unchecked: ${t.reason}`,`read`)}}const z8=600*1e3,B8=2e3;5*B8;function Tae(e){switch(e.kind){case`current`:return[`info`,`build: current ${L8(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${L8(e.source)}, running ${L8(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function Eae(e){switch(e.kind){case`current`:return[`info`,`release: current ${rs(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${rs(e.latest)}, running ${rs(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${rs(e.installed)}, latest ${rs(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function Dae(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=So(`unread`),g=So(`unread`),_=async e=>{let t=await i.startTime(e);if(T)throw new uc(`apply-update`);return t},v=gae(s,_,r,n),y=null,b=null,x=Fe(m),S=Fe(m),C=new F8,w=e=>C.run(`acts`,e),T=!1,E=[],ee=(e,t)=>{E.push(n.every(t,e,{unref:!0}))},D=()=>{let e=t.get();return e.kind===`ok`?e.value:null};function te(){let e=D(),t=e===null?null:I8(e);(b===null?null:b.identity)!==t&&(b?.dispose(),b=t===null?null:{identity:t,dispose:f.state.register(xz,[t])})}function O(){let e=T?I:Cae(h,g),r=lQ(t.get(),e,st(n));(0,X.runInAction)(()=>t.set(r)),te()}function k(){let e=Un(a,()=>Bn(o));return h=F(e),x(Tae(e)),O(),e}async function ne(){let e=os(Rn,await as(is,d,u,n));g=F(e),S(Eae(e)),O()}let A=null,re=Fe(m),ie=e=>`update act files (${s}): ${e}`;async function ae(e){try{let t=await e();return A=null,{ok:!0,value:t}}catch(e){return e instanceof uc?{ok:!1,error:e.message}:(A=ie(e.message),re([`error`,A]),{ok:!1,error:A})}}let oe=null,se=null,ce=null,le=Fe(m);function ue(e){if(!e?.alive)return null;let t=bae(s,e,oe?.job===e.job?oe.awake:null,n.now(),1e4);return t===null?null:(oe={job:e.job,awake:t.awake},t.awake.spentMs>z8&&de(e),t.fault===null?null:ie(t.fault))}function de(e){let t=xae(s,e,r);if(t.verdict===`gone`){m(`error`,`apply-update: act ${e.act} timed out, but its files were removed before it could be ended; its group (pid ${e.record.pid}) was not signalled`);return}let n=t.signalled?`ending it`:`its group took no signal`;if(t.verdict!==`unrecorded`){let r=t.verdict===`stands`?`timed out`:`outlived its verdict`;m(`error`,`apply-update: act ${e.act} ${r}; ${n}`);return}let i=ie(`act ${e.act} timed out; its verdict could not be written: ${t.error}; ${n}`);m(`error`,`apply-update: ${i}`),se={job:e.job,reason:i}}async function fe(){let e=await ae(async()=>{let e=await v.read();return T||(ce=ue(e)),e});if(T||!e.ok)return;ce!==null&&le([`error`,ce]),se!==null&&e.value?.job!==se.job&&(se=null);let t=D8(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`),k(),p()),t.kind===`failed`&&m(`error`,`apply-update: act ${t.act} failed: ${t.reason}`)),y=t}let pe;async function me(){await w(fe),!T&&(pe=n.after(B8,()=>void me(),{unref:!0}))}return{arm(){let e=k();ee(k,c),E.push(()=>pe?.()),me(),e.kind===`not-source-checkout`&&(ne(),ee(()=>void ne(),l))},close(){T=!0,O(),E.forEach(e=>e())},notice:e=>Sae(D(),y??E8,e),running:()=>w(async()=>{let e=await ae(()=>v.read());return e.ok&&D8(e.value).kind===`running`}),error:()=>A??ce??se?.reason??null,act:()=>w(async()=>{if(T)throw new uc(`apply-update`);let e=await ae(()=>v.read());if(T)throw new uc(`apply-update`);if(!e.ok)throw new R(`apply-update: ${e.error}`);let t=D();if(t===null)throw new R(`apply-update: nothing newer is known to apply`);let i=R8(t),a=e.value;if(D8(a).kind===`running`)throw new R(`apply-update: already ${i.busy}`);let o=await vae(r,s,a===null?null:a.act,I8(t),{...i.command,category:`update.apply`},z8,n.now(),_);if(!o.ok)throw new R(`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},se=null})}}function Oae(){return X.observable.box(So(`unread`),{deep:!1})}function V8(e,t){try{return F(t.statSync(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?I:L(e.message,`read`)}}function kae(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function Aae(e){let{targets:t,intervalMs:n,filesystem:r,held:i,exit:a,log:o,clock:s}=e,c=Fe(o),l=t.map(e=>({path:e,stamp:V8(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=V8(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!kae(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 jae=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 H8=`pass`,U8={okMs:5*6e4,failedMs:45e3},Mae=U8.okMs;function W8({failures:e}){return Cj(U8,e,Mae)}function Nae(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function Pae(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function Fae(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function Iae(e,t,n,r){let i=[{path:n,filenames:[`HEAD`,`index`]},{path:s.join(r,`refs`,`heads`),recursive:!0}],a=i.map(t=>Lc(e,t.path));return{key:`git:${t}:${i.map((e,t)=>`${e.path}@${Rc(a[t])}`).join(`|`)}`,targets:{dirs:i},unbound:a.some(e=>typeof e==`string`||`unreadable`in e)}}function Lae(e){return e.find(e=>e.kind===`ok`)?.value.branch}function G8(e){e.missed=!0,Oj(e,`unread`)}function Rae(e,t){return e.missed&&e.reading.get().kind===`pending`&&Dj(e,t.size>0?L([...t].join(`; `),`read`):I),`unkeyed`}function zae(e,t){let n=jj(e);return t===null||n.kind!==`ok`?n:F({...n.value,pullRequest:jj(t)})}const Bae=L(`git cache closed`,`read`);function K8(e){return t=>L(`${e} threw: ${String(t)}`,`read`)}var Vae=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 Do(e.maxPrLookups??2),this.logger=e.logger??Ie;let t=e.ledger??new Hj(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 xj({filesystem:mn,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=L(`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 Fj(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>zae(a,o)}}asked(e,t,n,r){if(this.closed)return{kind:`settled`,outcome:Bae};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 jae,watch:this.followWatch(e,null).watch,period:new wj(()=>{n.refresh.share(H8,()=>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=Iae(this.watchers.filesystem,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(H8,()=>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&&G8(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(H8,()=>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:Tj(),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=Fae(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(Pae(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(K8(`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,Dj(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of KU(n.value))c.add(e)});let l=Lae(o),u=a===null||i.length===0?`-`:l===void 0?Rae(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}`,Nae(n),c.size===0?F(null):L([...c].join(`; `),`read`),Qe(this.clock,t))}prSource(e){let t={period:new wj(()=>{this.readPr(e,t,`period`)},this.clock),seen:new Map,holders:0,missed:!0,key:``,remote:I,reading:Tj(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(K8(`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?(G8(t),`owed`):(Oj(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,Dj(t,a.outcome),t.period.landed(W8(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(K8(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:I)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${z(r)}`,n,i,Qe(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||(Dj(t,i),t.period.landed(W8(s),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=L(`git state dropped: ${e.root}`,`read`);for(let n of e.values.values())kj(n,t);e.pr!==null&&kj(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 q8=`claude-sonnet-4-5-20250929`,Hae={"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}},J8=new n(`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`),Uae={okMs:1440*60*1e3,failedMs:3e4},Y8=e=>e===null?null:e.kind===`landed`?e:e.last,X8=(e,t)=>e===null?t:t===null||e.at>=t.at?e:t,Z8=e=>e.kind===`landed`?0:e.failures,Q8=e=>Cj(Uae,e,36e5),$8=(e,t)=>e.at+Q8(Z8(e))<=t;function Wae(e){let t=X.observable.box(null,{deep:!1}),n=(0,X.computed)(()=>Y8(t.get()),{equals:(e,t)=>e?.at===t?.at}),r=n=>n.then(e=>(0,X.runInAction)(()=>t.set(e))).catch(t=>{e.log(`error`,`pricing load rejected: ${String(t)}`)}),i=r(t5(e)),a=null,o=Fe(e.log);return{table:()=>n.get()?.table??Hae,ask:()=>{let n=t.get();!(n===null||$8(n,e.clock.now()))||e.closing.aborted||(a??=i.then(()=>r(Gae(e,t.get(),o))).finally(()=>{a=null}))}}}async function Gae(e,t,n){let r=await t5(e);if(r!==null&&!$8(r,e.clock.now()))return X8(r,Y8(t));let i=await Kae(e).catch(t=>(e.log(`error`,`pricing load threw: ${String(t)}`),null));if(i!==null)return i;if(e.closing.aborted)return t??r;let a={kind:`failed`,at:e.clock.now(),failures:(t===null?0:Z8(t))+1,last:X8(r,Y8(t))};return n([`warn`,`pricing table not loaded: priced by ${a.last===null?`the bundled rates`:`the last table`}; the next ask after ${Q8(a.failures)}ms tries again`]),a}const e5=e=>s.join(e,`usage`,`pricing.json`);async function Kae(e){let t=e.closing.aborted?null:await Jae(e.closing);if(t===null)return null;let n={kind:`landed`,table:t,at:e.clock.now()};return e.closing.aborted||await qae(e,n),n}async function t5(e){try{let{data:t,timestamp:n}=JSON.parse(await m.promises.readFile(e5(e.cacheRoot),`utf8`));return typeof n!=`number`||n>e.clock.now()||!n5(t)?null:{kind:`landed`,table:t,at:n}}catch(t){return t.code!==`ENOENT`&&e.log(`warn`,`pricing disk cache unreadable: ${String(t)}`),null}}async function qae(e,t){let n=e5(e.cacheRoot),r=ct(n);try{await m.promises.mkdir(s.dirname(n),{recursive:!0}),await m.promises.writeFile(r,JSON.stringify({data:t.table,timestamp:t.at}),`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 Jae(e){return new Promise(t=>{let n=ve({hostname:J8.hostname,path:J8.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3,agent:!1,signal:e},e=>{if(e.statusCode!==200){Pe(`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){Pe(`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);n5(i)?(Pe(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),Pe(`Pricing last updated: ${n?.updated||`unknown`}`),t(i)):(Pe(`Invalid pricing data structure`),t(null))}catch(e){Pe(`Failed to parse JSON:`,e),t(null)}}),e.on(`error`,e=>{Pe(`Response error:`,e),t(null)})});n.on(`error`,e=>{Pe(`Request error:`,e),t(null)}),n.on(`timeout`,()=>{Pe(`Request timeout`),n.destroy(),t(null)}),n.end()})}function n5(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 Yae(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[q8]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}function Xae(e,t,n){let r=Yae(t,e);return n.input/1e6*r.input+n.output/1e6*r.output+n.cacheCreation/1e6*r.cache_write_5m+n.cacheRead/1e6*r.cache_read}function Zae(e){return e.model||e.message?.model||q8}var r5=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 Qae(e,t){return{input:e.input+e.cacheCreation+e.cacheRead,output:e.output,total:HK(e),atMs:t}}const $ae={okMs:60*1e3,failedMs:10*1e3},eoe={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function i5(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-1),t.getTime()}function a5(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}function o5(e,t){e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function toe(e){return{input:e.input_tokens||0,output:e.output_tokens||0,cacheCreation:e.cache_creation_input_tokens||0,cacheRead:e.cache_read_input_tokens||0}}const s5={carried:{cost:0,tokens:a5()},unpriced:new Map};function c5(){return{carried:{cost:0,tokens:a5()},unpriced:new Map}}function l5(e,t){e.carried.cost+=t.carried.cost,o5(e.carried.tokens,t.carried.tokens);for(let[n,r]of t.unpriced){let t=e.unpriced.get(n);t===void 0?e.unpriced.set(n,{...r}):o5(t,r)}}function noe(e,t){let n=toe(t),r=e.costUSD??(HK(n)===0?0:void 0);return r===void 0?{carried:s5.carried,unpriced:new Map([[Zae(e.raw),n]])}:{carried:{cost:r,tokens:n},unpriced:s5.unpriced}}function u5(e){let t={...e.carried.tokens};for(let n of e.unpriced.values())o5(t,n);return t}function d5(e,t){let n=e.carried.cost;for(let[r,i]of e.unpriced)n+=Xae(t,r,i);return n}function roe(e,t){return{cost:d5(e,t),...u5(e)}}function f5(e,t){if(e===void 0||e.entries===0)return eoe;let n=u5(e.usage),r=d5(e.usage,t);return{cost:r,calculatedCost:r,officialCost:null,tokens:HK(n),tokenBreakdown:n}}const ioe={entries:0,usage:s5,days:new Map};function p5(e,t,n){let r=e.get(t);r===void 0&&(r=c5(),e.set(t,r)),l5(r,n)}function aoe(e,t,n){let r=e.entries,i=c5();l5(i,e.usage);let a=new Map;for(let[t,r]of e.days)t>=n&&p5(a,t,r);for(let e of t){let t=e.message?.usage;if(!t)continue;r++;let o=noe(e,t);l5(i,o);let s=GK(new Date(e.timestamp));s<n||p5(a,s,o)}return{entries:r,usage:i,days:a}}function ooe(e){let t=0,n=c5(),r=new Map;for(let{value:i}of e.values()){t+=i.entries,l5(n,i.usage);for(let[e,t]of i.days)p5(r,e,t)}return{entries:t,usage:n,days:r}}function m5(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function soe(e,t,n){let r=new Map;for(let{record:n}of e)if(!(n===void 0||!m5(n.transcriptPath,t)))for(let[e,t]of n.days)p5(r,e,t);return h5(r,n)}function h5(e,t){let n={};for(let[r,i]of e)n[r]=roe(i,t);return n}async function coe(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 g5(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function _5(e,t){(0,X.runInAction)(()=>e.set(t))}var loe=class{sessions=X.observable.map(void 0,{deep:!1});flight=new r5;scans;daySets=new Map;speedFlight=new r5;requestFlight=new r5;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??Ie,this.ledger=e.ledger??new Hj(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new Lj({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${z(e.join(`,`))}`,read:e=>this.scan(e),every:()=>e.rescan??$ae,watch:Ij,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=ko(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async e=>{let t=await r().record;return t.kind===`failed`?t:F(g5(f5(t.kind===`ok`?t.value:void 0,this.pricing.table()),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 So(`unread`);let r=n.failure.get();return r===null?F(g5(f5(n.record,this.pricing.table()),t)):L(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,Qe(this.clock,i)),_5(this.hold(e).failure,a.kind===`failed`?a.reason:null),this.holdsUnpriced()&&this.pricing.ask(),a})}holdsUnpriced(){for(let{record:e}of this.sessions.values())if(e!==void 0&&e.usage.unpriced.size>0)return!0;return!1}refreshToday(e){return this.request(e?.session_id??``,e?.transcript_path).today()}declareToday(e,t){if(this.closed)return Fj(L(`usage store closed`,`read`));let n=b2(t,this.host.home),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?F({roots:i.roots,sums:i.sums.read()}):e}}}daysOutside(e,t){let n=this.sessions.get(e);if(n===void 0)return I;let r=n.failure.get();if(r!==null)return L(r,`read`);let i=n.record;return i===void 0||m5(i.transcriptPath,t)?I:F(h5(i.days,this.pricing.table()))}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return I;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return _5(this.hold(e).speed,t),t;let r=Qae(t.kind===`ok`?u5(t.value.usage):a5(),n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=F({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return _5(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??So(`unread`):I}async ingest(e,t,n,r){if(!e)return I;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,F(i);if(!t)return i?F(i):I;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`,`read`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let{mainStamp:c,...l}=s.value,u={...l,transcriptStamp:c,transcriptPath:t},d=this.sessions.get(e)?.record;return d===o?(this.stored(e,u),F(u)):d===void 0?F(u):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,X.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:X.observable.box(null),speed:X.observable.box(void 0,{deep:!1})};return(0,X.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 xw(`today over ${e.join(`,`)}`,()=>soe(this.sessions.values(),r,this.pricing.table()))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await C2(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of M2(r.longLines))this.log(`info`,e);let i=GK(new Date(i5(this.clock.now()))),a=new Map,o=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),s=await N2(e,r,ioe,(e,t)=>aoe(e,t,i));if(s.kind===`failed`)return s;if(s.kind===`absent`){r&&a.set(e,r);continue}let{folded:c,longLines:l}=s.value;for(let e of M2(l))this.log(`info`,e);a.set(e,c),e===t&&(o=c.cursor.stamp)}return F({files:a,...ooe(a),mainStamp:o})}async scan(e){try{let t=i5(this.clock.now()),n=await x2(e),r=[];for(let e of n){let n=await S2(No(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a=await S2(Po(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:Ao(a)})}}let i=[],a={hits:0,misses:0};return await coe(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?L(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`,`read`):F({sessions:r.length,read:a.misses})}catch(e){return L(`usage scan: ${e instanceof Error?e.message:String(e)}`,`read`)}}sweepStale(){let e=this.clock.now(),t=GK(new Date(e)),n=0,r=0,i=0;return(0,X.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,X.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},v5=class{values=X.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,X.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)}})}},y5=class{sessions;flight=new r5;constructor(e,t,n,r,i=Ie,a=256){this.empty=e,this.step=t,this.refreshes=n,this.clock=r,this.log=i,this.sessions=new v5(a)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=ko(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 N2(t,n,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${z(e)}`,`request`,i,Qe(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 M2(o))this.log(`info`,e);return this.store(e,a,{kind:`ok`,value:a.value})}answer(e){return this.sessions.get(e)?.answer??So(`unread`)}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function uoe(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 doe=class{fold;constructor(e){let t=e.logger??Ie;this.fold=new y5(void 0,uoe,(e.ledger??new Hj(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 Pe(`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);Pe(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){return this.contextFrom(await this.fold.read(e,t),n)}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t?F(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,b5(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return F(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,b5(e))}contextFrom(e,t){if(e.kind===`failed`)return L(`context transcript: ${e.reason}`,e.failedAt);let n=e.value;return n===void 0?(Pe(`No main chain entries with usage data found`),I):(Pe(`Most recent main chain context: ${n} tokens (limit: ${t})`),F({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function b5(e){return e.context_window?.context_window_size??2e5}const foe={messageCount:0,nonPrompts:0,recent:[]},poe=new Set([`turn`,`interrupt`,`claude-code`]);function moe(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!poe.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function hoe(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 goe=class{fold;constructor(e){let t=e.logger??Ie;this.fold=new y5(foe,moe,(e.ledger??new Hj(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getMetricsInfo(e,t){Pe(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?x5(e,n,await this.fold.read(e,t.transcript_path)):I}metricsOf(e,t){let n=t.cost;if(!n)return I;let r=this.fold.answer(e);return r.kind===`pending`?r:x5(e,n,r)}};function x5(e,t,n){return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`,n.failedAt):F({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:hoe(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 _oe={command:null,todos:[],pending:[],done:[]};function S5(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 voe(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 yoe(e,t){if(t.isSidechain)return e;let n=voe(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=S5(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 boe(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>S5(e,t.name),[]),done:e.done}}var xoe=class{fold;constructor(e){let t=e.logger??Ie;this.fold=new y5(_oe,yoe,(e.ledger??new Hj(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),e.clock,t)}async getActivityInfo(e,t){return C5(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:C5(e,t)}};function C5(e,t){return t.kind===`failed`?L(`activity (${e}): ${t.reason}`,t.failedAt):F(boe(t.value))}const w5=3e4;var Soe=class{names;constructor(e){let t=e.logger??Ie;this.names=new Lj({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${z(e.pane)} socket=${z(e.socket)}`,read:t=>Coe(e.launcher,t),every:()=>({okMs:w5,failedMs:w5}),watch:Ij,maxEntries:64,logger:t,ledger:e.ledger??new Hj(t),clock:e.clock})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function Coe(e,t){let n=await sc(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return L(n.reason,`read`);let r=n.stdout.trim();return r?F(r):I}const T5=6e4,woe={okMs:T5,failedMs:T5};function Toe(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function E5(e,t){try{let e=t();return Promise.resolve(e===``?I:F(e))}catch(t){return Promise.resolve(L(`host.${e}: ${String(t)}`,`read`))}}var Eoe=class{name;user;constructor(e){let t=e.logger??Ie,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:()=>woe,watch:Ij,maxEntries:1,logger:t,ledger:e.ledger??new Hj(t),clock:e.clock};this.name=new Lj({...n,name:`host.name`,read:()=>E5(`name`,()=>Toe(o.hostname()))}),this.user=new Lj({...n,name:`host.user`,read:()=>E5(`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()}},Doe=class{known=new v5(64);refreshes;constructor(e,t=Ie,n=new Hj(t)){this.clock=e,this.refreshes=n.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=Ooe(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=bI(e);return this.refreshes.recorded(`path=${z(e)} stamp=${z(t)}`,`request`,i,Qe(this.clock,r)),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??So(`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 Ooe(e){try{let t=m.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Ao(t)}catch(e){return`unread:${e.code??`error`}`}}const koe=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function Aoe(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 joe=class{known=new v5(256);refreshes;constructor(e,t=Ie,n=new Hj(t)){this.clock=e,this.refreshes=n.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=ko(t),r=this.known.get(e);if(r!==void 0&&n!==``&&r.stamp===n&&r.outcome.kind!==`failed`)return this.known.touch(e),r.outcome;let i=await this.read(e,t,n);return this.known.set(e,{stamp:n,outcome:i}),i}expiryOf(e){return this.known.get(e)?.outcome??So(`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 Moe(t);return this.refreshes.recorded(`sid=${z(e)} stamp=${z(n)}`,`request`,i,Qe(this.clock,r)),i}};async function Moe(e){let t=await Noe(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function Noe(e){for(let t of[65536,1048576]){let n=await Uo(e,t);if(n.kind!==`ok`)return n;let r=Poe(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function Poe(e,t){let n=e.toString(`utf8`).split(`
501
+ `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!koe.test(t))continue;let r=Aoe(t);if(r!=null)return r}return null}const D5=e=>ZV(e),O5=e=>s.join(e.storage.folder,D5(e.sessionId)),k5=e=>JSON.stringify([e.folder,e.generation]),Foe=(e,t)=>e.folder===t.folder&&e.generation===t.generation,Ioe=(e,t,n)=>e.kind===`unusable`?{cause:`unusable`,reason:e.reason}:t===null?n===null?null:{cause:`error`,reason:n}:{cause:t.kind===`refused`?`refused`:`error`,reason:fj(t)};var Loe=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;fileEvents;clock;unsubscribe;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.fileEvents=e.fileEvents,this.clock=e.clock,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new Lj({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${z(O5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:()=>null,watch:Ij,maxEntries:256,logger:e.logger,ledger:e.ledger??new Hj(e.logger),clock:e.clock})}keyFor(e){let t=this.folders.get(e)??this.recorded(e);t.unusable=null;try{this.watchers.filesystem.mkdirSync(e)}catch(e){t.unusable=`could not be created: ${e.message}`}let n=t.unusable===null?this.statOf(e):{now:`gone`},r=`now`in n?n.now:null,i=t.lost||t.identity!==null&&r!==null&&(r===`gone`||!Fc(r,t.identity)),a=i?null:t.identity;return t.identity=r===null?a:r===`gone`?null:r,i&&(t.generation++,t.lost=!1,this.logger(`info`,`plugin storage generation folder=${z(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(k5(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.statOf(e.folder):{now:`gone`},i=e.generation===t.generation?t.identity:null,a=`now`in r?r.now:i??`unnamed`;e.generation===t.generation&&(t.identity=typeof a==`string`?null:a),n!==null&&(t.lost=!0);let o={key:e,folder:t,identity:a,holders:0,handle:this.watchers.acquire(`plugin-storage:${k5(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(o,e)),stopSweep:this.clock.every(864e5,()=>void this.sweep(e),{unref:!0}),health:n===null?{kind:`watching`}:{kind:`unusable`,reason:n},deafness:null,statFailure:`failed`in r?r.failed:null,reported:null};return this.watched.set(k5(e),o),this.heard(o),this.settled(o,()=>!1),this.sweep(e),o}closed(e){let t=k5(e.key);this.watched.delete(t),e.health={kind:`closed`},e.stopSweep(),e.handle.release()}invalidated(e,t){let{key:n}=e,r=s.join(n.folder,s.basename(n.folder));this.heard(e);let i;if(t.kind===`changed`&&!t.paths.has(r)){let{paths:e}=t;i=t=>e.has(O5(t))}else{let t=this.judged(e);i=(e,n)=>t===`lost`||t===`present`&&n===null}this.settled(e,i)}heard(e){e.deafness=e.handle.deaf[0]??null}judged(e){let{health:t}=e;if(t.kind!==`watching`)return`none`;let{key:n,folder:r}=e,i=this.statOf(n.folder);if(e.statFailure=`failed`in i?i.failed:null,`failed`in i)return`none`;let{now:a}=i,o=e.identity===`unnamed`?a:e.identity;return e.identity=o,n.generation===r.generation&&o!==`gone`&&(r.identity=o),a!==`gone`&&o!==`gone`&&Fc(a,o)?`present`:(e.health={kind:`lost`},n.generation===r.generation?(r.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${z(n.folder)} generation=${n.generation} now=${a===`gone`?`gone`:`replaced`}`),`lost`):`none`)}statOf(e){try{return{now:Pc(this.watchers.filesystem,e)}}catch(e){return{failed:`stat failed: ${e.message}`}}}settled(e,t){let{key:n}=e,r=this.reported(e),i=e.reported;this.sessions.changed(e=>Foe(e.storage,n)&&(r||t(e,i)))}reported(e){let{key:t}=e,n=e.reported,r=Ioe(e.health,e.deafness,e.statFailure);e.reported=r;let i=`folder=${z(t.folder)} generation=${t.generation}`;return r!==null&&(n===null||n.cause!==r.cause||n.reason!==r.reason)?(this.faultCounts[r.cause]++,this.logger(`warn`,`plugin storage fault ${i} cause=${r.cause} reason=${JSON.stringify(r.reason)}`),!0):r===null&&n!==null?(this.logger(`info`,`plugin storage fault cleared ${i} cause=${n.cause}`),!0):!1}noticed(e){switch(e.kind){case`period`:for(let e of[...this.watched.values()]){let t=this.judged(e)===`lost`;this.settled(e,()=>t)}return;case`moved`:case`caught-up`:this.sessions.changed(()=>!0);return}}standing(e){let t=this.watched.get(k5(e));if(t===void 0)return null;let n=t.reported;if(n?.cause===`unusable`)return`cannot refresh: ${e.folder} ${n.reason}; reload the config or restart the daemon`;let r=n?.reason??Gc(this.fileEvents.delivery(),t.handle);return r===null?null:`cannot refresh: ${e.folder}: ${r}`}async read(e){let t=this.standing(e.storage);if(t!==null)return L(t,`read`);let n=O5(e),r;try{r=await this.watchers.filesystem.readFile(n)}catch(e){let t=e;return t.code===`ENOENT`?I:L(`${n}: ${t.message}`,`read`)}if(r.trim()===``)return I;let i=Jj(r);return i.kind===`failed`?L(`${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=${Qe(this.clock,t)}ms`;try{let t=await this.watchers.filesystem.readdir(e.folder);for(let a of t){if(a.kind!==`file`||!a.name.endsWith(`.json`))continue;r++;let t=s.join(e.folder,a.name);try{let{mtimeMs:r}=await this.watchers.filesystem.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&D5(t.sessionId)===a.name);if(r>=n||o)continue;await this.watchers.filesystem.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 Roe(e){let{launcher:t,clock:n,logger:r,ledger:i}=e;return{home:e.host.home,hostService:new Eoe({clock:n,logger:r,ledger:i}),gitProvider:new Vae({inner:new bW(t,e.watchers.filesystem),watchers:e.watchers,clock:n,logger:r,ledger:i}),usageStore:new loe({host:e.host,pricing:e.pricing,clock:n,logger:r,ledger:i}),contextProvider:new doe({clock:n,logger:r,ledger:i}),metricsProvider:new goe({clock:n,logger:r,ledger:i}),activityProvider:new xoe({clock:n,logger:r,ledger:i}),tmuxService:new Soe({launcher:t,clock:n,logger:r,ledger:i}),autoCompact:new Doe(n,r,i),cacheExpiry:new joe(n,r,i),managedStorage:new Loe({watchers:e.watchers,fileEvents:e.fileEvents,clock:n,logger:r,ledger:i}),faults:new bQ,log:e.logger,clock:n}}function A5(e,t,n,r){let i=[];try{return{kind:`parsed`,loaded:pK(e,t,r.locs,r.layers,zK,{warned:e=>i.push(...e)},{repo:r.repo,cwd:n}),warnings:i}}catch(e){return e instanceof kb&&i.push(...e.warnings),{kind:`failed`,cause:e,warnings:i}}}function zoe(e,t){let{locations:n,projectDir:r,cwd:i,configFile:a}=t,o=zH(e,n,ZH(e,t.stateDir),r,i,a),{repos:s}=o,c={layers:o.kind===`chain`?o.layers:[],home:o.home,repo:s.plugins,locs:n};return{cwd:i,chain:c,repos:s,advisories:[KH(e,n,r,i),WH(o),zP(s)],parsed:A5(e,t.memo,i,c)}}function*j5(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*Boe(e){for(let t of Object.keys(e.segments))yield*NU(e,t);for(let t of nS(e.presets))yield*FU(e,t);for(let[,t]of j5(e))for(let[,e]of hb(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of vS(t))yield e}function Voe(e,t,n){let r=MU(t),i=new Set,a=new Set,o=new Set;for(let e of Boe(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of KC(e,t.helpers))a.add(n);for(let n of $C(e,t.helpers))o.add(n)}for(let[,e]of j5(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 nS(t.presets))for(let n of ob(aS(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=>!DS(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(j5(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 Hoe(e){return Math.floor(Math.max(e/4,e*Li-67108864))}const Uoe={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function M5(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[XV(SC(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[SC(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>CC(e)(t)&&t!==XV(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${jP(e,`<default>`)}: projections=${[...bG(n).keys()].join(`,`)||`-`} instantSegments=${DZ(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 Woe=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},Goe=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${Woe(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function Koe(e,t,n){let r=e=>z(e.join(`,`)||`-`);return`config loaded projectDir=${z(e.origin.projectDir)} cwd=${z(e.origin.cwd)} cause=${z(Goe(t))} state=${n} files=${z(jP(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 qoe(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function N5({projectDir:e,cwd:t,target:n}){return{projectDir:e,cwd:t,target:{path:n.path}}}function P5(e){return JSON.stringify(N5(e))}function Joe(e,t){return new Set(nS(e.presets).filter(n=>aS(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function Yoe(e,t,n){let{loaded:r,dropped:i,unreached:a}=t.state.plugins,o=[...new Set([...t.state.plugins.roots,s.join(t.origin.projectDir,AH)])];return uj(e,{named:[...FH(n,t.origin.projectDir,t.origin.cwd,t.origin.target.path),...o,...r.map(e=>e.path),...[...i,...a].map(e=>e.path),...new Set([...t.state.sources.values()].map(e=>e.folder))],whole:o})}function Xoe(e){return e.filter(Boolean).join(`
502
+ `)||null}const F5=e=>e instanceof Error?e.message:String(e);function I5(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function Zoe(e){let{loaded:t,chain:n}=e;return Qy({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:I5(e.plugins),source:null,warnings:null})),base:t.base,installed:{...I5(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 Qoe(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 L5(e,t,n,r){let i={cwd:e,chain:t,loaded:n.loaded,sources:Qoe(n.loaded.config,r)};return{kind:`resolved`,...i,key:Zoe(i),warnings:n.warnings}}function R5(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??zK,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new jw(t.clock),m=new bM(oM,p,o.globals.default_empty_value??``,w$(t.sessionState,()=>t.gates.state.gateFor(o))),h;try{h=xZ(o,m,n,t.compile??bZ(t.links),ese),f.push(...h.loadWarnings);let r=m.view(aM);f.push(...wZ(o,r,n,H5)),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 kb&&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:Joe(l,u),fileHeldSettings:K$(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>Voe(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,builtins:Bq(zU(o))}}}function z5(e,t,n,r,i){let a={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:Qe(i,e.started)},o=t=>Xoe([...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:F5(r.cause),cause:r.cause}}}function $oe(e,t,n,r,i,a){if(r.kind===`failed`)return z5(e,n,[],r,i.clock);let o=L5(t,n,r,i.storage),s=a?.loadKey===o.key?{kind:`kept`,state:a}:R5(o,i);return z5(e,n,o.warnings,s,i.clock)}function B5({projectDir:e,cwd:t,target:n},r,i=null){let a=r.clock.monotonic(),o=zoe(r.filesystem,{locations:r.locations,stateDir:r.stateDir,projectDir:e,cwd:t,configFile:n.path,memo:r.memo});return $oe({repos:o.repos,advisories:o.advisories,started:a},o.cwd,o.chain,o.parsed,r,i)}function V5(e,t,n){let r={layers:[],home:``,repo:t,locs:n.locations},i=A5(n.filesystem,n.memo,e,r),a=i.kind===`failed`?i:R5(L5(e,r,i,n.storage),n);if(a.kind===`failed`)throw Error(`bundled default failed to load: ${F5(a.cause)}`,{cause:a.cause});return a.state}const ese=new Set([`directory`]),H5=new Set([`view`]);function tse(e,t,n,{facts:r,source:i,changed:a,log:o}){let{sessionId:s}=n,c={builtins:e.builtins,sources:e.sources},l=r.follow(n,c),u=e.registry.view(l.runs),d=X.observable.box({facts:n},{deep:!1}),f=e=>{e!==d.get().facts&&(0,X.runInAction)(()=>{l.follow(e,c),d.set({facts:e})})},p=[],m=()=>(0,X.runInAction)(()=>{for(let e of p)e();let e=u.dispose();return l.dispose(),e});try{wZ(e.config,u,t,H5)}catch(e){throw m(),e}let h;try{h=i({sessionId:s,state:e,store:u.variableStore,declared:()=>d.get(),followed:l,onDispose:e=>p.push(e)})}catch(e){throw m(),e}JX(e.compiled,u.variableStore,u,h);let g=(0,X.reaction)(()=>[h.payload(),h.selections(),u.published()],()=>a(s),{equals:X.compareShallow,fireImmediately:!0,onError:e=>o(`error`,`session view change threw sid=${JSON.stringify(s)}: ${String(e)}`)});return{sessionId:s,state:e,store:u.variableStore,registry:u,source:h,requested:f,facts:()=>d.get().facts,settle:e=>l.settle(e),followed:{stamped:l.stamped,failure:l.failure},lastRenderCellsBySegment:new Map,retire:g,dispose:()=>(g(),m())}}var nse=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,filesystem:e.watchers.filesystem,memo:new dK,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Ie,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},e.watchers.filesystem.mkdirSync(JH(e.stateDir));let{dir:n,name:r}=cj(e.watchers.filesystem,YH(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)??EZ(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){let t=P5(e),n=this.entries.get(t);if(n)return this.entries.delete(t),this.entries.set(t,n),n;let r=this.load(e,null);r.state!==null&&this.log(`info`,M5(r.layers,r.state,r.ms));let i={origin:N5(e),configLayers:[],configHome:``,repos:r.repos,lastError:r.error,lastWarning:r.warning,state:r.state??V5(e.cwd,r.repos.plugins,this.deps),watch:null};return this.serve(i.state),this.entries.set(t,i),this.fit(i),this.log(`info`,`render-cache entry projectDir=${e.projectDir} cwd=${e.cwd} compile=${i.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${P(this.accountedBytes())}/${P(this.budgetBytes())}MB`),this.refreshWatcher(i,r),this.observers.onReload?.(i,[],{kind:`open`},r.kind),i}hold(e){let t=this.getOrCreate(e);return this.holdState(t,t.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){let n=this.hold(e),r,i;try{r=this.viewOf(n.entry,n.state,t,`request`),i=this.leaseOf(r)}catch(e){throw n[Symbol.dispose](),e}return i.read=!0,this.holdViewOf(n,r,i)}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=tse(t,e.origin.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.origin.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){if(this.closed)throw Error(`render cache used after close`);return B5(e,this.deps,t)}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=${P(this.accountedBytes())}/${P(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`,qoe(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){this.reloadInto(this.getOrCreate(e),t)}reloadInto(e,t){let n=this.sessionsOn(e),r=e.state,i=this.load(e.origin,r);e.lastWarning=i.warning,e.lastError=i.error,i.state!==null&&this.log(`info`,M5(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=Yoe(this.deps.watchers.filesystem,e,this.deps.locations),{targets:r,unresolved:i}=n,a=`config:${P5(e.origin)}:${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.origin.projectDir} cwd=${e.origin.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.origin.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)}get installedLayers(){return this.deps.memo}stopDrawing(e,t){this.copies.get(e)?.delete(t)}};const rse=e=>!w0(e)&&!cI(e)&&e!==`update.dismissed`&&e!==jS;var ise=class{past=X.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&&n.verdict(e.key,e.before).kind===`held`))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:l0(e,rse,(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 R(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,X.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,X.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 U5=(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 W5(e,t,n,r,i){let a=(e,t)=>Object.fromEntries([...e].map(([e,n])=>[e,lQ(t?.[e],n,i)])),o=a(Object.entries(n.builtins),e?.builtins),s=a(n.sources,e?.sources),c=Object.fromEntries([...n.runs].map(([t,{reading:n,fault:r}])=>{let a=e?.runs[t],o=lQ(a?.reading,n,i);return[t,a!==void 0&&a.reading===o&&a.fault===r?a:{reading:o,fault:r}]})),l={builtins:o,sources:s,runs:c,update:r,diagnostics:n.faults};return e!==void 0&&U5(o,e.builtins)&&U5(s,e.sources)&&U5(c,e.runs)&&(0,X.compareStructural)({update:r,diagnostics:n.faults},{update:e.update,diagnostics:e.diagnostics})?e:{v:3,session:t,seq:e===void 0?1:e.seq+1,...l}}function ase(e,t,n){let r=Yj(e),i=(0,X.computed)(()=>t().runs[r]),a=(0,X.computed)(()=>{let e=i.get();return e===void 0?n(r):Dq(e.reading)},{equals:X.compareStructural});return{digest:r,current:()=>a.get(),fault:()=>i.get()?.fault??null}}function ose(e,t,n,r){if(t.kind===`failed`)return yo(e,t.reason);try{let i=W5(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 yo(e,`stamping the facts document: ${String(t)}`)}}function sse({providers:e,update:t,runs:n}){let{clock:r,log:i}=e;return{follow(a,o){let s=a.sessionId,c=new sj,l=X.observable.map(void 0,{deep:!1}),u=!1,d=(e,t)=>{if(!l.has(t))return L(`the run of ${Zj(e.read)} is not declared by this view`,`read`);let{failure:n}=y.get();return n===null?So(`unread`):L(`the run of ${Zj(e.read)} is in no document: ${n}`,`read`)},f=JSON.stringify(s),p=(t,n)=>{try{let{result:{lanes:r,faults:a},acquired:o,released:s}=c.declare(()=>Cq(e,c,t,n));for(let e of a)i(`error`,`session view declaration threw sid=${f} ${e}`);return o+s>0&&i(`info`,`session view declared sid=${f} builtins=${Hq(n.builtins)} acquired=${o} released=${s} held=${c.size}`),r}catch(e){return i(`error`,`session view declaration threw sid=${f}: ${O(e)}`),bq(L(`view declaration threw: ${String(e)}`,`read`),n)}},m=X.observable.box({facts:a,lanes:p(a,o)},{deep:!1}),h=(0,X.computed)(()=>{let{facts:t}=m.get();return{hookData:t.hookData,cwd:t.cwd,hints:t.hints,deps:{...e,lanes:()=>m.get().lanes}}}),g=(0,X.computed)(()=>wq(h.get())),_=(0,X.computed)(()=>new Map([...l].map(([e,{run:t}])=>[e,{reading:t.current(),fault:t.fault()}]))),v=(0,X.computed)(()=>({...g.get(),runs:_.get()})),y,b=(0,X.reaction)(()=>{try{return{kind:`read`,readings:v.get(),update:t()}}catch(e){return{kind:`failed`,reason:`reading the owners: ${String(e)}`}}},e=>(0,X.runInAction)(()=>{let t=y.get(),n=ose(t,e,st(r),s);n.failure!==null&&n!==t&&i(`error`,`session facts sid=${f}: ${n.failure}`),y.set(n)}),{onError:e=>i(`error`,`session facts threw sid=${f}: ${O(e)}`)});try{let e=st(r);y=X.observable.box({line:{at:e,facts:W5(void 0,s,v.get(),t(),e)},failure:null},{deep:!1})}catch(e){throw b(),c.close(),e}return{runs:{declare:(e,t)=>{if(u)throw Error(`the run of ${Zj(t.read)} was declared after its view's follow was disposed`);let r=Yj(t);return e.take(`facts.run:${r}`,()=>{let e=new sj,i=n.declare(e,t),a=ase(t,()=>y.get().line.facts,e=>d(t,e));return(0,X.runInAction)(()=>l.set(r,{run:i,held:e,lane:a})),()=>{(0,X.runInAction)(()=>l.delete(r)),e.close()}}),l.get(r).lane}},stamped:()=>y.get().line,failure:()=>y.get().failure,follow:(e,t)=>{let n=p(e,t);(0,X.runInAction)(()=>m.set({facts:e,lanes:n}))},settle:e=>{let t=new Map;return{refreshed:t,landed:Yq(h.get(),e,t)}},dispose:()=>{u=!0,b();for(let{held:e}of l.values())e.close();c.close()}}}}}function G5(e,t){return e===t||e?.cause===t?.cause&&e?.reason===t?.reason}function cse(e,t,n){if(t.kind===`failed`){let n={cause:`inputs`,reason:t.reason};return G5(e.failure,n)?e:{...e,failure:n}}let r=t.facts===null?null:{cause:`facts`,reason:t.facts};return G5(e.failure,r)&&t.stamped===e.stamped&&t.request===e.request&&t.compose===e.compose&&t.draw===e.draw?e:{stamped:t.stamped,request:t.request,picks:n(),compose:t.compose,draw:t.draw,failure:r}}function lse(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`,()=>cJ(n.config,s,e=>n.authoredRoots.has(e))),l=r.derive(`session.foreign`,`computed`,()=>{let r=e.stateGates.gateFor(n.config);return Object.entries(e.sessionState.values(t)).flatMap(([e,t])=>{let n=r.verdict(e,t);return n.kind===`foreign`?[{key:e,held:t,admits:n.admits}]:[]})}),u=r.derive(`session.compose`,`computed`,()=>{let{facts:t}=i();return{hookData:t.hookData,hints:t.hints,home:e.providers.home}}),d=r.derive(`session.draw`,`computed`,()=>({effective:c.read(),configFacts:{...q$(n.config,n.fileHeldSettings,s),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})),f=()=>({values:e.sessionState.values(t),revision:e.sessionState.revision(t)}),p=a.failure(),m=X.observable.box({stamped:a.stamped(),request:i().facts,picks:f(),compose:u.read(),draw:d.read(),failure:p===null?null:{cause:`facts`,reason:p}},{deep:!1});o((0,X.reaction)(()=>{try{return{kind:`read`,stamped:a.stamped(),facts:a.failure(),request:i().facts,compose:u.read(),draw:d.read()}}catch(e){return{kind:`failed`,reason:`reading the turn's inputs: ${String(e)}`}}},n=>(0,X.runInAction)(()=>{let r=m.get(),i=cse(r,n,f);n.kind===`failed`&&i!==r&&e.providers.log(`error`,`session turn sid=${JSON.stringify(t)}: ${n.reason}`),m.set(i)}),{onError:n=>e.providers.log(`error`,`session turn threw sid=${JSON.stringify(t)}: ${String(n)}`)}));let h=r.derive(`session.payload`,`computed`,()=>{let{stamped:e,compose:t,draw:n}=m.get();return Vq(e.facts,t,n)});return{payload:()=>h.read(),effective:()=>m.get().draw.effective,foreign:()=>l.read(),facts:()=>m.get().stamped.facts,turn:()=>{let{stamped:e,request:t,picks:n,draw:r}=m.get();return{document:e,request:t,state:{...n,history:r.history,back:r.back}}},held:()=>m.get().failure?.cause===`inputs`,home:()=>m.get().compose.home,hints:()=>m.get().compose.hints,failure:()=>m.get().failure,selections:()=>m.get().draw.effective,state:()=>({values:e.sessionState.values(t),revision:e.sessionState.revision(t),history:m.get().draw.history,back:m.get().draw.back})}}}const use=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function K5(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?use[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const dse={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 fse({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=K5(t),o=K5(n),s={};for(let e of r){let t=dse[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 pse(e){return{ok:!0,band:e.rows.map(e=>lF(e).map(fse))}}function mse(e){return aF(pse,e)}const hse=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function q5(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:hse[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 gse={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 _se(e){return e.replaceAll(`#`,`##`)}function vse({fg:e,bg:t,attrs:n=[]}){let r=n.map(e=>{let t=gse[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${q5(e)}`,`bg=${q5(t)}`,...r].join(`,`)}]`}function yse(e,t){let n={},r=e=>{let r=vse(e)+_se(e.text);if(e.link===void 0)return r;let i=t(e.link);return i===null?r:(n[i]=e.link,`#[range=user|${i}]${r}#[norange]`)};return{rows:e.rows.map(e=>lF(e).map(r).join(``)),links:n}}function bse(e,t){return t.frame(t=>aF(e=>yse(e,t),e))}var xse=class{ranges=new Map;constructor(e,t=256){this.source=e,this.cap=t}frame(e){let t=new Set,n=e(e=>(t.add(e),this.rangeOf(e)));for(let e of this.ranges.keys()){if(this.ranges.size<=this.cap||t.has(e))break;this.ranges.delete(e),this.source.evicted()}return n}rangeOf(e){let t=this.ranges.get(e);if(t!==void 0)return this.ranges.delete(e),this.ranges.set(e,t),this.source.reused(),t;let n=this.source.next();if(n===null)return null;let r=`ccb`+n.toString(36);return this.ranges.set(e,r),r}};function Sse(e){return{band:()=>e=>({json:JSON.stringify(mse(e)),value:null}),statusline:()=>(e,t)=>({json:t,value:null}),pane:()=>(e,t)=>({json:t,value:null}),tmuxStatus:()=>{let t=new xse(e);return e=>{let n=bse(e,t);return{json:JSON.stringify({ok:!0,tmuxStatus:n}),value:n}}}}}const Cse=/^\d{1,15}\n?$/,wse=10**15-1,J5=`remove it and a new one is made, starting again from 0 (a click on a status row drawn before then may run a link drawn since)`;function Tse(e){let{file:t,clock:n,retryMs:r,log:i}=e,a=0,o={kind:`ready`,next:0},s=0,c=0,l=0,u=0,d=0,f=()=>{try{let e=Math.max(Ese(t),a),n=e+1024;if(n>wse)throw Error(`${t} holds ${e}, too near the last count for another block: ${J5}`);return wr(t,`${n}\n`,384),a=n,u++,o.kind===`faulted`&&i(`info`,`link ids: ${t} reserved again`),{kind:`ready`,next:e}}catch(e){d++;let t=`link ids: ${e.message}`;return(o.kind!==`faulted`||o.reason!==t)&&i(`error`,t),{kind:`faulted`,reason:t,clear:n.after(r,()=>o=f(),{unref:!0})}}};return{next(){return o.kind===`ready`&&o.next===a&&(o=f()),o.kind===`ready`?(s++,o.next++):null},reused:()=>void c++,evicted:()=>void l++,error:()=>o.kind===`faulted`?o.reason:null,stats:()=>({minted:s,reused:c,evicted:l,reservations:u,faults:d}),close(){o.kind===`faulted`&&o.clear(),o={kind:`closed`}}}}function Ese(e){let t;try{t=m.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return 0;throw e}if(!Cse.test(t))throw Error(`${e} holds ${JSON.stringify(t.slice(0,40))}, not a count: ${J5}`);return Number(t.trim())}const Y5=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,X5=`#{session_id} #{client_control_mode} #{pane_id}`;function Z5(e){let t=new Set;for(let n of e.split(`
503
503
  `)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function Q5(e,t){let n=new Set;for(let r of e.split(`
504
504
  `)){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 Dse(e,t){let n=new Map;for(let t of e.split(`
505
505
  `)){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(`
506
506
  `)){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 Ose=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: ${O(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:Q5(t.stdout,Z5(n.stdout)),status:Dse(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),!kse(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 kse(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 $5(e){return`"${e.replace(/[\\"$~]/g,e=>`\\${e}`)}"`}function e7(e){return e.map(e=>e.map(t7).join(` `)).join(` ; `)}const t7=e=>typeof e==`string`?$5(e):`{ ${e7(e.block)} }`;function Ase(e){return e.map(e=>e.map(t7).join(` `)).join(` \\; `)}const jse={n:`
507
- `,t:` `,r:`\r`,b:`\b`,a:`\x07`,v:`\v`,f:`\f`,0:`\0`},Mse=(e,t)=>e.startsWith(`\\;`,t)&&(e[t+2]??` `)===` `;function n7(e){let t=0,n=n=>e[t]===n&&(e[t+1]??` `)===` `,r=()=>{let n=[],r=e=>{n.push(...Buffer.from(e,`utf8`))},i=null;for(;t<e.length;){let a=e[t];if(i===null&&(a===` `||a===`;`))break;if(a===i)i=null,t++;else if(i===null&&(a===`"`||a===`'`))i=a,t++;else if(a===`\\`&&t+1<e.length){let i=/^[0-7]{3}/.exec(e.slice(t+1,t+4)),a=e[t+1];i===null?(r(jse[a]??a),t+=2):(n.push(parseInt(i[0],8)),t+=4)}else{let n=String.fromCodePoint(e.codePointAt(t));r(n),t+=n.length}}return Buffer.from(n).toString(`utf8`)},i=a=>{let o=[[]];for(;t<e.length;)if(e[t]===` `)t++;else if(e[t]===`;`||!a&&Mse(e,t))o.push([]),t+=e[t]===`;`?1:2;else if(a&&n(`}`)){t++;break}else n(`{`)?(t++,o.at(-1).push({block:i(!0)})):o.at(-1).push(r());return o.filter(e=>e.length>0)};return i(!1)}const r7=[`-T`,`root`,`MouseDown1Status`],i7=`@cc-candybar-renderer`,a7=`@cc-candybar-click`;function Nse(e,t,n,r){return`${e} ${pC(t,sC,dC([n,r]))}`}const o7=`#{m:ccb*,#{mouse_status_range}}`;function Pse(e){let t=`run-shell -b ${$5(`#{${a7}}/#{s/%//:pane_id}/#{q:mouse_status_range}`)}`,n=`display-message ${$5(`cc-candybar: no renderer takes clicks on this row: the one that drew it is older than this binding`)}`;return[`bind-key`,...r7,`if-shell`,`-F`,o7,`if-shell -F ${$5(`#{${a7}}`)} ${$5(t)} ${$5(n)}`,...e===null?[]:[e7(e)]]}const Fse=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m;function s7(e){let[t,...n]=e;if(t===void 0||n.length>0||t[0]!==`if-shell`)return;let r=t.slice(1);for(;typeof r[0]==`string`&&r[0].startsWith(`-`);)r=r.slice(1);if(r[0]!==o7)return;let i=r[2],a=i===void 0?[]:typeof i==`string`?n7(i):i.block;return a.length>0?a:null}function c7(e){let t=Fse.exec(e)?.[1],n=t===void 0?null:n7(t),r=n!==null&&s7(n)!==void 0;for(;n!==null;){let e=s7(n);if(e===void 0)break;n=e}return{ours:r,user:n}}const l7=`#{S:#{?#{!=:#{${i7}},},1,}}`;function Ise(e){return[`if-shell`,`-F`,l7,`${e7([Pse(e)])} ; display-message -p ccb:bound`]}function Lse(e){return[`if-shell`,`-F`,l7,`display-message -p ccb:held`,`${e===null?`unbind-key ${r7.join(` `)}`:`bind-key ${r7.join(` `)} ${Ase(e)}`} ; display-message -p ccb:restored`]}const u7=Zc.tmuxStatus.rows,d7=`@cc-candybar-status-prior`,f7=`@cc-candybar-status-wrote`,p7=Array.from({length:u7},(e,t)=>t),m7=e=>`@cc-candybar-row-${e}`,Rse=e=>`#[fill=terminal]#{${m7(e)}}`,h7=e=>`status-format[${e}]`;function zse(e){return e===0?`off`:e===1?`on`:String(e)}function g7(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 Bse(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 _7(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}const v7={kind:`ok`,stdout:``};function y7(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}const b7=`ccb:separator`;function x7(e){return y7(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,b7],e]))}function S7(e,t){let n=e.split(`${b7}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const C7=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],Vse=e=>[`show-options`,`-g`,`-q`,`-v`,e],w7=e=>[[`show-options`,`-t`,e],C7(e,`status`),...p7.map(t=>C7(e,h7(t)))];function T7(e){let[t=``,n=``,...r]=e,i=t.split(`
508
- `).map(e=>e.split(` `)[0]??``),a={};for(let e of p7)i.includes(h7(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 E7(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,h7(Number(t)),_7(n)])]}const Hse=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...w7(e),...p7.map(e=>Vse(h7(e))),C7(e,d7),C7(e,f7)];function D7(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:g7(t)}catch(e){return{kind:`theirs`,why:`${d7} 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 O7=(e,t)=>[[`set-option`,`-t`,e,i7,t.name],[`set-option`,`-t`,e,a7,t.click]];function Use(e,t,n,r){let[i=``,...a]=t,o=T7(a.slice(0,2+u7)),s=a.slice(2+u7,2+2*u7),[c=``,l=``]=a.slice(2+2*u7);if(c!==``){let t=D7(c,l,n);return t.kind===`theirs`?t:{...t,commands:O7(e,r)}}let u=g7(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:u7-u},(e,t)=>[u+t,Rse(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,d7,JSON.stringify(p)],...O7(e,r),...E7(e,f)]}}const k7=e=>[...w7(e),C7(e,f7)];function A7(e,t,n){let r=T7(n.slice(0,2+u7)),i=n[2+u7]??``,a=[],o=[];if(Bse(r.formats,t.wrote))a.push(...E7(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,h7(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,_7(t.status)]):o.push(`status`)),a.push(...p7.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,m7(t)]),[`set-option`,`-q`,`-u`,`-t`,e,d7],[`set-option`,`-q`,`-u`,`-t`,e,f7],[`set-option`,`-q`,`-u`,`-t`,e,i7],[`set-option`,`-q`,`-u`,`-t`,e,a7]),{commands:a,kept:o}}const j7=[[`list-keys`,`-T`,`root`]];var Wse=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.kind===`runs`?t.tmux:r??null:null;if(r!==void 0&&(i===null||!jc(r,i))&&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=e.value,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 e=this.deps.sessionInPane(n);e!==null&&e!==n.sessionId&&this.release(n,`pane taken by sid=${JSON.stringify(e)}`)}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,k7(r));if(a===null)continue;let o=A7(r,i.prior,a);this.writeSync(e,t,o.commands),this.saidRestored(t,r,o.kept)}if(n.binding===`none`)continue;n.binding=`none`;let r=this.askSync(e,t,j7);if(r===null)continue;let i=this.bindingRestore(t,r[0]??``);if(i===null)continue;let a=this.writeSync(e,t,[i.command]);this.saidBindingRestore(t,a,i.user)}}linkAt(e){let t=Gse(e),[n,r,i,a,...o]=t??[];if(t===null||n===void 0||r===void 0||i===void 0||a===void 0||o.length>0)return{kind:`refused`,reason:`${sC} needs <socket>/<mac>/<pane>/<range>, got ${JSON.stringify(e)}`};if(!this.deps.signer.verifyBinding(n,r))return{kind:`refused`,reason:`a status-line click on ${JSON.stringify(n)} whose mac is not this renderer's binding's`};let s=[...this.held.values()].find(e=>e.socket===n&&e.pane===`%${i}`)?.frame?.links,c=s!==void 0&&Object.hasOwn(s,a)?s[a]:void 0;return c===void 0?{kind:`refused`,reason:`pane %${i}'s status line draws no link ${a} now`}:{kind:`link`,url:c}}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:`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,u7-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#{${d7}}\t#{${f7}}`]);if(n.kind===`ok`){let r=this.marks(e),i=[];for(let a of n.stdout.split(`
509
- `)){let[n,o,s=``]=a.split(` `);if(n===void 0||o===void 0||o===``)continue;let c=D7(o,s,this.deps.owner);c.kind===`ours`?(t.layouts.set(n,{prior:c.prior,rows:[],status:c.status}),i.push(...O7(n,r))):this.leave(e,t,n,c.why)}await this.write(e,i)}t.layouts.size>0&&(t.binding=`owed`,this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)}`))}marks(e){return{name:this.deps.name,click:Nse(this.deps.handler,this.deps.name,e,this.deps.signer.signBinding(e))}}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,Hse(n));if(r===null||this.closed)return null;let i=Use(n,r,this.deps.owner,this.marks(e));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,m7(r),e])}),i!==n.status){let e=zse(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,f7,e])}(a.length===0||(await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,e7(a)]])).kind===`ok`)&&(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,k7(n));if(i===null)return;let a=A7(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){if(t.binding===`bound`)return;let n=t.binding,r=await this.ask(e,j7);if(r===null||this.closed)return;let{user:i}=c7(r[0]??``);t.binding=`bound`;let a=await this.write(e,[Ise(i),[`set-option`,`-g`,`-q`,`-u`,`@cc-candybar-binding-prior`]]),o=a.kind===`ok`&&a.stdout.includes(`ccb:bound`);o||(t.binding=n);let s=o?`bound MouseDown1Status over ${M7(i)}`:a.kind===`ok`?`left MouseDown1Status unbound: no session names a renderer`:`MouseDown1Status not bound: ${a.reason}`;this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${s}`)}async restoreBinding(e,t){if(t.binding===`none`)return;t.binding=`none`;let n=await this.ask(e,j7);if(n===null)return;let r=this.bindingRestore(e,n[0]??``);if(r===null)return;let i=await this.write(e,[r.command]);this.saidBindingRestore(e,i,r.user)}bindingRestore(e,t){let n=c7(t);return n.ours?{command:Lse(n.user),user:n.user}:(this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} left MouseDown1Status as it is: not a cc-candybar binding`),null)}saidBindingRestore(e,t,n){let r=t.kind===`ok`?t.stdout.includes(`ccb:restored`)?`restored MouseDown1Status to ${M7(n)}`:t.stdout.includes(`ccb:held`)?`left MouseDown1Status bound: a session still names a renderer`:`MouseDown1Status restore said neither way: ${JSON.stringify(t.stdout)}`:`MouseDown1Status not restored: ${t.reason}`;this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r}`)}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){return this.counted(e,await this.deps.edge.run(e,t))}async ask(e,t){let n=await this.run(e,x7(t));return n.kind===`ok`?S7(n.stdout,t.length):null}askSync(e,t,n){let r=this.counted(t,e(t,x7(n)));return r.kind===`ok`?S7(r.stdout,n.length):null}async write(e,t){return t.length===0?v7:(this.writes++,this.run(e,y7(t)))}writeSync(e,t,n){return n.length===0?v7:(this.writes++,this.counted(t,e(t,y7(n))))}};const M7=e=>e===null?`unbound`:JSON.stringify(e7(e));function Gse(e){try{return Ate(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),N7=e=>({arity:e,keep:!1}),Kse={"--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":N7(`none`),"--background":N7(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":N7(`optional`),"-c":N7(`none`),"--continue":N7(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":N7(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":N7(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":N7(`none`),"--forward-subagent-text":$(`none`),"--from-pr":N7(`optional`),"-h":N7(`none`),"--help":N7(`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":N7(`none`),"--print":N7(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":N7(`optional`),"--resume":N7(`optional`),"--safe-mode":$(`none`),"--session-id":N7(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":N7(`optional`),"--tmux":N7(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":N7(`none`),"--version":N7(`none`),"-w":N7(`optional`),"--worktree":N7(`optional`)},qse={resume:`--resume`,fresh:`--session-id`};function Jse(e){return[qse[e.kind],e.sessionId]}const P7=e=>e.startsWith(`-`)&&e!==`-`;function F7(e,t){let n=I7(t);return n===null?{dir:e??t,args:[]}:e!==null&&Yse(e,n.top)?{dir:e,args:[]}:{dir:e===null||I7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const Yse=(e,t)=>e===t||e.startsWith(t+s.sep);function Xse(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!P7(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=Kse[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=>!P7(e)):o.arity===`variadic`?Zse(n.slice(r),e=>!P7(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 I7(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 Zse(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const L7=`candybar-band@cc-candybar`,Qse=s.join(`bin`,`cc-candybar-native`),$se=pI(`/reload-plugins`);function ece(e,t,n){let r=e();if(r.kind===`gone`)throw Error(r.reason);let i=()=>{let t=e();if(t.kind===`gone`)return t;let n=l$(t.session.hints.tmux);return n.kind===`refused`?n:{kind:`in`,session:t.session,tmux:n.hint}},a=async e=>{let r=i();if(r.kind!==`in`)return r;let o=await t(r.tmux,async()=>{let t=i();return t.kind!==`in`||!jc(t.tmux,r.tmux)?t:{kind:`held`,value:await e(t.session,t.tmux)}});return o.kind===`in`?(n(r.tmux,o.tmux),a(e)):o};return{session:r.session,inPane:a}}function R7(e,t){if(e.kind!==`held`)throw new R(t(e.reason));return e.value}const z7=e=>({kind:`done`,said:e});function B7(e){let t=l$(e.hints.tmux);if(t.kind===`refused`)throw new R(t.reason);return t.hint}const tce={band:{on:async(e,t,n)=>{let r=zn(t.bundle);if(r===null)throw new R(`${Zc.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,Qse);if(!n.fileExists(i))throw new R(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${L7} from ${r}`,finished:nce(e,r,n)}},off:async()=>z7(`nothing to stop: the band mod ends its child once the lane is off`)},statusline:{on:async(e,t,n)=>{let r=B7(e.session),i=N(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new R(`${Zc.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:e.inPane((e,r)=>ace(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)).then(e=>R7(e,e=>`Claude Code was not restarted under the attach launcher: ${e}`))}},off:async()=>z7(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>R7(await e.inPane(async(e,r)=>{let i=await n.barPanes(r);return i.length>0?z7(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):z7(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],tr(t.home))} under ${r.pane}`)}),e=>`no bar pane was opened: ${e}`),off:async(e,t,n)=>{let r=await e.inPane(async(e,t)=>{let r=await n.barPanes(t);for(let e of r)await n.closePane(t,e);return z7(r.length===0?`no bar pane draws ${t.pane}'s bar`:`closed bar pane ${r.join(`, `)}`)});return r.kind===`refused`?z7(`no bar pane to close: ${r.reason}`):R7(r,e=>e)}},tmuxStatus:{on:async({session:e})=>z7(`the daemon draws ${B7(e).pane}'s bar in its status line`),off:async()=>z7(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function nce(e,t,n){let{session:r}=e,i={sessionId:r.sessionId,projectDir:r.origin.projectDir,claudeConfigDir:r.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],i),await n.claude([`plugin`,`install`,L7],i);let a=await e.inPane((e,t)=>u$(n.claudeInput,t,$se)),o=a.kind===`held`?a.value:{kind:`refused`,reason:a.reason};if(o.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${o.reason} — or type /reload-plugins yourself`);return`installed ${L7} from ${t} and typed /reload-plugins into ${o.pane}`}const rce=new Set([Go,DP]);function ice(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function ace(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,En(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}) — ${Zc.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);let o=await r.paneClaude(t);if(o.pid!==i.pid||o.startTime!==i.startTime)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}, started ${i.startTime}; now pid ${o.pid}, started ${o.startTime}), so it was not restarted under the attach launcher`);let s=uce(await r.claudeInput.read(t));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s} — then turn ${Zc.statusline.label} off and on again`);let c=oce(e,r.presence(e.transcript));if(c!==null)throw Error(`Claude Code in ${t.pane} was left running: ${c}`);let l=Xse(i.argv);if(l.kind===`refused`)throw Error(`${l.reason} — restart it with that flag removed`);let u=ice(i.env),d=u.get(`PATH`),f=r.launcherNode(d);if(f.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${f.why}`);let p=r.onPath(`claude`,d)===i.executable?`claude`:i.executable,m=[...u].filter(([e])=>rce.has(e)),h=(e,t)=>kn(n.preload,{dir:e.dir,env:m,program:p,args:[...e.args,...l.args,...Jse(t)]}),g=r.heldSession({pid:i.pid,startTime:i.startTime,configDir:Ko(Object.fromEntries(u),i.cwd)});if(g.kind!==`holds`)throw Error(`Claude Code in ${t.pane} was left running: ${g.why}, so which session it runs is unknown`);if(g.sessionId!==e.sessionId)throw Error(`Claude Code in ${t.pane} now runs session ${g.sessionId}, not ${e.sessionId}, so it was not restarted under the attach launcher — turn ${Zc.statusline.label} off and on again from the bar in ${t.pane} to restart that one`);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 _=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),v=sce(e,r.presence(e.transcript)),y=v.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:v,b;try{b=await r.paneDir(t,i.parent)}catch(e){throw _(`the directory it was started in could not be read (${e.message})`,h(F7(null,i.cwd),y))}let x=h(F7(b,i.cwd),y);if(v.kind===`unchecked`)throw _(`whether session ${e.sessionId} has a conversation could not be seen (${v.error})`,x);try{await r.typeShellLine(t,x)}catch(e){throw _(`the line could not be typed into its pane (${e.message})`,x)}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 \`${x}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${x}\`, ${cce[v.kind](e.sessionId)}, and its statusline follows lane B`}function oce(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 sce(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const cce={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},lce={"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 uce(e){let t=i$(e);return t.kind===`ready`?s$(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:a$(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:lce[t.kind]}var dce=class{owed=new Map;closed=!1;constructor(e){this.deps=e}clicked(e,t,n){let r=Qc.filter(e=>t[e]!==n[e]),i=this.take(e);for(let e of r)i.has(e)||i.set(e,t[e]);let a=e=>r.includes(e)?`click`:`owed`;if(this.deps.latest(e)!==null)return V7(e,i,n,a,this.deps.log);for(let[e,t]of i)t===n[e]&&i.delete(e);if(r.length>0){let t=[...i.keys()].map(e=>`${e} ${n[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}i.size>0&&this.owed.set(e,i);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(`,`)}`)}return[]}noted(e,t){return V7(e,this.take(e),t,()=>`owed`,this.deps.log)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}async setup({sessionId:e,lane:t,on:n,by:r}){if(this.closed)throw new uc(`lane setup`);let i=`by=${r} (session=${e})`,a=e=>{let r=`lane: ${t} ${n?`on`:`off`}: ${e instanceof Error?e.message:String(e)}`;return this.deps.log(`warn`,`${r} ${i}`),lc(r)},o;try{o=await tce[t][n?`on`:`off`](ece(()=>this.latestOf(e),this.paneOrder,(e,r)=>this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — the session moved from ${e.pane} to ${r.pane} while its step waited for the pane, so it takes ${r.pane}'s order ${i}`)),this.deps.host,this.deps.edge)}catch(e){return a(e)}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`done`?{kind:`ok`,said:o.said}:o.finished.then(e=>(this.deps.log(`info`,`lane: ${t} ${e} ${i}`),{kind:`ok`,said:e}),a)}paneOrder=(e,t)=>this.deps.paneOrder(e,()=>{if(this.closed)throw new uc(`lane setup`);return t()});latestOf(e){let t=this.deps.latest(e);return t===null?{kind:`gone`,reason:`this daemon no longer holds a request of session ${e}`}:{kind:`known`,session:t}}close(){this.closed=!0}};function V7(e,t,n,r,i){let a=[];for(let[o,s]of t)n[o]===s?i(`info`,`lane: ${o} ${s?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(o)} (session=${e})`):a.push({kind:`lane-setup`,sessionId:e,lane:o,on:n[o],by:r(o)});return a}const fce=[`request`,`feed`],H7=new WeakMap;let pce=0;const U7=e=>{let t=H7.get(e);if(t!==void 0)return t;let n=pce++;return H7.set(e,n),n};var mce=class{records=new Map;constructor(e=512){this.maxRecords=e}of(e,t){return this.records.get(W7(e,t))?.warnings??[]}ofSession(e,t,n){let r=U7(n.config),i=[];for(let n of fce){let a=this.records.get(W7(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=W7(e,t);this.records.delete(a),this.records.set(a,{generation:U7(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 W7=(e,t)=>`${t}\0${e}`,hce={session:({session:e})=>[`session`,e],pane:({tmux:e})=>[`pane`,Ac(e)],lane:({session:e,lane:t})=>[`lane`,e,t]};function gce(e){let t=hce[e.kind];return JSON.stringify(t(e))}var _ce=class{gathers=new F8;effects=new F8;open=!0;holder=null;gathersInFlight=0;take(e,t){if(!this.open)throw new uc(e);if(this.holder!==null)throw Error(`journal: ${e} took a turn inside ${this.holder}'s`);this.holder=e;try{return t()}finally{this.holder=null}}inTurn(){return this.holder}async gathering(e){this.gathersInFlight++;try{return await this.gathers.run(`gathers`,()=>{if(!this.open)throw new uc(`doctor`);return e()})}finally{this.gathersInFlight--}}performing(e,t){return this.effects.run(gce(e),t)}getStats(){return{gathers:this.gathersInFlight}}close(){this.open=!1}},vce=class{sessions=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown?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++;return{sessions:this.sessions.size,armed:e}}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?ute(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,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 yce(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,home:o,gates:s,host:c}=e,l=hr(o),u=_r(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 c3(i),g=e.launcher({inherited:c.env,stats:h.launchStats,signal:f.signal,now:d,observeWarnings:Tce(m,()=>ue)}),_=e.probe(g),v=e.storage(m,e.filesystem),y=new _ce,b=new d0(y,v.session),x=new O0(e.filesystem,b,m,v.history),S=Vi({...e.limits({startedAtMs:h.startedAt.getTime(),exit:a,launcher:g,log:m}),limitBytes:n}),C=new D3,w=new Yne,T=e.doctorStores(e.filesystem),E=new xj({filesystem:e.filesystem,clock:i,counters:h,logger:m}),ee=new Hj(m),D=new Uc({watchers:E,logger:m,clock:i}),te=new sM({launcher:g,clock:i,logger:m,ledger:ee,watchers:E,fileEvents:D}),O=Roe({launcher:g,host:c,pricing:e.pricing({cacheRoot:Jn(o),closing:f.signal,log:m}),watchers:E,fileEvents:D,clock:i,logger:m,ledger:ee}),{managedStorage:k}=O,ne=new ise,A=new Sne,re=Oce(()=>ye,{clock:i,now:d,log:m}),ie={to:o.name,signer:e.linkSigner},ae=kce({managedStorage:k,launcher:g,log:m,clock:i}),oe=e.heldSession(c.home),se=Cce(()=>ye,y,{edge:e.laneEdge(g,e=>ue.following(e),f.signal,_,oe,e.filesystem),host:{bundle:t.path,node:t.node,home:o,preload:_s(t.path,c)},log:m}),ce=wce(()=>ye,{launcher:g,heldSession:oe,home:o,owner:l.socket,bundle:t,signer:e.linkSigner,log:m}),le=Tse({file:l.linkIds,clock:i,retryMs:zZ.still,log:m}),ue=xce(()=>ye,{render:(e,t,n)=>IQ(ye,e,t,n),visibility:Sce(()=>ye,{launcher:g,clock:i,log:m}),linkIds:le,clock:i,instant:d,log:m}),de=new mce,fe=Oae(),{cache:pe,recorder:me}=bce({clock:i,stateDir:l.state,locations:u,sessionState:b,watchers:E,log:m,links:ie,gates:s,providers:O,updateFact:fe,sourceRuns:te,history:x,navigation:ne,source:lse,budgetBytes:()=>Hoe(n),wake:(e,t)=>ue.wake(e,t)});Ece({fileEvents:D,watcherRegistry:E,renderCache:pe,frameFeeds:ue});let{binaryWatch:he,updateWatch:ge}=Ace({clock:i,launcher:g,probe:_,filesystem:e.filesystem,bundle:t,stateDir:l.state,registryUrl:r,fetch:e.fetch,gates:s,updateFact:fe,exit:a,log:m}),_e=new S$(y),ve={gates:s,sessionState:b,stateDir:l.state,filesystem:e.filesystem,installedLayers:pe.installedLayers,storedRoot:l.storedRoot,locations:u,journalTurns:y,log:m,launcher:g,now:d,doctor:e.doctorEdge(g,e=>{pe.reload(e,{kind:`doctor`});let t=pe.getOrCreate(e);return{layers:t.configLayers,error:t.lastError,warning:t.lastWarning,unused:t.state.unused,config:t.state.config,repos:t.repos}},c,e.filesystem),doctorStores:T,probes:C,clients:w,mismatchRuns:_e,bundle:t.path,claudeInput:e.claudeInput(g),history:x,navigation:ne,links:ie,runs:ae,...jce(()=>ye)},ye={home:c.home,storedRoot:l.storedRoot,tmp:c.tmp,heldSession:oe,launcher:g,log:m,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:T,stats:h,handlerProbes:C,renderSightings:w,mismatchRuns:_e,watcherRegistry:E,refreshLedger:ee,fileEvents:D,payloadProviders:O,sessionState:b,rendererName:o.name,draw:Dce(()=>ye),effectSessions:A,menuIdle:re,journalTurns:y,links:ie,runs:ae,sourceRuns:te,laneSetups:se,tmuxStatusLines:ce,frameFeeds:ue,linkIds:le,renderWarnings:de,renderCache:pe,recorder:me,updateWatch:ge,limits:S,verbCtx:ve};return{stats:h,launcher:g,log:m,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(f.signal.throwIfAborted(),Jie(ye,e,t,n,r)),reply:async(e,t,n,r)=>(f.signal.throwIfAborted(),x8(ye,e,t,n,r)),subscribe:(e,t)=>(f.signal.throwIfAborted(),ue.subscribe(e,t)),reloadConfig:e=>{f.signal.throwIfAborted(),ve.reloadConfig(e)},arm(){f.signal.throwIfAborted(),D.start(l.watchProbe),he.arm(),ge.arm(),S.arm()},close(e){return Nce({...ye,journalTurns:y,sessionState:b,closing:f,binaryWatch:he},e),p=!0,g.settled()}}}function bce(e){let{budgetBytes:t,wake:n,providers:r,updateFact:i,sourceRuns:a,history:o,navigation:s,source:c,...l}=e,{log:u,sessionState:d,gates:f}=l;return EQ(e=>new nse({...l,storage:r.managedStorage,facts:sse({providers:r,update:()=>i.get(),runs:a}),source:c({providers:r,sessionState:d,stateGates:f.state,history:e=>o.depth(e),navigation:(e,t)=>s.depth(e,d,f.state.gateFor(t))})},{budgetBytes:t,observers:{onReload:(e,t,r,i)=>{u(`info`,Koe(e,r,i));for(let e of t)n(e,`reload`)},onViewChanged:e=>n(e,`data`),...e}}),u)}function xce(e,t){let{visibility:n,linkIds:r,...i}=t;return new GZ({...i,shown:e=>n.shown(e.hints.tmux),watching:()=>n.follow(),refreshes:()=>e().refreshLedger.totals(),encoders:Sse(r),watch:(t,n)=>(0,X.reaction)(()=>e().sessionState.revision(t),n),lanes:t=>RQ(e(),t),pin:t=>{let{renderCache:n}=e(),r=n.pin(t);return()=>{n.stopDrawing(t,`feed`),r()}},periods:zZ})}function Sce(e,{launcher:t,clock:n,log:r}){return new Ose({clock:n,listPanes:e=>sc(t,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,Y5]),listClients:e=>sc(t,{socket:e},`frames.visibility`,[`list-clients`,`-F`,X5]),sockets:()=>new Set(e().frameFeeds.watched().flatMap(({req:e})=>G7(e))),onAnswer:(t,n)=>e().tmuxStatusLines.answered(t,n),onChange:t=>e().frameFeeds.wakeWhere(`visibility`,e=>G7(e).some(e=>t.has(e))),intervalMs:1e3,log:r})}function G7({hints:{tmux:e}}){return e==null?[]:[e.socket]}function Cce(e,t,n){return new dce({...n,latest:t=>{let n=e().frameFeeds.latest(t);return n===null?null:XQ(n)},paneOrder:(e,n)=>t.performing({kind:`pane`,tmux:e},n)})}function wce(e,{launcher:t,heldSession:n,home:r,owner:i,bundle:a,signer:o,log:s}){return new Wse({edge:{run:(e,n)=>sc(t,{socket:e},`tmux-status`,n)},subscribe:(t,n)=>e().frameFeeds.subscribe(t,n),sessionInPane:t=>e().frameFeeds.newestWhere(ll(t,n)),handler:[...Object.entries(tr(r)).map(([e,t])=>`${e}=${Cn(t)}`),...[...a.node,a.path].map(Cn),`url-handle`].join(` `),owner:i,name:r.name,signer:o,log:s})}function Tce(e,t){return n=>{n.kind===`launch-pipes`?e(`warn`,n.text):e(n.fault===null?`info`:`warn`,n.fault===null?`launch lifeline running again`:`launch lifeline ${n.fault}; the next launch starts another`),t().wakeWhere(`data`,()=>!0)}}function Ece({fileEvents:e,watcherRegistry:t,renderCache:n,frameFeeds:r}){e.subscribe(e=>{switch(e.kind){case`period`:t.judge();return;case`caught-up`:n.reloadEvery({kind:`events-resumed`,since:e.since}),r.wakeWhere(`data`,()=>!0);return;case`moved`:r.wakeWhere(`data`,()=>!0);return}})}function Dce(e){return(t,n,r,i)=>QQ(e(),t,n,r,i)}function Oce(e,{clock:t,now:n,log:r}){return new vce({clock:t,now:n,close:async(t,n)=>{await u8({kind:`menu-idle`,session:t,idle:n},e())},failed:(e,t)=>p8(r,`menu-idle`,`session=${e}`,t)})}function kce({managedStorage:e,launcher:t,log:n,clock:r}){return new gc({supersede:(t,n)=>e.supersede(t,n),launch:t.launch,log:n,clock:r})}function Ace({clock:e,launcher:t,probe:n,filesystem:r,bundle:i,stateDir:a,registryUrl:o,fetch:s,gates:c,updateFact:l,exit:u,log:d}){let f=Aae({clock:e,targets:i.targets,intervalMs:K7,filesystem:r,held:()=>p.running(),exit:()=>u(0),log:d}),p=Dae({fact:l,clock:e,launcher:t,probe:n,entryUrl:i.entryUrl,digest:i.digest,actsDir:cae(a,i.path),intervalMs:K7,releaseIntervalMs:Mce,registryUrl:o,fetchImpl:s,gates:c,onApplied:()=>f.checkNow(),log:d});return{binaryWatch:f,updateWatch:p}}function jce(e){return{clickLanded:t=>e().menuIdle.clicked(t,e().verbCtx.now()),applyUpdate:()=>e().updateWatch.act(),serving:()=>e().limits.serving(),configFor:t=>e().renderCache.getOrCreate(t).state.config,reloadConfig:t=>e().renderCache.reload(t,{kind:`write`}),sourcesFor:t=>e().renderCache.getOrCreate(t).state.sources,lanes:{of:(t,n)=>zQ(e(),t,n),clicked:(t,n,r)=>ZQ(e(),t,n,r),arrived:t=>JQ(e(),t),setup:t=>e().laneSetups.setup(t)},diagnosticCopy:(t,n,r)=>e().renderCache.drawnCopy(t,n,r)}}const K7=60*1e3,Mce=360*60*1e3;function Nce(e,t){let{journalTurns:n,tmuxStatusLines:r,closing:i,laneSetups:a,frameFeeds:o,linkIds:s,menuIdle:c,updateWatch:l,binaryWatch:u,limits:d,recorder:f,renderCache:p,payloadProviders:{gitProvider:m,usageStore:h,tmuxService:g,hostService:_,managedStorage:v},runs:y,sourceRuns:b,fileEvents:x,watcherRegistry:S,sessionState:C,log:w}=e,T=[[`journalTurns close`,()=>n.close()],[`tmuxStatusLines restore`,()=>r.restoreAll(t)],[`launches abort`,()=>i.abort(Error(`the daemon closed`))],[`laneSetups close`,()=>a.close()],[`frameFeeds close`,()=>o.close()],[`linkIds close`,()=>s.close()],[`menuIdle dispose`,()=>c.dispose()],[`updateWatch close`,()=>l.close()],[`binaryWatch close`,()=>u.close()],[`limits disarm`,()=>d.disarm()],[`recorder close`,()=>f.close()],[`renderCache close`,()=>p.close()],[`gitService close`,()=>m.close()],[`usageStore close`,()=>h.close()],[`tmuxService close`,()=>g.close()],[`hostService close`,()=>_.close()],[`runs close`,()=>y.close()],[`sourceRuns close`,()=>b.close()],[`managedStorage close`,()=>v.close()],[`fileEvents close`,()=>x.close()],[`watcherRegistry close`,()=>S.closeAll()],[`sessionState close`,()=>C.close()]];for(let[e,t]of T)try{t()}catch(t){w(`warn`,`${e} failed: ${t.message}`)}}function Pce(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 Fce=class{clearTimer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t,n=500,r=Ie){this.filePath=e,this.clock=t,this.debounceMs=n,this.logger=r,this.writingPath=ct(e)}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 Pce(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=Qe(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=${Qe(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(),n=ct(this.filePath);try{m.mkdirSync(s.dirname(this.filePath),{recursive:!0});let 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,Qe(this.clock,t)),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`);try{m.rmSync(n,{force:!0})}catch(e){this.logger(`warn`,`session-state staged file left: ${e.message}`)}}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${Qe(this.clock,n)}ms held=${r}ms`)}};function Ice(e,t,n,r){return{session:new Fce(e.sessionState,n,500,t),history:X0(r,e.settingsHistory,e.storedRoot,t)}}function q7(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 J7(e,t){try{return m.accessSync(e,t),m.statSync(e).isFile()}catch{return!1}}function Lce(e){try{return m.realpathSync(e)}catch{return s.resolve(e)}}function Rce(e,t,n){let r=q7(`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 Y7=2e3;async function X7(e,t,n,r){let i=await sc(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function Z7(e,t){if(t.ok)return t.stdout;let n=ht(t,t.stdout);throw Error(`${e} failed (${gt(t)}${n===``?``:`: ${n}`})`)}function zce(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 Bce=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function Vce(e,t){return e.split(`
507
+ `,t:` `,r:`\r`,b:`\b`,a:`\x07`,v:`\v`,f:`\f`,0:`\0`},Mse=(e,t)=>e.startsWith(`\\;`,t)&&(e[t+2]??` `)===` `;function n7(e){let t=0,n=n=>e[t]===n&&(e[t+1]??` `)===` `,r=()=>{let n=[],r=e=>{n.push(...Buffer.from(e,`utf8`))},i=null;for(;t<e.length;){let a=e[t];if(i===null&&(a===` `||a===`;`))break;if(a===i)i=null,t++;else if(i===null&&(a===`"`||a===`'`))i=a,t++;else if(a===`\\`&&t+1<e.length){let i=/^[0-7]{3}/.exec(e.slice(t+1,t+4)),a=e[t+1];i===null?(r(jse[a]??a),t+=2):(n.push(parseInt(i[0],8)),t+=4)}else{let n=String.fromCodePoint(e.codePointAt(t));r(n),t+=n.length}}return Buffer.from(n).toString(`utf8`)},i=a=>{let o=[[]];for(;t<e.length;)if(e[t]===` `)t++;else if(e[t]===`;`||!a&&Mse(e,t))o.push([]),t+=e[t]===`;`?1:2;else if(a&&n(`}`)){t++;break}else n(`{`)?(t++,o.at(-1).push({block:i(!0)})):o.at(-1).push(r());return o.filter(e=>e.length>0)};return i(!1)}const r7=[`-T`,`root`,`MouseDown1Status`],i7=`@cc-candybar-renderer`,a7=`@cc-candybar-click`;function Nse(e,t,n,r){return`${e} ${fC(t,oC,uC([n,r]))}`}const o7=`#{m:ccb*,#{mouse_status_range}}`;function Pse(e){let t=`run-shell -b ${$5(`#{${a7}}/#{s/%//:pane_id}/#{q:mouse_status_range}`)}`,n=`display-message ${$5(`cc-candybar: no renderer takes clicks on this row: the one that drew it is older than this binding`)}`;return[`bind-key`,...r7,`if-shell`,`-F`,o7,`if-shell -F ${$5(`#{${a7}}`)} ${$5(t)} ${$5(n)}`,...e===null?[]:[e7(e)]]}const Fse=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m;function s7(e){let[t,...n]=e;if(t===void 0||n.length>0||t[0]!==`if-shell`)return;let r=t.slice(1);for(;typeof r[0]==`string`&&r[0].startsWith(`-`);)r=r.slice(1);if(r[0]!==o7)return;let i=r[2],a=i===void 0?[]:typeof i==`string`?n7(i):i.block;return a.length>0?a:null}function c7(e){let t=Fse.exec(e)?.[1],n=t===void 0?null:n7(t),r=n!==null&&s7(n)!==void 0;for(;n!==null;){let e=s7(n);if(e===void 0)break;n=e}return{ours:r,user:n}}const l7=`#{S:#{?#{!=:#{${i7}},},1,}}`;function Ise(e){return[`if-shell`,`-F`,l7,`${e7([Pse(e)])} ; display-message -p ccb:bound`]}function Lse(e){return[`if-shell`,`-F`,l7,`display-message -p ccb:held`,`${e===null?`unbind-key ${r7.join(` `)}`:`bind-key ${r7.join(` `)} ${Ase(e)}`} ; display-message -p ccb:restored`]}const u7=Zc.tmuxStatus.rows,d7=`@cc-candybar-status-prior`,f7=`@cc-candybar-status-wrote`,p7=Array.from({length:u7},(e,t)=>t),m7=e=>`@cc-candybar-row-${e}`,Rse=e=>`#[fill=terminal]#{${m7(e)}}`,h7=e=>`status-format[${e}]`;function zse(e){return e===0?`off`:e===1?`on`:String(e)}function g7(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 Bse(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 _7(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}const v7={kind:`ok`,stdout:``};function y7(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}const b7=`ccb:separator`;function x7(e){return y7(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,b7],e]))}function S7(e,t){let n=e.split(`${b7}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const C7=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],Vse=e=>[`show-options`,`-g`,`-q`,`-v`,e],w7=e=>[[`show-options`,`-t`,e],C7(e,`status`),...p7.map(t=>C7(e,h7(t)))];function T7(e){let[t=``,n=``,...r]=e,i=t.split(`
508
+ `).map(e=>e.split(` `)[0]??``),a={};for(let e of p7)i.includes(h7(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 E7(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,h7(Number(t)),_7(n)])]}const Hse=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...w7(e),...p7.map(e=>Vse(h7(e))),C7(e,d7),C7(e,f7)];function D7(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:g7(t)}catch(e){return{kind:`theirs`,why:`${d7} 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 O7=(e,t)=>[[`set-option`,`-t`,e,i7,t.name],[`set-option`,`-t`,e,a7,t.click]];function Use(e,t,n,r){let[i=``,...a]=t,o=T7(a.slice(0,2+u7)),s=a.slice(2+u7,2+2*u7),[c=``,l=``]=a.slice(2+2*u7);if(c!==``){let t=D7(c,l,n);return t.kind===`theirs`?t:{...t,commands:O7(e,r)}}let u=g7(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:u7-u},(e,t)=>[u+t,Rse(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,d7,JSON.stringify(p)],...O7(e,r),...E7(e,f)]}}const k7=e=>[...w7(e),C7(e,f7)];function A7(e,t,n){let r=T7(n.slice(0,2+u7)),i=n[2+u7]??``,a=[],o=[];if(Bse(r.formats,t.wrote))a.push(...E7(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,h7(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,_7(t.status)]):o.push(`status`)),a.push(...p7.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,m7(t)]),[`set-option`,`-q`,`-u`,`-t`,e,d7],[`set-option`,`-q`,`-u`,`-t`,e,f7],[`set-option`,`-q`,`-u`,`-t`,e,i7],[`set-option`,`-q`,`-u`,`-t`,e,a7]),{commands:a,kept:o}}const j7=[[`list-keys`,`-T`,`root`]];var Wse=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.kind===`runs`?t.tmux:r??null:null;if(r!==void 0&&(i===null||!jc(r,i))&&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=e.value,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 e=this.deps.sessionInPane(n);e!==null&&e!==n.sessionId&&this.release(n,`pane taken by sid=${JSON.stringify(e)}`)}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,k7(r));if(a===null)continue;let o=A7(r,i.prior,a);this.writeSync(e,t,o.commands),this.saidRestored(t,r,o.kept)}if(n.binding===`none`)continue;n.binding=`none`;let r=this.askSync(e,t,j7);if(r===null)continue;let i=this.bindingRestore(t,r[0]??``);if(i===null)continue;let a=this.writeSync(e,t,[i.command]);this.saidBindingRestore(t,a,i.user)}}linkAt(e){let t=Gse(e),[n,r,i,a,...o]=t??[];if(t===null||n===void 0||r===void 0||i===void 0||a===void 0||o.length>0)return{kind:`refused`,reason:`${oC} needs <socket>/<mac>/<pane>/<range>, got ${JSON.stringify(e)}`};if(!this.deps.signer.verifyBinding(n,r))return{kind:`refused`,reason:`a status-line click on ${JSON.stringify(n)} whose mac is not this renderer's binding's`};let s=[...this.held.values()].find(e=>e.socket===n&&e.pane===`%${i}`)?.frame?.links,c=s!==void 0&&Object.hasOwn(s,a)?s[a]:void 0;return c===void 0?{kind:`refused`,reason:`pane %${i}'s status line draws no link ${a} now`}:{kind:`link`,url:c}}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:`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,u7-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#{${d7}}\t#{${f7}}`]);if(n.kind===`ok`){let r=this.marks(e),i=[];for(let a of n.stdout.split(`
509
+ `)){let[n,o,s=``]=a.split(` `);if(n===void 0||o===void 0||o===``)continue;let c=D7(o,s,this.deps.owner);c.kind===`ours`?(t.layouts.set(n,{prior:c.prior,rows:[],status:c.status}),i.push(...O7(n,r))):this.leave(e,t,n,c.why)}await this.write(e,i)}t.layouts.size>0&&(t.binding=`owed`,this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)}`))}marks(e){return{name:this.deps.name,click:Nse(this.deps.handler,this.deps.name,e,this.deps.signer.signBinding(e))}}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,Hse(n));if(r===null||this.closed)return null;let i=Use(n,r,this.deps.owner,this.marks(e));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,m7(r),e])}),i!==n.status){let e=zse(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,f7,e])}(a.length===0||(await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,e7(a)]])).kind===`ok`)&&(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,k7(n));if(i===null)return;let a=A7(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){if(t.binding===`bound`)return;let n=t.binding,r=await this.ask(e,j7);if(r===null||this.closed)return;let{user:i}=c7(r[0]??``);t.binding=`bound`;let a=await this.write(e,[Ise(i),[`set-option`,`-g`,`-q`,`-u`,`@cc-candybar-binding-prior`]]),o=a.kind===`ok`&&a.stdout.includes(`ccb:bound`);o||(t.binding=n);let s=o?`bound MouseDown1Status over ${M7(i)}`:a.kind===`ok`?`left MouseDown1Status unbound: no session names a renderer`:`MouseDown1Status not bound: ${a.reason}`;this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${s}`)}async restoreBinding(e,t){if(t.binding===`none`)return;t.binding=`none`;let n=await this.ask(e,j7);if(n===null)return;let r=this.bindingRestore(e,n[0]??``);if(r===null)return;let i=await this.write(e,[r.command]);this.saidBindingRestore(e,i,r.user)}bindingRestore(e,t){let n=c7(t);return n.ours?{command:Lse(n.user),user:n.user}:(this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} left MouseDown1Status as it is: not a cc-candybar binding`),null)}saidBindingRestore(e,t,n){let r=t.kind===`ok`?t.stdout.includes(`ccb:restored`)?`restored MouseDown1Status to ${M7(n)}`:t.stdout.includes(`ccb:held`)?`left MouseDown1Status bound: a session still names a renderer`:`MouseDown1Status restore said neither way: ${JSON.stringify(t.stdout)}`:`MouseDown1Status not restored: ${t.reason}`;this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r}`)}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){return this.counted(e,await this.deps.edge.run(e,t))}async ask(e,t){let n=await this.run(e,x7(t));return n.kind===`ok`?S7(n.stdout,t.length):null}askSync(e,t,n){let r=this.counted(t,e(t,x7(n)));return r.kind===`ok`?S7(r.stdout,n.length):null}async write(e,t){return t.length===0?v7:(this.writes++,this.run(e,y7(t)))}writeSync(e,t,n){return n.length===0?v7:(this.writes++,this.counted(t,e(t,y7(n))))}};const M7=e=>e===null?`unbound`:JSON.stringify(e7(e));function Gse(e){try{return jte(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),N7=e=>({arity:e,keep:!1}),Kse={"--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":N7(`none`),"--background":N7(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":N7(`optional`),"-c":N7(`none`),"--continue":N7(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":N7(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":N7(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":N7(`none`),"--forward-subagent-text":$(`none`),"--from-pr":N7(`optional`),"-h":N7(`none`),"--help":N7(`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":N7(`none`),"--print":N7(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":N7(`optional`),"--resume":N7(`optional`),"--safe-mode":$(`none`),"--session-id":N7(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":N7(`optional`),"--tmux":N7(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":N7(`none`),"--version":N7(`none`),"-w":N7(`optional`),"--worktree":N7(`optional`)},qse={resume:`--resume`,fresh:`--session-id`};function Jse(e){return[qse[e.kind],e.sessionId]}const P7=e=>e.startsWith(`-`)&&e!==`-`;function F7(e,t){let n=I7(t);return n===null?{dir:e??t,args:[]}:e!==null&&Yse(e,n.top)?{dir:e,args:[]}:{dir:e===null||I7(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const Yse=(e,t)=>e===t||e.startsWith(t+s.sep);function Xse(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!P7(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=Kse[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=>!P7(e)):o.arity===`variadic`?Zse(n.slice(r),e=>!P7(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 I7(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 Zse(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const L7=`candybar-band@cc-candybar`,Qse=s.join(`bin`,`cc-candybar-native`),$se=pI(`/reload-plugins`);function ece(e,t,n){let r=e();if(r.kind===`gone`)throw Error(r.reason);let i=()=>{let t=e();if(t.kind===`gone`)return t;let n=l$(t.session.hints.tmux);return n.kind===`refused`?n:{kind:`in`,session:t.session,tmux:n.hint}},a=async e=>{let r=i();if(r.kind!==`in`)return r;let o=await t(r.tmux,async()=>{let t=i();return t.kind!==`in`||!jc(t.tmux,r.tmux)?t:{kind:`held`,value:await e(t.session,t.tmux)}});return o.kind===`in`?(n(r.tmux,o.tmux),a(e)):o};return{session:r.session,inPane:a}}function R7(e,t){if(e.kind!==`held`)throw new R(t(e.reason));return e.value}const z7=e=>({kind:`done`,said:e});function B7(e){let t=l$(e.hints.tmux);if(t.kind===`refused`)throw new R(t.reason);return t.hint}const tce={band:{on:async(e,t,n)=>{let r=zn(t.bundle);if(r===null)throw new R(`${Zc.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,Qse);if(!n.fileExists(i))throw new R(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${L7} from ${r}`,finished:nce(e,r,n)}},off:async()=>z7(`nothing to stop: the band mod ends its child once the lane is off`)},statusline:{on:async(e,t,n)=>{let r=B7(e.session),i=N(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new R(`${Zc.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:e.inPane((e,r)=>ace(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)).then(e=>R7(e,e=>`Claude Code was not restarted under the attach launcher: ${e}`))}},off:async()=>z7(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>R7(await e.inPane(async(e,r)=>{let i=await n.barPanes(r);return i.length>0?z7(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):z7(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],tr(t.home))} under ${r.pane}`)}),e=>`no bar pane was opened: ${e}`),off:async(e,t,n)=>{let r=await e.inPane(async(e,t)=>{let r=await n.barPanes(t);for(let e of r)await n.closePane(t,e);return z7(r.length===0?`no bar pane draws ${t.pane}'s bar`:`closed bar pane ${r.join(`, `)}`)});return r.kind===`refused`?z7(`no bar pane to close: ${r.reason}`):R7(r,e=>e)}},tmuxStatus:{on:async({session:e})=>z7(`the daemon draws ${B7(e).pane}'s bar in its status line`),off:async()=>z7(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function nce(e,t,n){let{session:r}=e,i={sessionId:r.sessionId,projectDir:r.origin.projectDir,claudeConfigDir:r.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],i),await n.claude([`plugin`,`install`,L7],i);let a=await e.inPane((e,t)=>u$(n.claudeInput,t,$se)),o=a.kind===`held`?a.value:{kind:`refused`,reason:a.reason};if(o.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${o.reason} — or type /reload-plugins yourself`);return`installed ${L7} from ${t} and typed /reload-plugins into ${o.pane}`}const rce=new Set([Go,DP]);function ice(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function ace(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,En(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}) — ${Zc.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);let o=await r.paneClaude(t);if(o.pid!==i.pid||o.startTime!==i.startTime)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}, started ${i.startTime}; now pid ${o.pid}, started ${o.startTime}), so it was not restarted under the attach launcher`);let s=uce(await r.claudeInput.read(t));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s} — then turn ${Zc.statusline.label} off and on again`);let c=oce(e,r.presence(e.transcript));if(c!==null)throw Error(`Claude Code in ${t.pane} was left running: ${c}`);let l=Xse(i.argv);if(l.kind===`refused`)throw Error(`${l.reason} — restart it with that flag removed`);let u=ice(i.env),d=u.get(`PATH`),f=r.launcherNode(d);if(f.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${f.why}`);let p=r.onPath(`claude`,d)===i.executable?`claude`:i.executable,m=[...u].filter(([e])=>rce.has(e)),h=(e,t)=>kn(n.preload,{dir:e.dir,env:m,program:p,args:[...e.args,...l.args,...Jse(t)]}),g=r.heldSession({pid:i.pid,startTime:i.startTime,configDir:Ko(Object.fromEntries(u),i.cwd)});if(g.kind!==`holds`)throw Error(`Claude Code in ${t.pane} was left running: ${g.why}, so which session it runs is unknown`);if(g.sessionId!==e.sessionId)throw Error(`Claude Code in ${t.pane} now runs session ${g.sessionId}, not ${e.sessionId}, so it was not restarted under the attach launcher — turn ${Zc.statusline.label} off and on again from the bar in ${t.pane} to restart that one`);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 _=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),v=sce(e,r.presence(e.transcript)),y=v.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:v,b;try{b=await r.paneDir(t,i.parent)}catch(e){throw _(`the directory it was started in could not be read (${e.message})`,h(F7(null,i.cwd),y))}let x=h(F7(b,i.cwd),y);if(v.kind===`unchecked`)throw _(`whether session ${e.sessionId} has a conversation could not be seen (${v.error})`,x);try{await r.typeShellLine(t,x)}catch(e){throw _(`the line could not be typed into its pane (${e.message})`,x)}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 \`${x}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${x}\`, ${cce[v.kind](e.sessionId)}, and its statusline follows lane B`}function oce(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 sce(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const cce={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},lce={"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 uce(e){let t=i$(e);return t.kind===`ready`?s$(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:a$(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:lce[t.kind]}var dce=class{owed=new Map;closed=!1;constructor(e){this.deps=e}clicked(e,t,n){let r=Qc.filter(e=>t[e]!==n[e]),i=this.take(e);for(let e of r)i.has(e)||i.set(e,t[e]);let a=e=>r.includes(e)?`click`:`owed`;if(this.deps.latest(e)!==null)return V7(e,i,n,a,this.deps.log);for(let[e,t]of i)t===n[e]&&i.delete(e);if(r.length>0){let t=[...i.keys()].map(e=>`${e} ${n[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}i.size>0&&this.owed.set(e,i);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(`,`)}`)}return[]}noted(e,t){return V7(e,this.take(e),t,()=>`owed`,this.deps.log)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}async setup({sessionId:e,lane:t,on:n,by:r}){if(this.closed)throw new uc(`lane setup`);let i=`by=${r} (session=${e})`,a=e=>{let r=`lane: ${t} ${n?`on`:`off`}: ${e instanceof Error?e.message:String(e)}`;return this.deps.log(`warn`,`${r} ${i}`),lc(r)},o;try{o=await tce[t][n?`on`:`off`](ece(()=>this.latestOf(e),this.paneOrder,(e,r)=>this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — the session moved from ${e.pane} to ${r.pane} while its step waited for the pane, so it takes ${r.pane}'s order ${i}`)),this.deps.host,this.deps.edge)}catch(e){return a(e)}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`done`?{kind:`ok`,said:o.said}:o.finished.then(e=>(this.deps.log(`info`,`lane: ${t} ${e} ${i}`),{kind:`ok`,said:e}),a)}paneOrder=(e,t)=>this.deps.paneOrder(e,()=>{if(this.closed)throw new uc(`lane setup`);return t()});latestOf(e){let t=this.deps.latest(e);return t===null?{kind:`gone`,reason:`this daemon no longer holds a request of session ${e}`}:{kind:`known`,session:t}}close(){this.closed=!0}};function V7(e,t,n,r,i){let a=[];for(let[o,s]of t)n[o]===s?i(`info`,`lane: ${o} ${s?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(o)} (session=${e})`):a.push({kind:`lane-setup`,sessionId:e,lane:o,on:n[o],by:r(o)});return a}const fce=[`request`,`feed`],H7=new WeakMap;let pce=0;const U7=e=>{let t=H7.get(e);if(t!==void 0)return t;let n=pce++;return H7.set(e,n),n};var mce=class{records=new Map;constructor(e=512){this.maxRecords=e}of(e,t){return this.records.get(W7(e,t))?.warnings??[]}ofSession(e,t,n){let r=U7(n.config),i=[];for(let n of fce){let a=this.records.get(W7(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=W7(e,t);this.records.delete(a),this.records.set(a,{generation:U7(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 W7=(e,t)=>`${t}\0${e}`,hce={session:({session:e})=>[`session`,e],pane:({tmux:e})=>[`pane`,Ac(e)],lane:({session:e,lane:t})=>[`lane`,e,t]};function gce(e){let t=hce[e.kind];return JSON.stringify(t(e))}var _ce=class{gathers=new F8;effects=new F8;open=!0;holder=null;gathersInFlight=0;take(e,t){if(!this.open)throw new uc(e);if(this.holder!==null)throw Error(`journal: ${e} took a turn inside ${this.holder}'s`);this.holder=e;try{return t()}finally{this.holder=null}}inTurn(){return this.holder}async gathering(e){this.gathersInFlight++;try{return await this.gathers.run(`gathers`,()=>{if(!this.open)throw new uc(`doctor`);return e()})}finally{this.gathersInFlight--}}performing(e,t){return this.effects.run(gce(e),t)}getStats(){return{gathers:this.gathersInFlight}}close(){this.open=!1}},vce=class{sessions=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown?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++;return{sessions:this.sessions.size,armed:e}}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?dte(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,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 yce(e){let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a,home:o,gates:s,host:c}=e,l=hr(o),u=_r(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 c3(i),g=e.launcher({inherited:c.env,stats:h.launchStats,signal:f.signal,now:d,observeWarnings:Tce(m,()=>de)}),_=e.probe(g),v=e.storage(m,e.filesystem),y=new _ce,b=new d0(y,v.session),x=new O0(e.filesystem,b,m,v.history),S=Vi({...e.limits({startedAtMs:h.startedAt.getTime(),exit:a,launcher:g,log:m}),limitBytes:n}),C=new D3,w=new Yne,T=e.doctorStores(e.filesystem),E=new xj({filesystem:e.filesystem,clock:i,counters:h,logger:m}),ee=new Hj(m),D=new Uc({watchers:E,logger:m,clock:i}),te=new sM({launcher:g,clock:i,logger:m,ledger:ee,watchers:E,fileEvents:D}),O=Roe({launcher:g,host:c,pricing:e.pricing({cacheRoot:Jn(o),closing:f.signal,log:m}),watchers:E,fileEvents:D,clock:i,logger:m,ledger:ee}),{managedStorage:k}=O,ne=new ise,A=new Sne,re=Oce(()=>be,{clock:i,now:d,log:m}),ie={to:o.name,signer:e.linkSigner},ae=kce({managedStorage:k,launcher:g,log:m,clock:i}),oe=e.heldSession(c.home),se=e.claudeInput(g),ce=Cce(()=>be,y,{edge:e.laneEdge(g,e=>de.following(e),f.signal,_,oe,e.filesystem,se),host:{bundle:t.path,node:t.node,home:o,preload:_s(t.path,c)},log:m}),le=wce(()=>be,{launcher:g,heldSession:oe,home:o,owner:l.socket,bundle:t,signer:e.linkSigner,log:m}),ue=Tse({file:l.linkIds,clock:i,retryMs:zZ.still,log:m}),de=xce(()=>be,{render:(e,t,n)=>IQ(be,e,t,n),visibility:Sce(()=>be,{launcher:g,clock:i,log:m}),linkIds:ue,clock:i,instant:d,log:m}),fe=new mce,pe=Oae(),{cache:me,recorder:he}=bce({clock:i,stateDir:l.state,locations:u,sessionState:b,watchers:E,log:m,links:ie,gates:s,providers:O,updateFact:pe,sourceRuns:te,history:x,navigation:ne,source:lse,budgetBytes:()=>Hoe(n),wake:(e,t)=>de.wake(e,t)});Ece({fileEvents:D,watcherRegistry:E,renderCache:me,frameFeeds:de});let{binaryWatch:ge,updateWatch:_e}=Ace({clock:i,launcher:g,probe:_,filesystem:e.filesystem,bundle:t,stateDir:l.state,registryUrl:r,fetch:e.fetch,gates:s,updateFact:pe,exit:a,log:m}),ve=new S$(y),ye={gates:s,sessionState:b,stateDir:l.state,filesystem:e.filesystem,installedLayers:me.installedLayers,storedRoot:l.storedRoot,locations:u,journalTurns:y,log:m,launcher:g,now:d,doctor:e.doctorEdge(g,e=>{me.reload(e,{kind:`doctor`});let t=me.getOrCreate(e);return{layers:t.configLayers,error:t.lastError,warning:t.lastWarning,unused:t.state.unused,config:t.state.config,repos:t.repos}},c,e.filesystem),doctorStores:T,probes:C,clients:w,mismatchRuns:ve,bundle:t.path,claudeInput:se,history:x,navigation:ne,links:ie,runs:ae,...jce(()=>be)},be={home:c.home,storedRoot:l.storedRoot,tmp:c.tmp,heldSession:oe,launcher:g,log:m,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:T,stats:h,handlerProbes:C,renderSightings:w,mismatchRuns:ve,watcherRegistry:E,refreshLedger:ee,fileEvents:D,payloadProviders:O,sessionState:b,rendererName:o.name,draw:Dce(()=>be),effectSessions:A,menuIdle:re,journalTurns:y,links:ie,runs:ae,sourceRuns:te,laneSetups:ce,tmuxStatusLines:le,frameFeeds:de,linkIds:ue,renderWarnings:fe,renderCache:me,recorder:he,updateWatch:_e,limits:S,verbCtx:ye};return{stats:h,launcher:g,log:m,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(f.signal.throwIfAborted(),Jie(be,e,t,n,r)),reply:async(e,t,n,r)=>(f.signal.throwIfAborted(),x8(be,e,t,n,r)),subscribe:(e,t)=>(f.signal.throwIfAborted(),de.subscribe(e,t)),reloadConfig:e=>{f.signal.throwIfAborted(),ye.reloadConfig(e)},arm(){f.signal.throwIfAborted(),D.start(l.watchProbe),ge.arm(),_e.arm(),S.arm()},close(e){return Nce({...be,journalTurns:y,sessionState:b,closing:f,binaryWatch:ge},e),p=!0,g.settled()}}}function bce(e){let{budgetBytes:t,wake:n,providers:r,updateFact:i,sourceRuns:a,history:o,navigation:s,source:c,...l}=e,{log:u,sessionState:d,gates:f}=l;return EQ(e=>new nse({...l,storage:r.managedStorage,facts:sse({providers:r,update:()=>i.get(),runs:a}),source:c({providers:r,sessionState:d,stateGates:f.state,history:e=>o.depth(e),navigation:(e,t)=>s.depth(e,d,f.state.gateFor(t))})},{budgetBytes:t,observers:{onReload:(e,t,r,i)=>{u(`info`,Koe(e,r,i));for(let e of t)n(e,`reload`)},onViewChanged:e=>n(e,`data`),...e}}),u)}function xce(e,t){let{visibility:n,linkIds:r,...i}=t;return new GZ({...i,shown:e=>n.shown(e.hints.tmux),watching:()=>n.follow(),refreshes:()=>e().refreshLedger.totals(),encoders:Sse(r),watch:(t,n)=>(0,X.reaction)(()=>e().sessionState.revision(t),n),lanes:t=>RQ(e(),t),pin:t=>{let{renderCache:n}=e(),r=n.pin(t);return()=>{n.stopDrawing(t,`feed`),r()}},periods:zZ})}function Sce(e,{launcher:t,clock:n,log:r}){return new Ose({clock:n,listPanes:e=>sc(t,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,Y5]),listClients:e=>sc(t,{socket:e},`frames.visibility`,[`list-clients`,`-F`,X5]),sockets:()=>new Set(e().frameFeeds.watched().flatMap(({req:e})=>G7(e))),onAnswer:(t,n)=>e().tmuxStatusLines.answered(t,n),onChange:t=>e().frameFeeds.wakeWhere(`visibility`,e=>G7(e).some(e=>t.has(e))),intervalMs:1e3,log:r})}function G7({hints:{tmux:e}}){return e==null?[]:[e.socket]}function Cce(e,t,n){return new dce({...n,latest:t=>{let n=e().frameFeeds.latest(t);return n===null?null:XQ(n)},paneOrder:(e,n)=>t.performing({kind:`pane`,tmux:e},n)})}function wce(e,{launcher:t,heldSession:n,home:r,owner:i,bundle:a,signer:o,log:s}){return new Wse({edge:{run:(e,n)=>sc(t,{socket:e},`tmux-status`,n)},subscribe:(t,n)=>e().frameFeeds.subscribe(t,n),sessionInPane:t=>e().frameFeeds.newestWhere(ll(t,n)),handler:[...Object.entries(tr(r)).map(([e,t])=>`${e}=${Cn(t)}`),...[...a.node,a.path].map(Cn),`url-handle`].join(` `),owner:i,name:r.name,signer:o,log:s})}function Tce(e,t){return n=>{n.kind===`launch-pipes`?e(`warn`,n.text):e(n.fault===null?`info`:`warn`,n.fault===null?`launch lifeline running again`:`launch lifeline ${n.fault}; the next launch starts another`),t().wakeWhere(`data`,()=>!0)}}function Ece({fileEvents:e,watcherRegistry:t,renderCache:n,frameFeeds:r}){e.subscribe(e=>{switch(e.kind){case`period`:t.judge();return;case`caught-up`:n.reloadEvery({kind:`events-resumed`,since:e.since}),r.wakeWhere(`data`,()=>!0);return;case`moved`:r.wakeWhere(`data`,()=>!0);return}})}function Dce(e){return(t,n,r,i)=>QQ(e(),t,n,r,i)}function Oce(e,{clock:t,now:n,log:r}){return new vce({clock:t,now:n,close:async(t,n)=>{await u8({kind:`menu-idle`,session:t,idle:n},e())},failed:(e,t)=>p8(r,`menu-idle`,`session=${e}`,t)})}function kce({managedStorage:e,launcher:t,log:n,clock:r}){return new gc({supersede:(t,n)=>e.supersede(t,n),launch:t.launch,log:n,clock:r})}function Ace({clock:e,launcher:t,probe:n,filesystem:r,bundle:i,stateDir:a,registryUrl:o,fetch:s,gates:c,updateFact:l,exit:u,log:d}){let f=Aae({clock:e,targets:i.targets,intervalMs:K7,filesystem:r,held:()=>p.running(),exit:()=>u(0),log:d}),p=Dae({fact:l,clock:e,launcher:t,probe:n,entryUrl:i.entryUrl,digest:i.digest,actsDir:cae(a,i.path),intervalMs:K7,releaseIntervalMs:Mce,registryUrl:o,fetchImpl:s,gates:c,onApplied:()=>f.checkNow(),log:d});return{binaryWatch:f,updateWatch:p}}function jce(e){return{clickLanded:t=>e().menuIdle.clicked(t,e().verbCtx.now()),applyUpdate:()=>e().updateWatch.act(),serving:()=>e().limits.serving(),configFor:t=>e().renderCache.getOrCreate(t).state.config,reloadConfig:t=>e().renderCache.reload(t,{kind:`write`}),sourcesFor:t=>e().renderCache.getOrCreate(t).state.sources,lanes:{of:(t,n)=>zQ(e(),t,n),clicked:(t,n,r)=>ZQ(e(),t,n,r),arrived:t=>JQ(e(),t),setup:t=>e().laneSetups.setup(t)},diagnosticCopy:(t,n,r)=>e().renderCache.drawnCopy(t,n,r)}}const K7=60*1e3,Mce=360*60*1e3;function Nce(e,t){let{journalTurns:n,tmuxStatusLines:r,closing:i,laneSetups:a,frameFeeds:o,linkIds:s,menuIdle:c,updateWatch:l,binaryWatch:u,limits:d,recorder:f,renderCache:p,payloadProviders:{gitProvider:m,usageStore:h,tmuxService:g,hostService:_,managedStorage:v},runs:y,sourceRuns:b,fileEvents:x,watcherRegistry:S,sessionState:C,log:w}=e,T=[[`journalTurns close`,()=>n.close()],[`tmuxStatusLines restore`,()=>r.restoreAll(t)],[`launches abort`,()=>i.abort(Error(`the daemon closed`))],[`laneSetups close`,()=>a.close()],[`frameFeeds close`,()=>o.close()],[`linkIds close`,()=>s.close()],[`menuIdle dispose`,()=>c.dispose()],[`updateWatch close`,()=>l.close()],[`binaryWatch close`,()=>u.close()],[`limits disarm`,()=>d.disarm()],[`recorder close`,()=>f.close()],[`renderCache close`,()=>p.close()],[`gitService close`,()=>m.close()],[`usageStore close`,()=>h.close()],[`tmuxService close`,()=>g.close()],[`hostService close`,()=>_.close()],[`runs close`,()=>y.close()],[`sourceRuns close`,()=>b.close()],[`managedStorage close`,()=>v.close()],[`fileEvents close`,()=>x.close()],[`watcherRegistry close`,()=>S.closeAll()],[`sessionState close`,()=>C.close()]];for(let[e,t]of T)try{t()}catch(t){w(`warn`,`${e} failed: ${t.message}`)}}function Pce(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 Fce=class{clearTimer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t,n=500,r=Ie){this.filePath=e,this.clock=t,this.debounceMs=n,this.logger=r,this.writingPath=ct(e)}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 Pce(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=Qe(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=${Qe(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(),n=ct(this.filePath);try{m.mkdirSync(s.dirname(this.filePath),{recursive:!0});let 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,Qe(this.clock,t)),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`);try{m.rmSync(n,{force:!0})}catch(e){this.logger(`warn`,`session-state staged file left: ${e.message}`)}}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${Qe(this.clock,n)}ms held=${r}ms`)}};function Ice(e,t,n,r){return{session:new Fce(e.sessionState,n,500,t),history:X0(r,e.settingsHistory,e.storedRoot,t)}}function q7(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 J7(e,t){try{return m.accessSync(e,t),m.statSync(e).isFile()}catch{return!1}}function Lce(e){try{return m.realpathSync(e)}catch{return s.resolve(e)}}function Rce(e,t,n){let r=q7(`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 Y7=2e3;async function X7(e,t,n,r){let i=await sc(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function Z7(e,t){if(t.ok)return t.stdout;let n=ht(t,t.stdout);throw Error(`${e} failed (${gt(t)}${n===``?``:`: ${n}`})`)}function zce(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 Bce=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function Vce(e,t){return e.split(`
510
510
  `).flatMap(e=>{let[n,...r]=e.trim().split(` `);return Bce.exec(r.join(` `))?.[1]===t?[n]:[]})}const Hce=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function Uce(e,t,n){for(let r of f2(d2(e),t)){if(r.command.split(` `).some(e=>Hce.test(e)))return!0;if(r.pid===n)return!1}return!1}const Wce=[`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(`
511
- `);async function Gce(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=Z7(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,Wce,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function Q7(e,t,n){return Z7(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function $7(e,t){let n=await sc(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 Q7(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function Kce(e,t){let{panePid:n,cwd:r,foreground:i}=await $7(e,t),a=await Q7(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await Gce(e,i),s=d2(a).get(i)?.ppid;if(s===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);let c=rn(i,await tn(i,t=>e.launch(t)));if(c.startTime===null)throw Error(`the start of pane ${t.pane}'s foreground job ${i} could not be read (${c.why})`);return{pid:i,startTime:c.startTime,executable:await m.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:s,fromShell:i!==n,attached:Uce(a,i,n)}}function qce(e,t){let n=e9(e,t);return n.torn?e9(e,t).held:n.held}function e9(e,t){let n;try{n=m.readFileSync(e,`utf8`)}catch(t){return{torn:!1,held:t.code===`ENOENT`?{kind:`none`,why:`it keeps no session record at ${e} (update Claude Code with \`claude update\`: recent releases keep one)`}:{kind:`unread`,why:t.message}}}let r;try{r=JSON.parse(n)}catch(t){return{torn:!0,held:{kind:`unread`,why:`its session record ${e} is not JSON (${t.message})`}}}let{sessionId:i,procStart:a}=typeof r==`object`&&r?r:{},o=$t(a);return{torn:!1,held:typeof i!=`string`||i===``?{kind:`unread`,why:`its session record ${e} names no session`}:a===void 0?{kind:`unread`,why:`its session record ${e} names no process start (update Claude Code with \`claude update\`: recent releases name one)`}:o===void 0?{kind:`unread`,why:`its session record ${e} names its process start as ${JSON.stringify(a)}, not in the form \`ps -o lstart=\` prints it`}:o===t.startTime?{kind:`holds`,sessionId:i}:{kind:`none`,why:`its session record ${e} was left by a Claude Code that has exited: the record names a process started ${o}, and pid ${t.pid} is a process started ${t.startTime}`}}}const Jce=e=>t=>qce(s.join(qo(t.configDir,e),`sessions`,`${t.pid}.json`),t);function Yce(e,t,n,r,i,a,o){let s=e=>et(r,e,n);return{claudeInput:h$(e),barPanes:async t=>Vce(await X7(e,t,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_start_command}`]),t.pane),openBarPane:async(t,n,r)=>(await X7(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 X7(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void Z7(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:Q0(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>_c(o,e)===`present`,presence:e=>_c(o,e),paneClaude:t=>Kce(e,t),heldSession:a,paneDir:async(t,n)=>{let i=r.monotonic()+Y7;for(;;){let a=await $7(e,t);if(a.foreground===n){if(a.cwd===``)throw Error(`tmux read no directory for pane ${t.pane}`);return a.cwd}if(r.monotonic()>i)throw Error(`the shell in pane ${t.pane} (pid ${n}) did not take its terminal back within ${Y7/1e3} s`);await s(100)}},launcherNode:e=>Rce(e,e=>J7(e,m.constants.X_OK),Lce),onPath:(e,t)=>{let n=q7(e,t,e=>J7(e,m.constants.X_OK));return n===null?null:m.realpathSync(n)},followed:async(e,n,i)=>{let a=r.monotonic()+i;for(;!t(e).has(n);){if(r.monotonic()>a)return!1;await s(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`?zce(i.stdout):null;return a===null?(Z7(`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 s(100)}return!0},typeShellLine:async(t,n)=>void await X7(e,t,p$(t.pane,`cc-candybar-lane`,[]),n)}}const Xce=/^[0-9a-f]{64}$/;function t9(e,t){return oe(`sha256`,e).update(JSON.stringify(t)).digest()}const n9=e=>[e.sessionId,e.action,e.declaration,e.evaluated],r9=e=>[sC,e];function Zce(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);let t=t=>t9(e,t).toString(`hex`),n=(t,n)=>Xce.test(n)&&le(Buffer.from(n,`hex`),t9(e,t));return{sign:e=>t(n9(e)),verify:(e,t)=>n(n9(e),t),signBinding:e=>t(r9(e)),verifyBinding:(e,t)=>n(r9(e),t)}}function i9(e){return s.join(e,`link.key`)}function a9(e){let t,n=()=>t??=Qce(e);return{sign:e=>n().sign(e),verify:(e,t)=>n().verify(e,t),signBinding:e=>n().signBinding(e),verifyBinding:(e,t)=>n().verifyBinding(e,t)}}function Qce(e){let t;try{t=m.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;$ce(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 Zce(t)}function $ce(e){m.mkdirSync(s.dirname(e),{recursive:!0});let t=ct(e);m.writeFileSync(t,se(32),{mode:384,flag:`wx`});try{m.linkSync(t,e)}catch(e){if(e.code!==`EEXIST`)throw e}finally{m.unlinkSync(t)}}function ele(e,t,n){return{daemonLog:t,launcher:e=>_n(e,n),storage:(t,r)=>Ice(e,t,n,r),doctorStores:t=>k4(t,e.state),doctorEdge:V4,claudeInput:h$,probe:on,laneEdge:(e,t,r,i,a,o)=>Yce(e,t,r,n,i,a,o),heldSession:Jce,linkSigner:a9(i9(e.state)),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>qi(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),fetch,pricing:e=>Wae({...e,clock:n}),filesystem:mn}}function o9(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}const tle={kind:`awaiting`},s9=e=>e.kind===`awaiting`||e.kind===`answering`||e.kind===`unattended`&&!e.lapsed,c9=e=>e.kind!==`streaming`&&e.kind!==`closed`,l9=e=>e.kind===`answered`&&e.by===`backstop`||(e.kind===`unattended`||e.kind===`closed`)&&e.lapsed,nle=e=>e.kind===`closed`,u9=e=>({next:e,effects:[]}),d9=(e,t)=>({next:{kind:`answered`,by:e},effects:[{kind:`answer`,answer:t}]}),rle=(e,t)=>{switch(t.kind){case`read`:return e.kind===`awaiting`?u9(t.waits?{kind:`answering`}:{kind:`unattended`,lapsed:!1}):e.kind===`answered`&&e.by===`backstop`&&!t.waits?u9({kind:`unattended`,lapsed:!0}):u9(e);case`unreadable`:return e.kind===`awaiting`?d9(`reply`,t.answer):u9(e);case`deadline`:if(e.kind===`awaiting`||e.kind===`answering`){let e=d9(`backstop`,t.answer);return{...e,effects:[{kind:`count-timeout`},...e.effects]}}return e.kind===`unattended`&&!e.lapsed?{next:{kind:`unattended`,lapsed:!0},effects:[{kind:`count-timeout`}]}:u9(e);case`reply`:return e.kind===`answering`||e.kind===`held`?d9(`reply`,t):e.kind===`answered`&&e.by===`backstop`||e.kind===`closed`&&e.lapsed?{next:e,effects:t.exitAfterFlush===null?[]:[{kind:`exit-dropped`}]}:e.kind===`closed`?{next:e,effects:t.exitAfterFlush===null?[]:[{kind:`exit`,code:t.exitAfterFlush}]}:u9(e);case`subscribe`:return e.kind===`answering`?{next:e,effects:[{kind:`attach`,sessionId:t.sessionId,lane:t.lane}]}:u9(e);case`subscribed`:return e.kind===`answering`?u9({kind:`streaming`,unsubscribe:t.unsubscribe}):{next:e,effects:[{kind:`unsubscribe`,unsubscribe:t.unsubscribe}]};case`held`:return e.kind===`answering`?{next:{kind:`held`},effects:[{kind:`start`,start:t.start}]}:u9(e);case`threw`:return e.kind===`answering`||e.kind===`held`?d9(`reply`,t.answer):u9(e);case`settled`:return e.kind===`unattended`?u9({kind:`closed`,lapsed:e.lapsed}):u9(e);case`close`:return e.kind===`unattended`||e.kind===`closed`?u9(e):e.kind===`streaming`?{next:{kind:`closed`,lapsed:!1},effects:[{kind:`unsubscribe`,unsubscribe:e.unsubscribe}]}:e.kind===`held`?{next:{kind:`closed`,lapsed:!1},effects:[{kind:`abort`}]}:u9({kind:`closed`,lapsed:l9(e)})}};function ile(e,t){let{next:n,effects:r}=rle(e,t);return{next:n,effects:[...[...s9(e)&&!s9(n)?[{kind:`clear-backstop`}]:[],...c9(e)&&!c9(n)?[{kind:`leave-in-flight`}]:[]],...r]}}function ale(e,t){t.allowHalfOpen=!1;let n=e.clock.monotonic();e.stats.inFlight++;let r=tle,i=e=>{let{next:t,effects:n}=ile(r,e);r=t,n.forEach(o)},a=new AbortController,o=t=>{switch(t.kind){case`answer`:return s(t.answer);case`exit`:return e.exit(t.code);case`exit-dropped`:return e.log(`warn`,`exit-after-flush dropped: the client was already told TIMEOUT`);case`count-timeout`:e.stats.requestsTimedOut++;return;case`clear-backstop`:return l();case`leave-in-flight`:e.stats.inFlight--;return;case`attach`:return i({kind:`subscribed`,unsubscribe:u(t.sessionId,t.lane)});case`start`:return d(t.start);case`abort`:return a.abort();case`unsubscribe`:return t.unsubscribe()}},s=({resp:n,exitAfterFlush:r,delivered:i})=>{let a=r===null?void 0:()=>e.exit(r),[o,s]=c(n,i);try{t.end(o,e=>{e??s(),a?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),a?.()}},c=(t,n)=>{try{return[Zr(t),n]}catch(t){return e.log(`error`,`response encode failed: ${O(t)}`),[Zr(PQ(t)),NQ]}},l=e.clock.after(200,()=>i({kind:`deadline`,answer:v8({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3})})),u=(n,r)=>{let i=o9(t);return e.subscribe(n,{lane:r,frame:e=>i(Qr(e.json)),refused:e=>t.end(Zr(e)),drawing:()=>!0})},d=t=>{t(a.signal).then(e=>i(y8(e)),t=>{e.log(`error`,`held request threw: ${O(t)}`),i({kind:`threw`,answer:v8(PQ(t))})})};ei(t,t=>{new Promise(a=>{let o=Kr(t);i({kind:`read`,waits:o.kind===`request`}),a(e.handle(o,()=>l9(r),n,()=>nle(r)))}).then(i).catch(t=>{e.log(`error`,`handler threw: ${O(t)}`),i({kind:`threw`,answer:v8(PQ(t))})}).finally(()=>i({kind:`settled`}))},t=>{e.log(`warn`,`frame parse failed: ${t.message}`),i({kind:`unreadable`,answer:v8({ok:!1,error:t.message,code:`BAD_REQUEST`,daemonV:3})})}),t.on(`error`,t=>{e.log(`warn`,`socket error: ${t.message}`),i({kind:`close`})}),t.on(`close`,()=>i({kind:`close`}))}const f9=`CC_CANDYBAR_PARENT_PID`;function ole(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 sle(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 cle(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:Vn(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function lle(e){let n=hr(e.home);g9={world:e,paths:n,log:new rc(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)});ule().catch(y9)}function y9(e){v9(`error`,`refusing to boot: ${O(e)}`),S9(1)}async function ule(){let{world:e,paths:n,log:r}=_9(),{host:i,home:a}=e,o=Ni(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 cn(t.pid,on(e.launcher).startTime);let s=await qs(Ys(e,p9,cr(i),n.socket!==er(Le)));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}),rr(n.socket);let c=yce({...ele(n,r,e.clock),bundle:cle(),host:i,home:a,memoryLimitBytes:o,registryUrl:i.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:wz(),exit:S9});h9=c,sle({clock:e.clock,anchor:ole(i.env),probe:on(e.launcher),onOrphaned:e=>{v9(`info`,`parent watchdog: ${e}; shutting down`),S9(0)}}),b9(c,ue.createServer(e=>ale(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}dle(e,n,r).catch(y9)}),n.listen(r,()=>fle(e,r))}async function dle(e,n,r){let i=await Fs(Is(ir(r)),(t,n)=>sn(t,n,on(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 fle(e,n){let r=zs(n);if(r.kind!==`present`){v9(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),S9(0);return}mle(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=${P(pe.getHeapStatistics().heap_size_limit)}MB memoryLimit=${P(e.memoryLimitBytes)}MB`),ta(_9().paths.spawnBackoff),e.arm(),ple(n,r.identity)}function ple(e,n){Hs({bound:n,myPid:t.pid,readIdentity:()=>zs(e),readLease:()=>Is(ir(e)),shutdown:e=>S9(e),log:v9,clock:_9().world.clock}).arm()}function mle(e){let n=Ls(ir(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:p9});n!==null&&v9(`warn`,`lease write failed: ${n}`)}const hle=e=>(t,n)=>oc(e,{socket:t},`tmux-status`,n);let x9=!1;function S9(e){x9||(x9=!0,_9().world.clock.after(500,()=>t.kill(t.pid,`SIGKILL`)),h9?.close(hle(_9().world.launcher)),Rs(_9().paths.lease,t.pid),m9!==null&&Js(m9,t.pid,Gs,e=>m.unlinkSync(e)),t.exit(e))}function gle(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=Jr(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 _le(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`record: ${ui(e)}\n`,code:1};let{path:n,lines:r,answers:i,frames:a,daemonClosed:o}=e.value,s=`the daemon closed before ${t}s ran out`;return i+a===0?{stdout:``,stderr:o?`record: ${n}: ${s}, and nothing had been drawn, so there is nothing to replay. No file was left.\n`:`record: ${n}: no request was answered and no lane drew a frame in ${t}s, so there is nothing to replay: the session was idle, or its bar is not drawn by this daemon. No file was left.\n`,code:1}:{stdout:`${n}: ${r} lines, ${i} answers, ${a} lane frames\n`,stderr:o?`record: ${s}: the file holds what came before.\n`:``,code:0}}async function vle(e,t,n){let r=gle(t,n);if(!r.ok)return{stdout:``,stderr:`record: ${r.problem}\n`,code:2};let{session:i,path:a,seconds:o}=r.args;return _le(await ri(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 yle={connectMs:200,budgetMs:500};async function ble(e,t,n){return xle(t,await Sle(e,t),n.includes(`--json`))}function xle(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
511
+ `);async function Gce(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=Z7(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,Wce,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function Q7(e,t,n){return Z7(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function $7(e,t){let n=await sc(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 Q7(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function Kce(e,t){let{panePid:n,cwd:r,foreground:i}=await $7(e,t),a=await Q7(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await Gce(e,i),s=d2(a).get(i)?.ppid;if(s===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);let c=rn(i,await tn(i,t=>e.launch(t)));if(c.startTime===null)throw Error(`the start of pane ${t.pane}'s foreground job ${i} could not be read (${c.why})`);return{pid:i,startTime:c.startTime,executable:await m.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:s,fromShell:i!==n,attached:Uce(a,i,n)}}function qce(e,t){let n=e9(e,t);return n.torn?e9(e,t).held:n.held}function e9(e,t){let n;try{n=m.readFileSync(e,`utf8`)}catch(t){return{torn:!1,held:t.code===`ENOENT`?{kind:`none`,why:`it keeps no session record at ${e} (update Claude Code with \`claude update\`: recent releases keep one)`}:{kind:`unread`,why:t.message}}}let r;try{r=JSON.parse(n)}catch(t){return{torn:!0,held:{kind:`unread`,why:`its session record ${e} is not JSON (${t.message})`}}}let{sessionId:i,procStart:a}=typeof r==`object`&&r?r:{},o=$t(a);return{torn:!1,held:typeof i!=`string`||i===``?{kind:`unread`,why:`its session record ${e} names no session`}:a===void 0?{kind:`unread`,why:`its session record ${e} names no process start (update Claude Code with \`claude update\`: recent releases name one)`}:o===void 0?{kind:`unread`,why:`its session record ${e} names its process start as ${JSON.stringify(a)}, not in the form \`ps -o lstart=\` prints it`}:o===t.startTime?{kind:`holds`,sessionId:i}:{kind:`none`,why:`its session record ${e} was left by a Claude Code that has exited: the record names a process started ${o}, and pid ${t.pid} is a process started ${t.startTime}`}}}const Jce=e=>t=>qce(s.join(qo(t.configDir,e),`sessions`,`${t.pid}.json`),t);function Yce(e,t,n,r,i,a,o,s){let c=e=>et(r,e,n);return{claudeInput:s,barPanes:async t=>Vce(await X7(e,t,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_start_command}`]),t.pane),openBarPane:async(t,n,r)=>(await X7(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 X7(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void Z7(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],envOverlay:Q0(n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>_c(o,e)===`present`,presence:e=>_c(o,e),paneClaude:t=>Kce(e,t),heldSession:a,paneDir:async(t,n)=>{let i=r.monotonic()+Y7;for(;;){let a=await $7(e,t);if(a.foreground===n){if(a.cwd===``)throw Error(`tmux read no directory for pane ${t.pane}`);return a.cwd}if(r.monotonic()>i)throw Error(`the shell in pane ${t.pane} (pid ${n}) did not take its terminal back within ${Y7/1e3} s`);await c(100)}},launcherNode:e=>Rce(e,e=>J7(e,m.constants.X_OK),Lce),onPath:(e,t)=>{let n=q7(e,t,e=>J7(e,m.constants.X_OK));return n===null?null:m.realpathSync(n)},followed:async(e,n,i)=>{let a=r.monotonic()+i;for(;!t(e).has(n);){if(r.monotonic()>a)return!1;await c(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`?zce(i.stdout):null;return a===null?(Z7(`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 c(100)}return!0},typeShellLine:async(t,n)=>void await X7(e,t,p$(t.pane,`cc-candybar-lane`,[]),n)}}const Xce=/^[0-9a-f]{64}$/;function t9(e,t){return oe(`sha256`,e).update(JSON.stringify(t)).digest()}const n9=e=>[e.sessionId,e.action,e.declaration,e.evaluated],r9=e=>[oC,e];function Zce(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);let t=t=>t9(e,t).toString(`hex`),n=(t,n)=>Xce.test(n)&&le(Buffer.from(n,`hex`),t9(e,t));return{sign:e=>t(n9(e)),verify:(e,t)=>n(n9(e),t),signBinding:e=>t(r9(e)),verifyBinding:(e,t)=>n(r9(e),t)}}function i9(e){return s.join(e,`link.key`)}function a9(e){let t,n=()=>t??=Qce(e);return{sign:e=>n().sign(e),verify:(e,t)=>n().verify(e,t),signBinding:e=>n().signBinding(e),verifyBinding:(e,t)=>n().verifyBinding(e,t)}}function Qce(e){let t;try{t=m.readFileSync(e)}catch(n){if(n.code!==`ENOENT`)throw n;$ce(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 Zce(t)}function $ce(e){m.mkdirSync(s.dirname(e),{recursive:!0});let t=ct(e);m.writeFileSync(t,se(32),{mode:384,flag:`wx`});try{m.linkSync(t,e)}catch(e){if(e.code!==`EEXIST`)throw e}finally{m.unlinkSync(t)}}function ele(e,t,n){return{daemonLog:t,launcher:e=>_n(e,n),storage:(t,r)=>Ice(e,t,n,r),doctorStores:t=>k4(t,e.state),doctorEdge:V4,claudeInput:h$,probe:on,laneEdge:(e,t,r,i,a,o,s)=>Yce(e,t,r,n,i,a,o,s),heldSession:Jce,linkSigner:a9(i9(e.state)),limits:({startedAtMs:r,exit:i,launcher:a,log:o})=>qi(r,i,{launcher:a,log:o,clock:n,snapshotDir:e.state,writeLogNow:()=>t.writeNow()}),fetch,pricing:e=>Wae({...e,clock:n}),filesystem:mn}}function o9(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}const tle={kind:`awaiting`},s9=e=>e.kind===`awaiting`||e.kind===`answering`||e.kind===`unattended`&&!e.lapsed,c9=e=>e.kind!==`streaming`&&e.kind!==`closed`,l9=e=>e.kind===`answered`&&e.by===`backstop`||(e.kind===`unattended`||e.kind===`closed`)&&e.lapsed,nle=e=>e.kind===`closed`,u9=e=>({next:e,effects:[]}),d9=(e,t)=>({next:{kind:`answered`,by:e},effects:[{kind:`answer`,answer:t}]}),rle=(e,t)=>{switch(t.kind){case`read`:return e.kind===`awaiting`?u9(t.waits?{kind:`answering`}:{kind:`unattended`,lapsed:!1}):e.kind===`answered`&&e.by===`backstop`&&!t.waits?u9({kind:`unattended`,lapsed:!0}):u9(e);case`unreadable`:return e.kind===`awaiting`?d9(`reply`,t.answer):u9(e);case`deadline`:if(e.kind===`awaiting`||e.kind===`answering`){let e=d9(`backstop`,t.answer);return{...e,effects:[{kind:`count-timeout`},...e.effects]}}return e.kind===`unattended`&&!e.lapsed?{next:{kind:`unattended`,lapsed:!0},effects:[{kind:`count-timeout`}]}:u9(e);case`reply`:return e.kind===`answering`||e.kind===`held`?d9(`reply`,t):e.kind===`answered`&&e.by===`backstop`||e.kind===`closed`&&e.lapsed?{next:e,effects:t.exitAfterFlush===null?[]:[{kind:`exit-dropped`}]}:e.kind===`closed`?{next:e,effects:t.exitAfterFlush===null?[]:[{kind:`exit`,code:t.exitAfterFlush}]}:u9(e);case`subscribe`:return e.kind===`answering`?{next:e,effects:[{kind:`attach`,sessionId:t.sessionId,lane:t.lane}]}:u9(e);case`subscribed`:return e.kind===`answering`?u9({kind:`streaming`,unsubscribe:t.unsubscribe}):{next:e,effects:[{kind:`unsubscribe`,unsubscribe:t.unsubscribe}]};case`held`:return e.kind===`answering`?{next:{kind:`held`},effects:[{kind:`start`,start:t.start}]}:u9(e);case`threw`:return e.kind===`answering`||e.kind===`held`?d9(`reply`,t.answer):u9(e);case`settled`:return e.kind===`unattended`?u9({kind:`closed`,lapsed:e.lapsed}):u9(e);case`close`:return e.kind===`unattended`||e.kind===`closed`?u9(e):e.kind===`streaming`?{next:{kind:`closed`,lapsed:!1},effects:[{kind:`unsubscribe`,unsubscribe:e.unsubscribe}]}:e.kind===`held`?{next:{kind:`closed`,lapsed:!1},effects:[{kind:`abort`}]}:u9({kind:`closed`,lapsed:l9(e)})}};function ile(e,t){let{next:n,effects:r}=rle(e,t);return{next:n,effects:[...[...s9(e)&&!s9(n)?[{kind:`clear-backstop`}]:[],...c9(e)&&!c9(n)?[{kind:`leave-in-flight`}]:[]],...r]}}function ale(e,t){t.allowHalfOpen=!1;let n=e.clock.monotonic();e.stats.inFlight++;let r=tle,i=e=>{let{next:t,effects:n}=ile(r,e);r=t,n.forEach(o)},a=new AbortController,o=t=>{switch(t.kind){case`answer`:return s(t.answer);case`exit`:return e.exit(t.code);case`exit-dropped`:return e.log(`warn`,`exit-after-flush dropped: the client was already told TIMEOUT`);case`count-timeout`:e.stats.requestsTimedOut++;return;case`clear-backstop`:return l();case`leave-in-flight`:e.stats.inFlight--;return;case`attach`:return i({kind:`subscribed`,unsubscribe:u(t.sessionId,t.lane)});case`start`:return d(t.start);case`abort`:return a.abort();case`unsubscribe`:return t.unsubscribe()}},s=({resp:n,exitAfterFlush:r,delivered:i})=>{let a=r===null?void 0:()=>e.exit(r),[o,s]=c(n,i);try{t.end(o,e=>{e??s(),a?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),a?.()}},c=(t,n)=>{try{return[Zr(t),n]}catch(t){return e.log(`error`,`response encode failed: ${O(t)}`),[Zr(PQ(t)),NQ]}},l=e.clock.after(200,()=>i({kind:`deadline`,answer:v8({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3})})),u=(n,r)=>{let i=o9(t);return e.subscribe(n,{lane:r,frame:e=>i(Qr(e.json)),refused:e=>t.end(Zr(e)),drawing:()=>!0})},d=t=>{t(a.signal).then(e=>i(y8(e)),t=>{e.log(`error`,`held request threw: ${O(t)}`),i({kind:`threw`,answer:v8(PQ(t))})})};ei(t,t=>{new Promise(a=>{let o=Kr(t);i({kind:`read`,waits:o.kind===`request`}),a(e.handle(o,()=>l9(r),n,()=>nle(r)))}).then(i).catch(t=>{e.log(`error`,`handler threw: ${O(t)}`),i({kind:`threw`,answer:v8(PQ(t))})}).finally(()=>i({kind:`settled`}))},t=>{e.log(`warn`,`frame parse failed: ${t.message}`),i({kind:`unreadable`,answer:v8({ok:!1,error:t.message,code:`BAD_REQUEST`,daemonV:3})})}),t.on(`error`,t=>{e.log(`warn`,`socket error: ${t.message}`),i({kind:`close`})}),t.on(`close`,()=>i({kind:`close`}))}const f9=`CC_CANDYBAR_PARENT_PID`;function ole(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 sle(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 cle(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:Vn(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function lle(e){let n=hr(e.home);g9={world:e,paths:n,log:new rc(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)});ule().catch(y9)}function y9(e){v9(`error`,`refusing to boot: ${O(e)}`),S9(1)}async function ule(){let{world:e,paths:n,log:r}=_9(),{host:i,home:a}=e,o=Ni(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 cn(t.pid,on(e.launcher).startTime);let s=await qs(Ys(e,p9,cr(i),n.socket!==er(Le)));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}),rr(n.socket);let c=yce({...ele(n,r,e.clock),bundle:cle(),host:i,home:a,memoryLimitBytes:o,registryUrl:i.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:e.clock,gates:wz(),exit:S9});h9=c,sle({clock:e.clock,anchor:ole(i.env),probe:on(e.launcher),onOrphaned:e=>{v9(`info`,`parent watchdog: ${e}; shutting down`),S9(0)}}),b9(c,ue.createServer(e=>ale(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}dle(e,n,r).catch(y9)}),n.listen(r,()=>fle(e,r))}async function dle(e,n,r){let i=await Fs(Is(ir(r)),(t,n)=>sn(t,n,on(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 fle(e,n){let r=zs(n);if(r.kind!==`present`){v9(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),S9(0);return}mle(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=${P(pe.getHeapStatistics().heap_size_limit)}MB memoryLimit=${P(e.memoryLimitBytes)}MB`),ta(_9().paths.spawnBackoff),e.arm(),ple(n,r.identity)}function ple(e,n){Hs({bound:n,myPid:t.pid,readIdentity:()=>zs(e),readLease:()=>Is(ir(e)),shutdown:e=>S9(e),log:v9,clock:_9().world.clock}).arm()}function mle(e){let n=Ls(ir(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:p9});n!==null&&v9(`warn`,`lease write failed: ${n}`)}const hle=e=>(t,n)=>oc(e,{socket:t},`tmux-status`,n);let x9=!1;function S9(e){x9||(x9=!0,_9().world.clock.after(500,()=>t.kill(t.pid,`SIGKILL`)),h9?.close(hle(_9().world.launcher)),Rs(_9().paths.lease,t.pid),m9!==null&&Js(m9,t.pid,Gs,e=>m.unlinkSync(e)),t.exit(e))}function gle(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=Jr(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 _le(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`record: ${ui(e)}\n`,code:1};let{path:n,lines:r,answers:i,frames:a,daemonClosed:o}=e.value,s=`the daemon closed before ${t}s ran out`;return i+a===0?{stdout:``,stderr:o?`record: ${n}: ${s}, and nothing had been drawn, so there is nothing to replay. No file was left.\n`:`record: ${n}: no request was answered and no lane drew a frame in ${t}s, so there is nothing to replay: the session was idle, or its bar is not drawn by this daemon. No file was left.\n`,code:1}:{stdout:`${n}: ${r} lines, ${i} answers, ${a} lane frames\n`,stderr:o?`record: ${s}: the file holds what came before.\n`:``,code:0}}async function vle(e,t,n){let r=gle(t,n);if(!r.ok)return{stdout:``,stderr:`record: ${r.problem}\n`,code:2};let{session:i,path:a,seconds:o}=r.args;return _le(await ri(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 yle={connectMs:200,budgetMs:500};async function ble(e,t,n){return xle(t,await Sle(e,t),n.includes(`--json`))}function xle(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
512
512
  `:Cle(t.value),stderr:``,code:0}:{stdout:``,stderr:`${e}: ${ui(t)}\n`,code:1}}function Sle(e,t){return ri(e,()=>({kind:`debug`,what:t}),yle,e=>`debug`in e?e.debug:void 0)}function Cle(e){switch(e.what){case`vars`:return wle(e.vars);case`segments`:return Tle(e.segments);case`config`:return Ele(e.config);default:return e}}function wle(e){if(e.length===0)return`no variables (DSL not active)
513
513
  `;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${Ole(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${Dle(a.value)}${e}${o}`)}return t.join(`
514
514
  `)+`
@@ -517,7 +517,7 @@ function run(argv) {
517
517
  `)+`
518
518
  `}function Ele(e){return e===null?`config: DSL not active
519
519
  `:JSON.stringify(e,null,2)+`
520
- `}function Dle(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function Ole(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function kle(){let e=jle();return e===null?null:m.readFileSync(e,`utf-8`)}function Ale(){let e;try{e=kle()}catch(e){return{stdout:``,stderr:`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`,code:2}}return e===null?{stdout:``,stderr:"schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n",code:2}:{stdout:e,stderr:``,code:0}}function jle(){let e=s.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let r=s.dirname(s.resolve(n));for(;;){let t=s.join(r,e);if(m.existsSync(t))return t;let n=s.dirname(r);if(n===r)return null;r=n}}const C9=5e3;function Mle(e,t){return{ms:t,signal:tt(e,t)}}function Nle(e,t){return t.length===0?[]:[`source${t.length===1?``:`s`} still running after ${e.ms} ms, drawn as pending: ${t.join(`, `)}`]}function w9({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=QK(a,o);return{drawn:FZ(n,r,i,Lle(t,a,e.at(-1)??null,s),c,a),opts:c}}const T9=`/home/tester`,E9=vQ(`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`),Ple={tmux:{socket:`/tmp/tmux.sock`,pane:`%0`,truecolor:null},ssh:!0};function Fle(e){let t=Math.floor(e);return{hook_event_name:`Status`,session_id:E9,version:`1.15.0`,cwd:`${T9}/code/cc-candybar/src`,transcript_path:`${T9}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:{current_dir:`${T9}/code/cc-candybar/src`,project_dir:`${T9}/code/cc-candybar`,added_dirs:[]},rate_limits:{five_hour:{used_percentage:63,resets_at:t+2*3600},seven_day:{used_percentage:21,resets_at:t+5*86400}}}}function Ile(e,t){let n=Math.floor(t),r=Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]),i={git:F({branch:`main`,status:`dirty`,aheadBehind:F({ahead:2,behind:1}),head:F(`abc1234def5678`),workingTree:{staged:3,unstaged:2,untracked:1,conflicts:0},sha:F(`abc1234`),operation:F(`rebase`),committedAt:F(n-780),stashCount:F(1),upstream:F(`origin/main`),repoName:F(`cc-candybar`),repoUrl:F(`https://github.com/promptctl/cc-candybar`)}),pr:I,session:F({session:{cost:.39,calculatedCost:.39,officialCost:null,tokens:241400,tokenBreakdown:null}}),context:F({totalTokens:48487,percentage:76,contextLeftPercentage:24,maxTokens:1e6}),metrics:F({lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,nonPrompts:0,linesAdded:512,linesRemoved:88}),activity:I,tmux:F({session:`work`}),hostName:F(`tester-box`),hostUser:F(`tester`),cache:F(n+900),speed:I,autocompact:F(4e5),today:F({sums:KK(t,12.5,34e5),own:{}})},a=Bq(zU(e));return{builtins:Object.fromEntries([...a].map(e=>[e,i[e]])),sources:new Map(r.map(e=>[e,I])),runs:new Map,faults:[]}}function Lle(e,t,n,r){let i=Fle(r),a=W5(void 0,E9,Ile(e,r),{...I,at:r},r),{term:o,...s}=Vq(a,{hookData:i,hints:Ple,home:T9},{effective:t,configFacts:{unsaved:1,resettable:Ox(()=>!0),themeDefault:t.theme.kind===`decided`?{differs:!0,theme:t.theme.name}:{differs:!1},configPath:n??`${T9}/.config/cc-candybar/config.json5`},history:{undo:1,redo:1,sinceEdit:1},back:1});return{...s,...zq(a,r)}}function Rle(e,t){let n=WH(e);return n!==null&&t.push(n),e.kind===`chain`?e.layers:[]}async function zle(e,n,r,i=t.cwd(),a=C9){let o=[],s=EP(i,r,e.host.home)??null,c=_r(e.host,e.home),l=zH(e.filesystem,c,ZH(e.filesystem,qn(e.home)),i,i,s??void 0);o.push(...BP(l.repos));let u=s===null?Rle(l,o):[RH(s)];if(s!==null){let t;try{t=e.filesystem.statSync(s)}catch(e){if(e.code!==`ENOENT`)return{kind:`unreadable`,path:s,message:e instanceof Error?e.message:String(e)}}if(t!==void 0&&t.kind!==`file`)return{kind:`unreadable`,path:s,message:`not a file`}}let d=KH(e.filesystem,c,i,i);d!==null&&o.push(d);try{return{kind:`clean`,layers:u,warnings:o,rendered:await Hle(e,n,u,{repo:l.repos.plugins},i,o,a)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&u.some(e=>e.path===t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof Ab&&o.push(...e.warnings),{kind:`fatal`,layers:u,message:e instanceof Ab||e instanceof Error?e.message:String(e),warnings:o})}}async function Ble(e,t,n,r,i,a,o=C9,s=wz()){let c=t.map(e=>e.path),l=pK(e.filesystem,new dK,_r(e.host,e.home),t,zK,{warned:e=>i.push(...e)},{...n,cwd:r});bK(l.dropped);let{config:u}=l,d=new Mw(e.clock),f=new sM({launcher:e.launcher,clock:e.clock}),p=new bM(f,d,u.globals.default_empty_value??``,w$(new d0(c0),()=>s.state.gateFor(u)));try{let t=yZ(u,p,{cwd:r,links:{to:e.home.name,signer:a9(i9(qn(e.home)))}});i.push(...t.loadWarnings);let n=cJ(u,()=>null,()=>!1),s=Mle(e.clock,o);return w9({layers:c,config:u,compiled:t,store:d,registry:p},n,200,a),await p.inFlight(s.signal),{settle:s,layers:c,droppedPlugins:[...l.installed.dropped,...l.layers.flatMap(e=>e.plugins.dropped)],config:u,compiled:t,store:d,registry:p,runs:f}}catch(e){throw p.dispose(),f.close(),e}}async function Vle(e,t,n,r){let i=new Map,a=new Set,o=e=>{switch(e.kind){case`rule`:i.set(`${e.slot} rule`,e.message);return;case`when`:i.set(e.where,e.error);return;case`refresh`:i.set(`variable "${e.variable}"`,`cannot refresh: ${e.error}`);return;default:}},{config:s,compiled:c,store:l,registry:u,settle:d}=e,{drawn:f,opts:p}=w9(e,t,n,r);for(let e of Nle(d,await u.inFlight(d.signal)))a.add(e);let{frame:m}=IZ(s,c,l,u,f,r,p,{onSegmentError:(e,t)=>i.set(`segment "${e}"`,t),onRenderWarning:o},t);return{rendered:m,failures:i,advisories:a}}async function Hle(e,t,n,r,i,a,o){let s=it(new Date(e.clock.now())),c=await Ble(e,n,r,i,a,s,o,t),{config:l}=c;try{t.state.gateFor(l),t.config.gateFor(l);let e=iS(null,l.globals.preset,l.presets),n=async(e,t)=>{let n=cJ(l,t=>t===`preset`?e:null,()=>t),r;try{r=await Vle(c,n,200,s)}catch(e){r={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...r}},r=await n(e,!1),i=[r,await n(e,!0)];for(let t of rS(l.presets))t!==e&&i.push(await n(t,!1),await n(t,!0));let o=t=>{let n=new Map;for(let e of i)for(let r of t(e)){let t=n.get(r)??new Map;t.set(e.preset,(t.get(e.preset)??new Set).add(e.customized)),n.set(r,t)}return[...n].map(([t,n])=>n.get(e)?.has(!1)?t:`${t} (under ${[...n].map(([t,n])=>[...t===e?[]:[`preset "${t}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};a.push(...o(e=>e.advisories));let u=o(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=r.rendered,f=c.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
520
+ `}function Dle(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function Ole(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function kle(){let e=jle();return e===null?null:m.readFileSync(e,`utf-8`)}function Ale(){let e;try{e=kle()}catch(e){return{stdout:``,stderr:`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`,code:2}}return e===null?{stdout:``,stderr:"schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n",code:2}:{stdout:e,stderr:``,code:0}}function jle(){let e=s.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let r=s.dirname(s.resolve(n));for(;;){let t=s.join(r,e);if(m.existsSync(t))return t;let n=s.dirname(r);if(n===r)return null;r=n}}const C9=5e3;function Mle(e,t){return{ms:t,signal:tt(e,t)}}function Nle(e,t){return t.length===0?[]:[`source${t.length===1?``:`s`} still running after ${e.ms} ms, drawn as pending: ${t.join(`, `)}`]}function w9({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=QK(a,o);return{drawn:FZ(n,r,i,Lle(t,a,e.at(-1)??null,s),c,a),opts:c}}const T9=`/home/tester`,E9=vQ(`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`),Ple={tmux:{socket:`/tmp/tmux.sock`,pane:`%0`,truecolor:null},ssh:!0};function Fle(e){let t=Math.floor(e);return{hook_event_name:`Status`,session_id:E9,version:`1.15.0`,cwd:`${T9}/code/cc-candybar/src`,transcript_path:`${T9}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:{current_dir:`${T9}/code/cc-candybar/src`,project_dir:`${T9}/code/cc-candybar`,added_dirs:[]},rate_limits:{five_hour:{used_percentage:63,resets_at:t+2*3600},seven_day:{used_percentage:21,resets_at:t+5*86400}}}}function Ile(e,t){let n=Math.floor(t),r=Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]),i={git:F({branch:`main`,status:`dirty`,aheadBehind:F({ahead:2,behind:1}),head:F(`abc1234def5678`),workingTree:{staged:3,unstaged:2,untracked:1,conflicts:0},sha:F(`abc1234`),operation:F(`rebase`),committedAt:F(n-780),stashCount:F(1),upstream:F(`origin/main`),repoName:F(`cc-candybar`),repoUrl:F(`https://github.com/promptctl/cc-candybar`)}),pr:I,session:F({session:{cost:.39,calculatedCost:.39,officialCost:null,tokens:241400,tokenBreakdown:null}}),context:F({totalTokens:48487,percentage:76,contextLeftPercentage:24,maxTokens:1e6}),metrics:F({lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,nonPrompts:0,linesAdded:512,linesRemoved:88}),activity:I,tmux:F({session:`work`}),hostName:F(`tester-box`),hostUser:F(`tester`),cache:F(n+900),speed:I,autocompact:F(4e5),today:F({sums:KK(t,12.5,34e5),own:{}})},a=Bq(zU(e));return{builtins:Object.fromEntries([...a].map(e=>[e,i[e]])),sources:new Map(r.map(e=>[e,I])),runs:new Map,faults:[]}}function Lle(e,t,n,r){let i=Fle(r),a=W5(void 0,E9,Ile(e,r),{...I,at:r},r),{term:o,...s}=Vq(a,{hookData:i,hints:Ple,home:T9},{effective:t,configFacts:{unsaved:1,resettable:Dx(()=>!0),themeDefault:t.theme.kind===`decided`?{differs:!0,theme:t.theme.name}:{differs:!1},configPath:n??`${T9}/.config/cc-candybar/config.json5`},history:{undo:1,redo:1,sinceEdit:1},back:1});return{...s,...zq(a,r)}}function Rle(e,t){let n=WH(e);return n!==null&&t.push(n),e.kind===`chain`?e.layers:[]}async function zle(e,n,r,i=t.cwd(),a=C9){let o=[],s=EP(i,r,e.host.home)??null,c=_r(e.host,e.home),l=zH(e.filesystem,c,ZH(e.filesystem,qn(e.home)),i,i,s??void 0);o.push(...BP(l.repos));let u=s===null?Rle(l,o):[RH(s)];if(s!==null){let t;try{t=e.filesystem.statSync(s)}catch(e){if(e.code!==`ENOENT`)return{kind:`unreadable`,path:s,message:e instanceof Error?e.message:String(e)}}if(t!==void 0&&t.kind!==`file`)return{kind:`unreadable`,path:s,message:`not a file`}}let d=KH(e.filesystem,c,i,i);d!==null&&o.push(d);try{return{kind:`clean`,layers:u,warnings:o,rendered:await Hle(e,n,u,{repo:l.repos.plugins},i,o,a)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&u.some(e=>e.path===t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof kb&&o.push(...e.warnings),{kind:`fatal`,layers:u,message:e instanceof kb||e instanceof Error?e.message:String(e),warnings:o})}}async function Ble(e,t,n,r,i,a,o=C9,s=wz()){let c=t.map(e=>e.path),l=pK(e.filesystem,new dK,_r(e.host,e.home),t,zK,{warned:e=>i.push(...e)},{...n,cwd:r});bK(l.dropped);let{config:u}=l,d=new jw(e.clock),f=new sM({launcher:e.launcher,clock:e.clock}),p=new bM(f,d,u.globals.default_empty_value??``,w$(new d0(c0),()=>s.state.gateFor(u)));try{let t=yZ(u,p,{cwd:r,links:{to:e.home.name,signer:a9(i9(qn(e.home)))}});i.push(...t.loadWarnings);let n=cJ(u,()=>null,()=>!1),s=Mle(e.clock,o);return w9({layers:c,config:u,compiled:t,store:d,registry:p},n,200,a),await p.inFlight(s.signal),{settle:s,layers:c,droppedPlugins:[...l.installed.dropped,...l.layers.flatMap(e=>e.plugins.dropped)],config:u,compiled:t,store:d,registry:p,runs:f}}catch(e){throw p.dispose(),f.close(),e}}async function Vle(e,t,n,r){let i=new Map,a=new Set,o=e=>{switch(e.kind){case`rule`:i.set(`${e.slot} rule`,e.message);return;case`when`:i.set(e.where,e.error);return;case`refresh`:i.set(`variable "${e.variable}"`,`cannot refresh: ${e.error}`);return;default:}},{config:s,compiled:c,store:l,registry:u,settle:d}=e,{drawn:f,opts:p}=w9(e,t,n,r);for(let e of Nle(d,await u.inFlight(d.signal)))a.add(e);let{frame:m}=IZ(s,c,l,u,f,r,p,{onSegmentError:(e,t)=>i.set(`segment "${e}"`,t),onRenderWarning:o},t);return{rendered:m,failures:i,advisories:a}}async function Hle(e,t,n,r,i,a,o){let s=it(new Date(e.clock.now())),c=await Ble(e,n,r,i,a,s,o,t),{config:l}=c;try{t.state.gateFor(l),t.config.gateFor(l);let e=rS(null,l.globals.preset,l.presets),n=async(e,t)=>{let n=cJ(l,t=>t===`preset`?e:null,()=>t),r;try{r=await Vle(c,n,200,s)}catch(e){r={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...r}},r=await n(e,!1),i=[r,await n(e,!0)];for(let t of nS(l.presets))t!==e&&i.push(await n(t,!1),await n(t,!0));let o=t=>{let n=new Map;for(let e of i)for(let r of t(e)){let t=n.get(r)??new Map;t.set(e.preset,(t.get(e.preset)??new Set).add(e.customized)),n.set(r,t)}return[...n].map(([t,n])=>n.get(e)?.has(!1)?t:`${t} (under ${[...n].map(([t,n])=>[...t===e?[]:[`preset "${t}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};a.push(...o(e=>e.advisories));let u=o(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=r.rendered,f=c.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
521
521
  `)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
522
522
  `));return d}finally{c.registry.dispose(),c.runs.close()}}function D9(e){return e.map(e=>`warning: ${e}\n`).join(``)}function Ule(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${jP(e.layers.map(e=>e.path))}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${cF(e.rendered)}\n`:``),stderr:D9(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:D9(e.warnings)+`✗ ${jP(e.layers.map(e=>e.path),`<default>`)}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const O9=`--render`,k9=`Usage: cc-candybar check [${O9}] [config-file]\n`;function Wle(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==O9);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${k9}`}:n.length>1?{kind:`usage`,message:`check: expected at most one path\n${k9}`}:{kind:`run`,target:n[0],render:t.includes(O9)}}async function A9(e,n){let r=Wle(e),i=t.cwd();return r.kind===`usage`?{stdout:``,stderr:r.message,code:2}:Ule(await zle(n,wz(),AP(r.target,n.host,i).path,i),r.render)}const Gle=/^[a-z][a-z0-9+.-]*:\/\//i,Kle=/^[^@\s/]+@[^:\s/]+:/,qle=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function Jle(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function Yle(e,t,n,r){let i=TP(t,e,n);if(r(i))return{kind:`path`,dir:i};if(Gle.test(e)||Kle.test(e))return{kind:`git`,url:e,shown:Jle(e)};let a=qle.exec(e);if(a){let e=`https://github.com/${a[1]}.git`;return{kind:`git`,url:e,shown:e}}return{error:`"${e}" is not a directory, a GitHub repo slug (owner/repo) or a git URL`}}function Xle(e,t){let n=s.join(e,AH),r=MH(mn,n);if(`error`in r)throw Error(`${t}: could not list ${AH}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${AH}/<name>/${KV}`);return r.folders.map(e=>s.join(n,e,KV))}function Zle(e,t,n,r){let i=(r,...i)=>{let a=e.launchSync({bin:`git`,args:i,envOverlay:r,category:`plugin.git`});if(!a.ok)throw Error(`git ${i.map(e=>e===t?n:e).join(` `)} failed (${gt(a)})`);return a.stdout},a={GIT_TERMINAL_PROMPT:`0`};for(let e of i(a,`rev-parse`,`--local-env-vars`).split(`
523
523
  `))a[e]=void 0;i(a,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,t,r),i(a,`-C`,r,`sparse-checkout`,`set`,`--no-cone`,`/${AH}/`)}function Qle({host:e,launcher:t},n,r){switch(n.kind){case`path`:return r(n.dir);case`git`:{let i=m.mkdtempSync(s.join(e.tmp,`cc-candybar-plugin-`));try{return Zle(t,n.url,n.shown,s.join(i,`repo`)),r(s.join(i,`repo`))}finally{m.rmSync(i,{recursive:!0,force:!0})}}}}function $le(e){let t;try{t=m.lstatSync(e)}catch(e){if(e.code===`ENOENT`)return`installed`;throw e}if(t.isDirectory())return`updated`;if(t.isSymbolicLink())return`replaced`;throw Error(`${e} is a file, not a plugin folder: move it, then install again`)}function eue(e,t,n,r){switch(r){case`updated`:m.renameSync(s.join(e,KV),s.join(t,KV));return;case`replaced`:m.renameSync(t,n),m.renameSync(e,t);return;case`installed`:m.renameSync(e,t);return}}function tue(e,t,n,r){let i=Xle(e,n);m.mkdirSync(t,{recursive:!0});let a=m.mkdtempSync(s.join(t,`.install-`));try{let o=i.map(e=>{let t=s.join(a,s.basename(s.dirname(e)));m.mkdirSync(t);try{m.copyFileSync(e,s.join(t,KV))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),c=fK(mn,o.map(e=>JV(s.join(e,KV),`plugins`)),zK,{root:e,git:!1},r);if(c.length>0)throw Error(c.map(e=>`${n}: ${s.join(AH,s.relative(a,e.path))} would not load: ${e.reason.split(a).join(s.join(n,AH))}`).join(`