@promptctl/cc-candybar 1.180.0 → 1.180.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +39 -39
- package/package.json +10 -8
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i}from"node:url";import{json as a}from"node:stream/consumers";import o,{basename as s,dirname as c,isAbsolute as l,join as u,sep as d}from"node:path";import f,{closeSync as p,constants as m,existsSync as h,fstatSync as g,linkSync as _,mkdtempSync as v,openSync as y,readFileSync as b,readSync as x,rmSync as S,statSync as C,writeFileSync as ee}from"node:fs";import te,{createHash as w,createHmac as ne,randomBytes as T,randomUUID as re,timingSafeEqual as E}from"node:crypto";import D,{homedir as ie,tmpdir as O}from"node:os";import ae from"node:net";import{spawn as oe,spawnSync as se}from"node:child_process";import{StringDecoder as ce}from"node:string_decoder";import{inspect as le,parseArgs as ue,types as de}from"node:util";import{clearInterval as fe,setImmediate as pe,setInterval as me}from"node:timers";import he from"node:v8";import{open as ge,readFile as _e,readdir as ve,stat as ye}from"node:fs/promises";import{get as be}from"node:https";import{setTimeout as xe}from"node:timers/promises";import{WriteStream as Se}from"node:tty";import{createInterface as Ce}from"node:readline";var we=Object.create,Te=Object.defineProperty,Ee=Object.getOwnPropertyDescriptor,De=Object.getOwnPropertyNames,Oe=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty,Ae=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),je=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=De(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ke.call(e,s)&&s!==n&&Te(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ee(t,s))||r.enumerable});return e},Me=(e,t,n)=>(n=e==null?{}:we(Oe(e)),je(t||!e||!e.__esModule?Te(n,`default`,{value:e,enumerable:!0}):n,e));const Ne=()=>!!process.env.CC_CANDYBAR_DEBUG;function Pe(e){return Ne()?`[DEBUG] ${e()}\n`:``}function k(e,...t){Ne()&&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)=>k(t),Le=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Re(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function ze(e){return Le.test(e)?e:Re(e)}function Be(e){return`${e.dir===void 0?``:`cd ${ze(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${ze(t)} `).join(``)}${[e.program,...e.args].map(ze).join(` `)}`}const Ve=`cc-extra`;function He(e){return o.join(o.dirname(e),Ve,`src`,`bun-attach.js`)}function Ue(e){return o.join(o.dirname(e),`bun-graph.js`)}const We=`attach-preload.cjs`;function Ge(e){return o.join(o.dirname(e),We)}function Ke(e,t){return Be({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const qe=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Je(e,t){return t.isSymbolicLink()?Buffer.from(f.readlinkSync(e)):f.readFileSync(e)}function Ye(e,t,n=qe){return f.readdirSync(t).filter(n).sort().flatMap(n=>{let r=o.join(t,n),i=f.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?Ye(e,r):[[o.relative(e,r).split(o.sep).join(`/`),Je(r,i)]]})}function Xe(e){let t=te.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Ze(e){return Xe(Ye(e,e))}const Qe=[`Cargo.toml`,`Cargo.lock`,`src`];function $e(e){return Xe(Ye(e,e,e=>Qe.includes(e)))}const et=e=>e.slice(0,7),tt=`1.180.
|
|
3
|
-
`)}function Ht(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=jt.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 Ut(e){return typeof e==`string`&&o.isAbsolute(e)?e:void 0}function Wt(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 A=1e4;function Gt(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>A?A:t}function Kt(e){return typeof e==`boolean`?e:void 0}function qt(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var Jt=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Yt(e){return Xt(JSON.stringify(e))}function Xt(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function j(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 Jt(`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 Jt(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function Zt(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.off(`data`,c),e.off(`error`,l),e.off(`close`,u);try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n-Date.now()),c=j(e=>o(()=>r(e)),e=>o(()=>i(e))),l=e=>o(()=>i(e)),u=()=>o(()=>i(Error(`socket closed before response`)));e.on(`data`,c),e.on(`error`,l),e.on(`close`,u),e.write(Yt(t))})}function Qt(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Ut(n);return Nt.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function $t(e,t,n){let r=null;try{r=await an(_t(),t.connectMs);let i=Date.now()+t.budgetMs,a=e(i),o=await Zt(r,{v:3,...a},i);return nn(a.kind,o,n)}catch(e){return rn(e)}finally{r&&r.destroy()}}function en(e,t){return typeof e==`string`?e:t}function tn(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function nn(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=en(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:tn(r.daemonV)};case`TIMEOUT`:return{kind:`busy`,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 rn(e){if(e instanceof Jt||e instanceof SyntaxError)return{kind:`permanent`,cause:`malformed_response`,message:e instanceof Error?e.message:String(e)};let t=e instanceof Error?e.message:String(e);return t===`CONNECT_TIMEOUT`||t===`TIMEOUT`?{kind:`transient`,cause:`timeout`,message:t}:t.includes(`ECONNREFUSED`)||t.includes(`ENOENT`)||t.includes(`ENOTSOCK`)?{kind:`transient`,cause:`unreachable`,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function an(e,t){return new Promise((n,r)=>{let i=ae.createConnection({path:e}),a=setTimeout(()=>{i.destroy(),r(Error(`CONNECT_TIMEOUT`))},t);i.once(`connect`,()=>{clearTimeout(a),n(i)}),i.once(`error`,e=>{clearTimeout(a),r(e)})})}function on(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 sn(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 cn(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 ln={connectMs:50,budgetMs:150},un={connectMs:50,budgetMs:350};function dn(e){let t=e.output;return typeof t==`string`?t:void 0}function fn(e){return nn(`render`,e,dn)}function pn(e,t,n,r,i=ln){return $t(i=>({kind:`render`,hookData:e,args:t,cwd:n,deadline:i,...r}),i,dn)}function mn(e,t){return $t(()=>({kind:`pane-session`,socket:e,pane:t}),un,e=>`paneSession`in e?e.paneSession:void 0)}function hn(e,t){return $t(()=>({kind:`click`,verb:e,value:t,clientVersion:tt}),un,dn)}function gn(e,t){return de.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!h(t)?`working directory does not exist: ${t}`:e.message:String(e)}const _n={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function vn(e,t){let n=_n[t];if(n===void 0)return{allowed:!0};let r=e.get(t);if(r===void 0)return{allowed:!0};let i=Date.now()-r;return i>=n?{allowed:!0}:{allowed:!1,minIntervalMs:n,sinceLastMs:i}}function yn(e){return e.env??process.env}const bn=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function xn(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${n}ms ago`}}function Sn(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function Cn(e,t,n){let r=wn(e,t,n);return r===null?(e.lastStartAt.set(t,Date.now()),null):(e.scope.stats?.onRefused(t),r)}function wn(e,t,n){if(e.scope.signal.aborted)return bn(e.scope.signal);if(n?.aborted)return bn(n);let r=vn(e.lastStartAt,t);return r.allowed?null:xn(t,r.minIntervalMs,r.sinceLastMs)}const Tn=`\$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 En(e,t){t!==e.fault&&(e.fault=t,e.scope.observeLifeline(t))}function M(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),En(e,n))}function Dn(e){return e.fault===null?[]:[{kind:`lifeline`,message:`programs launched now would outlive their launcher if it died: its launch lifeline ${e.fault}, and the next launch starts another`}]}function On(e){let{stats:t}=e.scope;t?.onStart(`lifeline`);let n=Date.now(),r;try{r=oe(`awk`,[Tn],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(r){return t?.onEnd(`lifeline`,Date.now()-n),En(e,`did not start: ${gn(r,void 0)}`),null}t?.onEnd(`lifeline`,Date.now()-n);let i=r.stdin;if(i==null)return r.once(`error`,t=>En(e,`did not start: ${t.message}`)),null;r.once(`spawn`,()=>{e.lifeline?.process===r&&En(e,null)}),r.once(`error`,t=>M(e,r,`failed: ${t.message}`)),r.once(`exit`,(t,n)=>M(e,r,`exited ${n??t}`)),i.on(`error`,t=>M(e,r,`pipe failed: ${t.message}`)),Sn(e,new Promise(e=>r.once(`close`,e))),r.unref(),i.unref();for(let t of e.liveGroups)i.write(`+ ${t}\n`);return{process:r,pipe:i}}function kn(e,t){e.liveGroups.add(t),e.lifeline??=On(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function An(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function jn(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}function Mn(e,t){try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!Nn(e)))throw t}}function Nn(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}function Pn(e){let t=new ce(`utf8`),n=``,r=e=>{n+=t.write(e)};return e?.on(`data`,r),()=>{e?.off(`data`,r);let i=n+t.end();return n=``,i}}async function Fn(e,t){let{stats:n}=e.scope,r=Cn(e,t.category,t.signal);if(r!==null)return r;let i=Date.now();return n?.onStart(t.category),new Promise(r=>{let a;try{a=oe(t.bin,t.args??[],{cwd:t.cwd,env:yn(t),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(e){n?.onEnd(t.category,Date.now()-i),r({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:gn(e,t.cwd)});return}let o=a.pid;o!==void 0&&kn(e,o);let s=new Promise(e=>a.once(`exit`,e)),c=Pn(a.stdout),l=Pn(a.stderr),u=()=>({stdout:c(),stderr:l()}),d=!1,f=null,p=null,m=null,h=null,g=()=>S(`aborted`),_=()=>{t.signal?.removeEventListener(`abort`,g),e.inFlight.delete(g)},v=r=>{if(!d){d=!0,f&&clearTimeout(f),p&&clearTimeout(p),m&&clearTimeout(m),_(),o!==void 0&&An(e,o),n?.onEnd(t.category,Date.now()-i);for(let e of[a.stdout,a.stderr])e?.unref();r()}},y=e=>v(()=>r(e)),b=(n,r)=>{try{Mn(n,r)}catch(n){e.unreaped.set(a,t.category),s.then(()=>e.unreaped.delete(a)),y({ok:!1,reason:`signal-refused`,...u(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},x=()=>C(a.exitCode,a.signalCode);if(o!==void 0){let e=t=>{if(!d){if(Wn(o)){pe(x);return}m=setTimeout(()=>e(Math.min(t*2,1e3)),t)}};s.then(()=>pe(()=>e(25)))}let S=e=>{if((a.exitCode!==null||a.signalCode!==null)&&o!==void 0&&Wn(o)){h=e===`aborted`?e:null,pe(x);return}h=e,f&&clearTimeout(f),_();let t=a.pid;t!==void 0&&(p=setTimeout(()=>{b(t,`SIGKILL`),s.then(()=>pe(x))},250),b(t,`SIGTERM`))};a.on(`error`,e=>{y({ok:!1,reason:`spawn-error`,...u(),exitCode:null,signal:null,error:gn(e,t.cwd)})});let C=(e,t)=>{if(h!==null){y({ok:!1,reason:h,...u(),exitCode:e,signal:t});return}if(e===0){y({ok:!0,...u(),exitCode:e});return}y({ok:!1,reason:t?`signal`:`non-zero`,...u(),exitCode:e,signal:t})};a.on(`close`,C),t.timeoutMs&&t.timeoutMs>0&&(f=setTimeout(()=>S(`timeout`),t.timeoutMs)),t.signal?.addEventListener(`abort`,g,{once:!0}),e.inFlight.add(g),a.stdin?.on(`error`,()=>{}),a.stdin?.end(t.stdinInput)})}function In(e,t){let{stats:n}=e.scope,r=Cn(e,t.category);if(r!==null)return r;let i=Date.now();n?.onStart(t.category);let a=[`pipe`,`pipe`,`pipe`];try{let e=se(t.bin,t.args??[],{cwd:t.cwd,env:yn(t),input:t.stdinInput,timeout:t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:void 0,stdio:a,encoding:`utf8`});n?.onEnd(t.category,Date.now()-i);let r=typeof e.stdout==`string`?e.stdout:``,o=typeof e.stderr==`string`?e.stderr:``,s=e.error?.code;return e.error&&s!==`EPIPE`&&s!==`ECONNRESET`?{ok:!1,reason:s===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:r,stderr:o,exitCode:null,signal:e.signal??null,error:gn(e.error,t.cwd)}:e.status===0?{ok:!0,stdout:r,stderr:o,exitCode:e.status}:{ok:!1,reason:e.signal?`signal`:`non-zero`,stdout:r,stderr:o,exitCode:e.status,signal:e.signal??null}}catch(e){return n?.onEnd(t.category,Date.now()-i),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:gn(e,t.cwd)}}}function Ln(e,t){let{stats:n}=e.scope,r=Cn(e,t.category);if(r!==null)return r;let i=Date.now();n?.onStart(t.category);let a=Rn(t);return n?.onEnd(t.category,Date.now()-i),a}function Rn(e){let t;try{t=oe(e.bin,e.args??[],{cwd:e.cwd,env:yn(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:gn(t,e.cwd)}}return t.once(`error`,()=>{}),t.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${e.bin}): no pid (binary not found or unexecutable)`}:(t.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}const zn=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`;function Bn(e,t,n){let{stats:r}=e.scope,i=Cn(e,t.category);if(i!==null)return{ok:!1,reason:i.reason,error:i.error};let a=Date.now();r?.onStart(t.category);let o;try{o=oe(`/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:yn(t),detached:!0,stdio:[`pipe`,`ignore`,`ignore`]})}catch(e){return r?.onEnd(t.category,Date.now()-a),{ok:!1,reason:`spawn-error`,error:gn(e,t.cwd)}}r?.onEnd(t.category,Date.now()-a),o.once(`error`,()=>{});let s=o.pid,c=o.stdin;return c.on(`error`,()=>{}),s===void 0?(c.destroy(),{ok:!1,reason:`spawn-error`,error:`spawn(/bin/sh): no pid (shell not found or unexecutable)`}):(o.unref(),c.unref(),{ok:!0,pid:s,release:()=>c.end(`go
|
|
2
|
+
import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i}from"node:url";import{json as a}from"node:stream/consumers";import o,{basename as s,dirname as c,isAbsolute as l,join as u,sep as d}from"node:path";import f,{closeSync as p,constants as m,existsSync as h,fstatSync as g,linkSync as _,mkdtempSync as v,openSync as y,readFileSync as b,readSync as x,rmSync as S,statSync as C,writeFileSync as ee}from"node:fs";import te,{createHash as w,createHmac as ne,randomBytes as T,randomUUID as re,timingSafeEqual as E}from"node:crypto";import D,{homedir as ie,tmpdir as O}from"node:os";import ae from"node:net";import{spawn as oe,spawnSync as se}from"node:child_process";import{StringDecoder as ce}from"node:string_decoder";import{inspect as le,parseArgs as ue,types as de}from"node:util";import{clearInterval as fe,setImmediate as pe,setInterval as me}from"node:timers";import he from"node:v8";import{open as ge,readFile as _e,readdir as ve,stat as ye}from"node:fs/promises";import{get as be}from"node:https";import{setTimeout as xe}from"node:timers/promises";import{WriteStream as Se}from"node:tty";import{createInterface as Ce}from"node:readline";var we=Object.create,Te=Object.defineProperty,Ee=Object.getOwnPropertyDescriptor,De=Object.getOwnPropertyNames,Oe=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty,Ae=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),je=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=De(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ke.call(e,s)&&s!==n&&Te(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ee(t,s))||r.enumerable});return e},Me=(e,t,n)=>(n=e==null?{}:we(Oe(e)),je(t||!e||!e.__esModule?Te(n,`default`,{value:e,enumerable:!0}):n,e));const Ne=()=>!!process.env.CC_CANDYBAR_DEBUG;function Pe(e){return Ne()?`[DEBUG] ${e()}\n`:``}function k(e,...t){Ne()&&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)=>k(t),Le=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Re(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function ze(e){return Le.test(e)?e:Re(e)}function Be(e){return`${e.dir===void 0?``:`cd ${ze(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${ze(t)} `).join(``)}${[e.program,...e.args].map(ze).join(` `)}`}const Ve=`cc-extra`;function He(e){return o.join(o.dirname(e),Ve,`src`,`bun-attach.js`)}function Ue(e){return o.join(o.dirname(e),`bun-graph.js`)}const We=`attach-preload.cjs`;function Ge(e){return o.join(o.dirname(e),We)}function Ke(e,t){return Be({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const qe=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Je(e,t){return t.isSymbolicLink()?Buffer.from(f.readlinkSync(e)):f.readFileSync(e)}function Ye(e,t,n=qe){return f.readdirSync(t).filter(n).sort().flatMap(n=>{let r=o.join(t,n),i=f.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?Ye(e,r):[[o.relative(e,r).split(o.sep).join(`/`),Je(r,i)]]})}function Xe(e){let t=te.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Ze(e){return Xe(Ye(e,e))}const Qe=[`Cargo.toml`,`Cargo.lock`,`src`];function $e(e){return Xe(Ye(e,e,e=>Qe.includes(e)))}const et=e=>e.slice(0,7),tt=`1.180.2`;function nt(e){let t=o.dirname(o.dirname(e));return f.existsSync(o.join(t,`src`))?t:null}function rt(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:tt,digest:e}}function it(){return`6152ad2846defa03cf3f14b44ec6f56837671a9bafbd190992d0d198f1504c63`}function at(e){let t=JSON.parse(f.readFileSync(o.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${o.join(e,`package.json`)} has no version string`);return n}function ot(e,t){try{let n=nt(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Ze(o.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:at(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function st(e,t,n){let r=ct(e);f.mkdirSync(o.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??f.statSync(r,{throwIfNoEntry:!1})?.mode;try{f.writeFileSync(i,t,a===void 0?{}:{mode:a}),f.renameSync(i,r)}catch(e){throw f.rmSync(i,{force:!0}),e}}function ct(e){return lt(e).at(-1)}function lt(e){let{hops:t,stopped:n}=ut(e);if(n!==null)throw n;return t}function ut(e){let t=[e];try{for(let e=0;e<ft;e++){let e=dt(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${ft} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function dt(e){try{return f.lstatSync(e).isSymbolicLink()?o.resolve(f.realpathSync(o.dirname(e)),f.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const ft=40;function pt(e,t){let n=e[t];return n&&n.length>0?n:void 0}function mt(e=process.env){let t=pt(e,`XDG_STATE_HOME`)??o.join(D.homedir(),`.local`,`state`);return o.join(t,`cc-candybar`)}function ht(){let e=pt(process.env,`XDG_CACHE_HOME`)??o.join(D.homedir(),`.cache`);return o.join(e,`cc-candybar`)}function gt(){return mt()}function _t(){return process.env.CC_CANDYBAR_SOCKET||vt()}function vt(){let e=D.userInfo().uid;return o.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function yt(e){f.mkdirSync(e,{recursive:!0,mode:448});let t=f.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=D.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function bt(e){yt(o.dirname(e));for(let t of[e,xt(e)])try{if(f.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function xt(e){return`${e}.lease`}function St(){return xt(_t())}function Ct(e=process.env){return o.join(mt(e),`session-state.json`)}function wt(){return o.join(mt(),`settings-history.json`)}function Tt(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=D.userInfo().uid;return o.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function Et(){return o.join(mt(),`spawn.lock`)}function Dt(){return o.join(mt(),`spawn.cooldown`)}function Ot(){return o.join(mt(),`spawn.backoff`)}function kt(){return o.join(mt(),`watch-probe`)}function At(e=process.env){return o.join(mt(e),`daemon.log`)}const jt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Mt(e){return Object.fromEntries(jt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const Nt=[`native`,`node`,`frames`];function Pt(e,t){return{kind:e,bundle:t,source:null}}const Ft=[`ansi`,`frame`],It=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function Lt(e){let t=Gt(e.termCols),n=Gt(e.termRows),r=Kt(e.ssh),i=Wt(e.tmux),a=Ut(e.configEnv),o=Ut(e.claudeConfigDir),s=Ht(e.terminalEnv),c=Qt(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function Rt(e,t){return It.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function zt(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 Bt={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Vt(e){let t=Object.keys(Bt).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Bt[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
3
|
+
`)}function Ht(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=jt.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 Ut(e){return typeof e==`string`&&o.isAbsolute(e)?e:void 0}function Wt(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 A=1e4;function Gt(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>A?A:t}function Kt(e){return typeof e==`boolean`?e:void 0}function qt(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var Jt=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Yt(e){return Xt(JSON.stringify(e))}function Xt(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function j(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 Jt(`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 Jt(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function Zt(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.off(`data`,c),e.off(`error`,l),e.off(`close`,u);try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n-Date.now()),c=j(e=>o(()=>r(e)),e=>o(()=>i(e))),l=e=>o(()=>i(e)),u=()=>o(()=>i(Error(`socket closed before response`)));e.on(`data`,c),e.on(`error`,l),e.on(`close`,u),e.write(Yt(t))})}function Qt(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Ut(n);return Nt.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function $t(e,t,n){let r=null;try{r=await an(_t(),t.connectMs);let i=Date.now()+t.budgetMs,a=e(i),o=await Zt(r,{v:3,...a},i);return nn(a.kind,o,n)}catch(e){return rn(e)}finally{r&&r.destroy()}}function en(e,t){return typeof e==`string`?e:t}function tn(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function nn(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=en(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:tn(r.daemonV)};case`TIMEOUT`:return{kind:`busy`,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 rn(e){if(e instanceof Jt||e instanceof SyntaxError)return{kind:`permanent`,cause:`malformed_response`,message:e instanceof Error?e.message:String(e)};let t=e instanceof Error?e.message:String(e);return t===`CONNECT_TIMEOUT`||t===`TIMEOUT`?{kind:`busy`,message:t}:t.includes(`ECONNREFUSED`)||t.includes(`ENOENT`)||t.includes(`ENOTSOCK`)?{kind:`transient`,cause:`unreachable`,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function an(e,t){return new Promise((n,r)=>{let i=ae.createConnection({path:e}),a=setTimeout(()=>{i.destroy(),r(Error(`CONNECT_TIMEOUT`))},t);i.once(`connect`,()=>{clearTimeout(a),n(i)}),i.once(`error`,e=>{clearTimeout(a),r(e)})})}function on(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 sn(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 cn(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 ln={connectMs:50,budgetMs:150},un={connectMs:50,budgetMs:350};function dn(e){let t=e.output;return typeof t==`string`?t:void 0}function fn(e){return nn(`render`,e,dn)}function pn(e,t,n,r,i=ln){return $t(i=>({kind:`render`,hookData:e,args:t,cwd:n,deadline:i,...r}),i,dn)}function mn(e,t){return $t(()=>({kind:`pane-session`,socket:e,pane:t}),un,e=>`paneSession`in e?e.paneSession:void 0)}function hn(e,t){return $t(()=>({kind:`click`,verb:e,value:t,clientVersion:tt}),un,dn)}function gn(e,t){return de.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!h(t)?`working directory does not exist: ${t}`:e.message:String(e)}const _n={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function vn(e,t){let n=_n[t];if(n===void 0)return{allowed:!0};let r=e.get(t);if(r===void 0)return{allowed:!0};let i=Date.now()-r;return i>=n?{allowed:!0}:{allowed:!1,minIntervalMs:n,sinceLastMs:i}}function yn(e){return e.env??process.env}const bn=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function xn(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${n}ms ago`}}function Sn(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function Cn(e,t,n){let r=wn(e,t,n);return r===null?(e.lastStartAt.set(t,Date.now()),null):(e.scope.stats?.onRefused(t),r)}function wn(e,t,n){if(e.scope.signal.aborted)return bn(e.scope.signal);if(n?.aborted)return bn(n);let r=vn(e.lastStartAt,t);return r.allowed?null:xn(t,r.minIntervalMs,r.sinceLastMs)}const Tn=`\$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 En(e,t){t!==e.fault&&(e.fault=t,e.scope.observeLifeline(t))}function M(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),En(e,n))}function Dn(e){return e.fault===null?[]:[{kind:`lifeline`,message:`programs launched now would outlive their launcher if it died: its launch lifeline ${e.fault}, and the next launch starts another`}]}function On(e){let{stats:t}=e.scope;t?.onStart(`lifeline`);let n=Date.now(),r;try{r=oe(`awk`,[Tn],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(r){return t?.onEnd(`lifeline`,Date.now()-n),En(e,`did not start: ${gn(r,void 0)}`),null}t?.onEnd(`lifeline`,Date.now()-n);let i=r.stdin;if(i==null)return r.once(`error`,t=>En(e,`did not start: ${t.message}`)),null;r.once(`spawn`,()=>{e.lifeline?.process===r&&En(e,null)}),r.once(`error`,t=>M(e,r,`failed: ${t.message}`)),r.once(`exit`,(t,n)=>M(e,r,`exited ${n??t}`)),i.on(`error`,t=>M(e,r,`pipe failed: ${t.message}`)),Sn(e,new Promise(e=>r.once(`close`,e))),r.unref(),i.unref();for(let t of e.liveGroups)i.write(`+ ${t}\n`);return{process:r,pipe:i}}function kn(e,t){e.liveGroups.add(t),e.lifeline??=On(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function An(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function jn(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}function Mn(e,t){try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!Nn(e)))throw t}}function Nn(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}function Pn(e){let t=new ce(`utf8`),n=``,r=e=>{n+=t.write(e)};return e?.on(`data`,r),()=>{e?.off(`data`,r);let i=n+t.end();return n=``,i}}async function Fn(e,t){let{stats:n}=e.scope,r=Cn(e,t.category,t.signal);if(r!==null)return r;let i=Date.now();return n?.onStart(t.category),new Promise(r=>{let a;try{a=oe(t.bin,t.args??[],{cwd:t.cwd,env:yn(t),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(e){n?.onEnd(t.category,Date.now()-i),r({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:gn(e,t.cwd)});return}let o=a.pid;o!==void 0&&kn(e,o);let s=new Promise(e=>a.once(`exit`,e)),c=Pn(a.stdout),l=Pn(a.stderr),u=()=>({stdout:c(),stderr:l()}),d=!1,f=null,p=null,m=null,h=null,g=()=>S(`aborted`),_=()=>{t.signal?.removeEventListener(`abort`,g),e.inFlight.delete(g)},v=r=>{if(!d){d=!0,f&&clearTimeout(f),p&&clearTimeout(p),m&&clearTimeout(m),_(),o!==void 0&&An(e,o),n?.onEnd(t.category,Date.now()-i);for(let e of[a.stdout,a.stderr])e?.unref();r()}},y=e=>v(()=>r(e)),b=(n,r)=>{try{Mn(n,r)}catch(n){e.unreaped.set(a,t.category),s.then(()=>e.unreaped.delete(a)),y({ok:!1,reason:`signal-refused`,...u(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},x=()=>C(a.exitCode,a.signalCode);if(o!==void 0){let e=t=>{if(!d){if(Wn(o)){pe(x);return}m=setTimeout(()=>e(Math.min(t*2,1e3)),t)}};s.then(()=>pe(()=>e(25)))}let S=e=>{if((a.exitCode!==null||a.signalCode!==null)&&o!==void 0&&Wn(o)){h=e===`aborted`?e:null,pe(x);return}h=e,f&&clearTimeout(f),_();let t=a.pid;t!==void 0&&(p=setTimeout(()=>{b(t,`SIGKILL`),s.then(()=>pe(x))},250),b(t,`SIGTERM`))};a.on(`error`,e=>{y({ok:!1,reason:`spawn-error`,...u(),exitCode:null,signal:null,error:gn(e,t.cwd)})});let C=(e,t)=>{if(h!==null){y({ok:!1,reason:h,...u(),exitCode:e,signal:t});return}if(e===0){y({ok:!0,...u(),exitCode:e});return}y({ok:!1,reason:t?`signal`:`non-zero`,...u(),exitCode:e,signal:t})};a.on(`close`,C),t.timeoutMs&&t.timeoutMs>0&&(f=setTimeout(()=>S(`timeout`),t.timeoutMs)),t.signal?.addEventListener(`abort`,g,{once:!0}),e.inFlight.add(g),a.stdin?.on(`error`,()=>{}),a.stdin?.end(t.stdinInput)})}function In(e,t){let{stats:n}=e.scope,r=Cn(e,t.category);if(r!==null)return r;let i=Date.now();n?.onStart(t.category);let a=[`pipe`,`pipe`,`pipe`];try{let e=se(t.bin,t.args??[],{cwd:t.cwd,env:yn(t),input:t.stdinInput,timeout:t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:void 0,stdio:a,encoding:`utf8`});n?.onEnd(t.category,Date.now()-i);let r=typeof e.stdout==`string`?e.stdout:``,o=typeof e.stderr==`string`?e.stderr:``,s=e.error?.code;return e.error&&s!==`EPIPE`&&s!==`ECONNRESET`?{ok:!1,reason:s===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:r,stderr:o,exitCode:null,signal:e.signal??null,error:gn(e.error,t.cwd)}:e.status===0?{ok:!0,stdout:r,stderr:o,exitCode:e.status}:{ok:!1,reason:e.signal?`signal`:`non-zero`,stdout:r,stderr:o,exitCode:e.status,signal:e.signal??null}}catch(e){return n?.onEnd(t.category,Date.now()-i),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:gn(e,t.cwd)}}}function Ln(e,t){let{stats:n}=e.scope,r=Cn(e,t.category);if(r!==null)return r;let i=Date.now();n?.onStart(t.category);let a=Rn(t);return n?.onEnd(t.category,Date.now()-i),a}function Rn(e){let t;try{t=oe(e.bin,e.args??[],{cwd:e.cwd,env:yn(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:gn(t,e.cwd)}}return t.once(`error`,()=>{}),t.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${e.bin}): no pid (binary not found or unexecutable)`}:(t.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}const zn=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`;function Bn(e,t,n){let{stats:r}=e.scope,i=Cn(e,t.category);if(i!==null)return{ok:!1,reason:i.reason,error:i.error};let a=Date.now();r?.onStart(t.category);let o;try{o=oe(`/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:yn(t),detached:!0,stdio:[`pipe`,`ignore`,`ignore`]})}catch(e){return r?.onEnd(t.category,Date.now()-a),{ok:!1,reason:`spawn-error`,error:gn(e,t.cwd)}}r?.onEnd(t.category,Date.now()-a),o.once(`error`,()=>{});let s=o.pid,c=o.stdin;return c.on(`error`,()=>{}),s===void 0?(c.destroy(),{ok:!1,reason:`spawn-error`,error:`spawn(/bin/sh): no pid (shell not found or unexecutable)`}):(o.unref(),c.unref(),{ok:!0,pid:s,release:()=>c.end(`go
|
|
4
4
|
`),withdraw:()=>c.end()})}function Vn(e){let t;try{t=b(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 Hn(e,t){try{return process.kill(-e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}function Un(e){return Hn(e,0)}function Wn(e){try{return process.kill(-e,0),!1}catch(e){return e.code===`ESRCH`}}function Gn(e,t,n){let r=`${t}.${process.pid}`;try{ee(r,`${zn(n)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let i=!0;try{_(r,t)}catch(e){if(e.code!==`EEXIST`)throw e;i=!1}finally{S(r,{force:!0})}let a=Hn(e,`SIGTERM`);return a&&setTimeout(()=>Hn(e,`SIGKILL`),250).unref(),{stands:i,signalled:a}}function Kn(e){return Jn(e).launcher}function qn(e){let{launcher:t,state:n}=Jn(e);return{...t,launchSync:e=>In(n,e)}}function Jn(e){let t={launch:e=>Sn(n,Fn(n,e)),launchDetachedSync:e=>Ln(n,e),launchJobSync:(e,t)=>Bn(n,e,t),lifelineWarnings:()=>Dn(n),settled:async()=>(await Promise.all(n.ending),{unreaped:[...n.unreaped.values()]}),__lifelineForTest:()=>{let e=n.lifeline;return{pid:e?.process.pid,cut:()=>{e?.pipe.end(),e&&M(n,e.process,`cut by a test`)}}}},n={scope:{stats:null,observeLifeline:()=>t.lifelineWarnings().forEach(e=>process.emitWarning(e.message)),signal:new AbortController().signal,...e},lastStartAt:new Map,inFlight:new Set,liveGroups:new Set,lifeline:null,fault:null,ending:new Set,unreaped:new Map};return n.scope.signal.addEventListener(`abort`,()=>{n.inFlight.forEach(e=>e()),jn(n)},{once:!0}),{launcher:t,state:n}}const Yn=qn({}),Xn=Yn;let Zn=null;function Qn(){if(Zn!==null){try{f.closeSync(Zn.fd)}catch{}Zn=null}}async function $n(e){let t=await f.promises.stat(e).catch(()=>null);if(Zn!==null&&Zn.path===e&&t!==null&&Zn.id===er(t))return{held:Zn,size:t.size};Qn(),await f.promises.mkdir(o.dirname(e),{recursive:!0});let n=await new Promise((t,n)=>f.open(e,`a`,(e,r)=>e===null?t(r):n(e))),r=await new Promise((e,t)=>f.fstat(n,(n,r)=>n===null?e(r):t(n)));return Zn={path:e,fd:n,id:er(r)},{held:Zn,size:r.size}}function er(e){return`${e.dev}:${e.ino}`}function tr(e,t){return new Promise((n,r)=>f.write(e,t,(e,t)=>e===null?n(t):r(e)))}async function nr(e){for(let t=2;t>=1;t--)await f.promises.rename(`${e}.${t}`,`${e}.${t+1}`).catch(()=>{});await f.promises.rename(e,`${e}.1`).catch(()=>{})}let rr=[],ir=0,ar=0,or=0,sr=null,cr=!1;const lr=[];let ur=!1,dr=!1;function fr(e,t){return`${new Date().toISOString()} [${e}] ${t}\n`}function pr(e,t){let n=fr(e,t);if(dr||(dr=!0,process.on(`exit`,()=>{ur=!0,br(!0,vr)})),rr.push(n),ir+=Buffer.byteLength(n),ir>4194304){let e=0;for(;ir>4194304/2&&e<rr.length-1;){let t=Buffer.byteLength(rr[e]);ir-=t,or+=t,e++}rr.splice(0,e),ar+=e}ur?br(!0,vr):cr||hr()}function mr(){br(!1,yr)}async function hr(){cr=!0;try{for(;rr.length>0;){let e=gr();sr={bytes:Buffer.from(e),state:{kind:`taken`}};try{await _r(At(),sr)}catch(t){Qn(),sr.state.kind!==`landed`&&Sr(e,t)}finally{sr=null}}}finally{cr=!1;for(let e of lr.splice(0))e()}}function gr(){let e=(ar===0?``:fr(`warn`,`log: ${ar} earlier line(s) dropped (${or} bytes): more than 4194304 bytes were waiting for the disk`))+rr.join(``);return rr=[],ir=0,ar=0,or=0,e}async function _r(e,t){let{held:n,size:r}=await $n(e);if(t.state.kind===`landed`)return;let{bytes:i}=t,a=r+i.length;t.state={kind:`issued`,fd:n.fd,endsAt:a};for(let e=0;e<i.length;){let t=await tr(n.fd,i.subarray(e));if(t===0)throw Error(`the disk took 0 bytes of a write`);e+=t}if(t.state={kind:`landed`},a>=5242880){Qn();let e=await f.promises.stat(n.path).catch(()=>null);e!==null&&er(e)===n.id&&await nr(n.path)}}const vr=1e3,yr=2e3;function br(e,t){let n=sr,r=Buffer.alloc(0);n!==null&&n.state.kind===`taken`&&(r=n.bytes,n.state={kind:`landed`});let i=null;if(n!==null&&n.state.kind===`issued`){let{fd:a,endsAt:o}=n.state;try{let s=xr(a,o,t);s<o&&e?(r=n.bytes.subarray(Math.max(0,s-(o-n.bytes.length))),n.state={kind:`landed`}):s<o&&(i={fd:a,endsAt:o})}catch(t){e&&(r=n.bytes,n.state={kind:`landed`}),Sr(n.bytes.toString(),t)}}if(r.length===0&&rr.length===0)return;let a=Buffer.concat([r,Buffer.from(gr())]);try{let e=At();f.mkdirSync(o.dirname(e),{recursive:!0}),f.appendFileSync(e,a),i!==null&&n!==null&&er(f.fstatSync(i.fd))===er(f.statSync(e))&&(n.state={kind:`issued`,fd:i.fd,endsAt:i.endsAt+a.length})}catch(e){Sr(a.toString(),e)}}function xr(e,t,n){let r=performance.now()+n,i=new Int32Array(new SharedArrayBuffer(4));for(;;){let{size:n}=f.fstatSync(e);if(n>=t||performance.now()>=r)return n;Atomics.wait(i,0,0,1)}}function Sr(e,t){try{process.stderr.write(`${e}cc-candybar: daemon.log unwritable: ${t.message}\n`)}catch{}}const Cr=5e3;async function wr(e){let t=[];for(let n of e){let e=await n.read();if(e.kind===`text`)return`# memory report from: ${n.name}\n${e.text}`;t.push(`# ${n.name}: unavailable — ${e.reason}`)}return[`# memory report: no probe answered`,...t.length>0?t:[`# no probe is known for this platform`]].join(`
|
|
5
5
|
`)}const Tr=`/usr/bin/footprint`;function Er(e,t,n){return t===`darwin`?[Ar(e,Tr,[`-p`,String(n)]),Ar(e,`/usr/bin/vmmap`,[`--summary`,String(n)])]:t===`linux`?[jr(`/proc/self/smaps_rollup`),jr(`/proc/self/status`)]:[]}function Dr(e,t,n){return t===`darwin`?Or(n,t=>e.launch({bin:Tr,args:t,timeoutMs:Cr,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function Or(e,t){return async n=>{let r=await t([`-p`,String(e),`--noCategories`,`-f`,`bytes`]);if(!r.ok)return{kind:`stand-in`,bytes:n,unread:`footprint ${r.reason}${r.error===void 0?``:`: ${r.error}`}${Mr(r.stderr)}`};let i=kr(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 kr(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function Ar(e,t,n){return{name:`${t} ${n.join(` `)}`,read:async()=>{let r=await e.launch({bin:t,args:[...n],timeoutMs:Cr,category:`limits.memory-report`});return r.ok?r.stdout.trim().length>0?{kind:`text`,text:r.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${r.reason}${r.error===void 0?``:`: ${r.error}`}${Mr(r.stderr)}`}}}}function jr(e){return{name:e,read:async()=>{try{let t=f.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}function Mr(e){let t=e.split(`
|
|
6
6
|
`).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const Nr=`CC_CANDYBAR_RSS_LIMIT_MB`;function Pr(e){let t=e[Nr];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${Nr} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function Fr(e){return Pr(e)*2}const Ir=1024*1024,Lr=e=>Math.round(e/Ir);function Rr(e){return Pr(e)*Ir}const zr={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function Br(e,t){return e>t}function Vr(e,t){if(e.kind===`charged`)return e;let n=t.kind===`unmeasured`?0:t.charge.kind===`charged`?t.rss-t.charge.bytes:t.charge.gap;return{...e,bytes:e.bytes-n,gap:n}}const Hr=.75;function Ur(e,t){return e>t*Hr}function Wr(e,t,n){let{prefix:r,suffix:i}=zr[t];return o.join(e,`${r}${n}${i}`)}function Gr(e){for(let t of Object.keys(zr)){let{prefix:n,suffix:r}=zr[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function Kr(e){let t=e.limitBytes??1024*Ir,n=e.snapshotsKeep??3,r=!1,i={kind:`unmeasured`},a=null,o=!1,s;function c(){return a??=l().finally(()=>{a=null}),a}async function l(){if(r)return!0;let{rss:a,heapTotal:s}=e.memoryBytes(),c=Vr(await e.memoryCharge(a),i),l={kind:`measured`,charge:c,rss:a,heapTotal:s};if(i=l,e.log(`info`,`memory ${Yr(l,t)}`),o||c.bytes<=t)return!1;r=!0,e.log(`warn`,`${qr(c)} > limit ${Lr(t)} MB (rss ${Lr(a)} MB, v8 heap ${Lr(s)} MB); recording memory then shutting down`);let u=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return await Xr(e.log,`memory report`,async()=>{let t=Wr(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 Xr(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=Wr(e.snapshotDir,`heapSnapshot`,u);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),await Xr(e.log,`artifact rotation`,async()=>{for(let{artifacts:t}of Zr(e.listArtifacts()).slice(n))for(let n of Object.values(t))await Xr(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0)}function u(){return i.kind===`measured`&&Ur(i.charge.bytes,t)?`${qr(i.charge)} approaching limit ${Lr(t)} MB (v8 heap ${Lr(i.heapTotal)} MB)`:null}function d(){let n;try{n={kind:`ok`,value:Zr(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=setTimeout(()=>void n(),t),s.unref())};n()}function p(){o=!0,clearTimeout(s)}return{check:c,describeNextRestart:u,serving:d,arm:f,disarm:p}}function qr(e){return e.kind===`charged`?`${e.measure} ${Lr(e.bytes)} MB`:`rss ${Lr(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${Lr(e.gap)} MB gap`} (standing in: ${e.unread})`}function Jr(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function Yr({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${Lr(e.gap)}MB`:``;return`measure=${Jr(e)} charge=${Lr(e.bytes)}MB rss=${Lr(t)}MB heap=${Lr(n)}MB limit=${Lr(r)}MB${i}`}async function Xr(e,t,n){try{await n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function Zr(e){let t=new Map;for(let n of e){let e=o.basename(n),r=Gr(e);if(r===null)continue;let{prefix:i,suffix:a}=zr[r],s=e.slice(i.length,e.length-a.length);t.set(s,{...t.get(s),[r]:n})}let n=Object.keys(zr);return[...t].sort(([e],[t])=>Br(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function Qr(e,t,n,r={}){let i=gt();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:n.log,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},memoryCharge:Dr(n.launcher,process.platform,process.pid),captureMemoryReport:()=>wr(Er(n.launcher,process.platform,process.pid)),writeMemoryReport:(e,t)=>f.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>he.writeHeapSnapshot(e),writeLogNow:mr,listArtifacts:()=>{let e;try{e=f.readdirSync(i)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>Gr(e)!==null).map(e=>o.join(i,e))},removeFile:e=>f.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}function $r(e={}){if(hi()!==null)return;let n=e.spawn??_i,r=fi();if(r.kind===`contended`){let e=ti();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),ei(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),ei(n);return}try{ei(n)}finally{mi()}}function ei(e){ci()&&ni(e)}function ti(){try{let e=f.statSync(Et());return Date.now()-e.mtimeMs}catch{return null}}function ni(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
|
|
@@ -56,9 +56,9 @@ import{createRequire as e}from"node:module";import t from"node:process";import{U
|
|
|
56
56
|
|
|
57
57
|
`)}},Aee=class extends Error{constructor(e){super(e.map(e=>e.message).join(`
|
|
58
58
|
`)),this.errors=e,this.name=`DroppedPlacements`}};function q(e,t){return wb(e)(t)}function wb(e){let t,n=()=>(t??={node:jee(e)},t.node);return t=>Mee(e,n,t)}function jee(e){try{return Ua(e)}catch(e){if(e instanceof La)return;throw e}}function Mee(e,t,n){let r=n.some(e=>/^\d+$/.test(e))?Nee(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=Pee(e,i,t);if(n===-1)return a===void 0?void 0:Tb(e,a);i=n,a=n}return a===void 0?void 0:Tb(e,a)}function Nee(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:Wa(r,e)?.value;if(n===void 0)break;a||=t,r=n,i=n}return i===void 0||!a?void 0:Tb(e,i.span.start)}function Pee(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 Tb(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Fee(e,t){try{return Ua(t),null}catch(n){if(!(n instanceof La))throw n;return`${e}:${Tb(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function Iee(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(`
|
|
59
|
-
`)}function Eb(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 ${jb(i)}`,line:q(e.source,[...t.split(`.`),r])}),null)}function Lee(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 ${jb(i)}`,line:q(e.source,[...t.split(`.`),`default`])});return}return i}}function Db(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 ${jb(i)}`,line:q(e.source,[...t.split(`.`),r])});return}return i}}function Ob(e,t,n){let r=Db(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${dy(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:q(e.source,[...t.split(`.`),`palette`])});return}return r}}function kb(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 ${J(a)}`,line:q(e.source,[...t.split(`.`),r])});return}return a}}function Ab(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jb(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function J(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function Mb(e,t,n,r){return Ab(r)?(Ib(e,n,r,t.noun,new Set(Object.keys(t.fields)),Nb(e,t.removed??{},n,r)),Pb(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${jb(r)}`,line:q(e.source,n.split(`.`))}),null)}function Nb(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)Lb(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function Pb(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 Fb=new Set;function Ib(e,t,n,r,i,a=Fb){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:q(e.source,[...t.split(`.`),o])})}function Lb(e,t,n){return e.issues.push({path:t,message:n,line:q(e.source,t.split(`.`))}),null}function Rb(e,t,n,r){if(!Ab(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${jb(r)}`,line:q(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:q(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:q(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:q(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function zb(e,t,n,r){if(!Ab(r))return e.issues.push({path:n,message:`${n} must be an object, got ${jb(r)}`,line:q(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 ${jb(i)}`,line:q(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:q(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 Ib(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function Bb(e,t,n){return{json:ex(Qb(n),e,t),keys:new Set([e,...Object.keys(n)])}}function Vb(e){return(...t)=>e()(...t)}function Hb(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:q(n.source,o.split(`.`))}),null}return a}}function Ub(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Db(e,t,r,n)}}function Wb(){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 ${jb(i)}`,line:q(e.source,[n])});return}return i}}}}function Gb(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 ${J(o)}`,line:q(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 ${J(a)}`,line:q(e.source,[r])});return}return a}}}}function qb(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Ob(e,t,r)}}function Jb(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Eb(e,t,r,n)??void 0}}function Yb(e,t){return l(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function Xb(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=Eb(e,t,r,n);if(i===null)return;let a=Yb(`${t}.${n}`,i);return a===null?i:Lb(e,`${t}.${n}`,a)??void 0}}}function Zb(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>kb(t,n,i,r,e)}}function Qb(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 $b(e){return Qb(e.fields)}function ex(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function tx(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function nx(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const rx=[`claude`,`tmux`],ix=`ne .tmux.pane ""`,ax={band:{switch:{setting:`experimentalBand`,on:!0,inTmux:!1},label:`🧪 band (A)`,handsOff:!0,rows:null},statusline:{switch:{setting:`experimentalStatusline`,on:!0,inTmux:!1},label:`🧪 statusline (B)`,handsOff:!1,rows:null},pane:{switch:{setting:`experimentalPane`,on:!0,inTmux:!1},label:`🧪 tmux pane (C)`,handsOff:!0,rows:null},tmuxStatus:{switch:{setting:`renderer`,on:`tmux`,inTmux:!0},label:`tmux status line`,handsOff:!0,rows:5}},ox=Object.keys(ax),sx=ox.filter(e=>ax[e].switch.on===!0),cx={by:`request`},lx=e=>`drawing.${e}`,ux={subscribers:0,fps:0,shown:!0},dx=(e,t)=>`feeds.${e}.${t}`;function fx(e){return Object.fromEntries(ox.map(t=>[t,e(t)]))}const px=fx(()=>ux);function mx(e){return typeof e==`string`&&Object.hasOwn(ax,e)?e:null}const hx=(e,t)=>Array.from({length:e*2},(e,n)=>({lit:n%2==0,seconds:t})),gx=[...hx(3,1),...hx(3,.25)],_x=gx.reduce((e,{seconds:t})=>e+t,0),Ree={min:15,max:600,step:15},zee=(e,t)=>e+t,Bee=e=>e-_x,vx=(e,t,{previews:n=[],shown:r=`true`}={})=>({label:e,place:t,previews:n,shown:r}),yx=(e,t,n={})=>({spec:Zb(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e,...n}}}),bx=e=>t=>e.includes(t)?`🧪 ${t}`:t,xx={spec:Wb(),domain:`bool`,parse:Jy},Sx=e=>({spec:Gb(e),domain:e,parse:t=>Yy(t,e)});function Cx(e,t,n,r={}){return{kind:`session`,...yx(e,r.optionDomain,{library:r.library,labelOf:r.labelOf}),floor:t,control:n,themeDefault:r.themeDefault??!1}}function wx(e,t){return{kind:`session`,...xx,floor:e,control:t,themeDefault:!1}}function Tx(e,t,n){return{kind:`session`,...Sx(e),floor:t,control:n,themeDefault:!1}}function Ex(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const Dx=e=>({kind:`text`,spec:e}),Ox={required:!1,json:{enum:[...zy]},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: ${zy.join(`, `)}`,line:q(e.source,[...t.split(`.`),n])});return}return kb(e,t,r,n,zy)}},kx={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=Db(e,t,r,n);return by(i)?i:Ob(e,t,r)}},Ax={required:!1,json:{anyOf:[{enum:[...ky]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&by(i)?i:kb(e,t,r,n,ky)}},jx=/^[^\r\n]*\S[^\r\n]*$/u,Mx=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),Nx={required:!1,json:{type:`string`,pattern:jx.source,not:{pattern:Mx.source}},parse:(e,t,n,r)=>{let i=Db(e,t,r,n);if(i===void 0||jx.test(i)&&!Mx.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:q(e.source,[...t.split(`.`),n])})}},Px=Object.fromEntries(sx.map(e=>[ax[e].switch.setting,wx(!1,vx(ax[e].label,`toggles`))])),Fx={claude:`Claude Code's status line`,tmux:`the tmux status line, while this pane is shown`},Ix={groups:[{id:`renderer`,label:`draw the bar in`}],entry:e=>({group:`renderer`,description:Fx[e]})},Lx={palette:Ex(`theme`,kx,{themes:`themes`},vx(`🎨 theme`,`door`)),preset:Ex(`preset`,Ub(),{from:`presets`},vx(`▦ preset`,`door`,{previews:[`layout`,`presetDelete`]})),style:Ex(`style`,Ub(),{from:`styles`},vx(`◐ style`,`gear`,{previews:[`palette`]}),{themeDefault:!0}),effect:Ex(`effect`,Ax,{from:ky},vx(`✨ effect`,`look`)),endcaps:Cx(Iy,`powerline`,vx(`✦ endcaps`,`look`),{optionDomain:`endcaps`}),variation:Cx(Hy,`accent`,vx(`🎼 variation`,`gear`,{previews:[`layout`]}),{optionDomain:`variations`,labelOf:bx(uv),themeDefault:!0}),shade:Cx(Uy,`middle`,vx(`🔆 shade`,`gear`,{previews:[`layout`]}),{optionDomain:`shades`,labelOf:bx($_),themeDefault:!0}),transitions:wx(!1,vx(`fade in/out`,`look`)),animationSpeed:Cx(jy,`1x`,vx(`speed`,`look`)),autoWrap:wx(!0,vx(`wrap`,`config`)),padding:Tx({...qy,step:1},1,vx(`padding`,`config`)),updateNotice:wx(!0,vx(`update notice`,`config`)),menuTimeout:Tx(Ree,120,vx(`menu timeout`,`config`)),renderer:Cx(rx,`claude`,vx(`renderer`,`config`,{shown:ix}),{optionDomain:`renderers`,library:Ix}),...Px,colorCompatibility:{kind:`config`,...yx(zy,`colorCompatibilities`),spec:Ox,floor:`truecolor`},default_empty_value:Dx(Ub()),default_separator:Dx(Ub()),menuGlyph:Dx(Nx)},Rx=Object.entries(Lx),zx=Rx.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),Bx=Rx.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),Vx=Rx.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),Hx=Rx.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function Ux(e){return Lx[e]}const Wx=e=>Ux(e).floor;function Gx(e){let t=Lx[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const Kx=e=>`${e}.effective`,qx=e=>{let t=Lx[e];return t.kind===`selection`?t.sessionKey:e},Jx=Object.fromEntries(Bx.map(e=>{let t=qx(e);return[t,{configKey:e,sessionKey:t,effectiveVar:Kx(t),...Lx[e].control}]})),Yx=Object.keys(Jx),Xx=Object.values(Jx),Zx=zx.filter(e=>Lx[e].kind===`config`).map(e=>({configKey:e,effectiveVar:Kx(e)})),Qx=new Set(Zx.map(e=>e.configKey)),$x=new Map([...Xx,...Zx].map(e=>[e.configKey,e.effectiveVar])),eS=new Map(Xx.map(e=>[e.sessionKey,e.effectiveVar]));function tS(e){return Object.fromEntries(Yx.map(t=>[t,e(t)]))}const nS=new Map(Yx.map(e=>[Jx[e].sessionKey,e])),rS=[[0,31],[127,159],[8234,8238],[8294,8303]];function iS(e){return rS.some(([t,n])=>e>=t&&e<=n)}function aS(e){let t=``;for(let n of e)t+=iS(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function oS(e,t){let n=aS(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const sS={fg:`#ffffff`,bg:`#c82828`},cS={fg:`#000000`,bg:`#dca028`};function lS(e,t){return`\x1b[${e};2;${[1,3,5].map(e=>Number.parseInt(t.slice(e,e+2),16)).join(`;`)}m`}const uS=lS(38,sS.fg),dS=lS(48,sS.bg),fS=new Gf({"strip.separator":`default`,"strip.rail":`default`});function pS(e){return fS.resolve(e)}const mS={kind:`still`},hS=e=>Wp.at(e.timeline,e.wall),gS=Symbol(`bar`);function _S(e){return e.name!==Ey}function vS(e){return t=>G.map(G.all(e.map(({timeline:e,effect:n})=>Wp.run(e,n(t)))),e=>(t,n)=>e.reduce((e,t)=>t(e,n),t))}const yS=tf;function bS(e,t){let n=new xu(t,yS.foregroundColor,yS.ansiColors,yS.palette);return t=>e({...t,theme:n})}function xS(e,t){return n=>Bh(()=>e(n),...t)(n)}function SS(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 CS=4096;function Vee(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=gx.reduceRight((e,{lit:t,seconds:n})=>G.sequence(G.constant(t?r:i),n,e),G.constant(i)),o=G.sequence(G.constant(i),n,a);return()=>o}var wS=class{inForce=null;anchor=Wp.play(0);placements=new Map;made=new Map;passages=null;frame={effect:Ey,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:Wp.withRate(this.anchor,e,t)}}motion(e,t,n,r=null){let i=hS(t),a=e=>Wp.seek(t.timeline,t.wall,e),o=this.inForce?.name===e?this.inForce:{name:e,since:i},s={scope:gS,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=a_.transitions[e]({z:SS(`${this.key}@${t}`)*CS});return{name:e,since:i,done:e=>r.done(e),effect:bS(r.effect,n)}},C=({since:e,done:t})=>t(i-e),ee=(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}),te=(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)}},w=(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?te(e,r):ee(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)},ne=(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}},T=(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=SS(t.scope===gS?e:`${e}@${t.scope}`),s=a?i.effect:a_.loops[t.name]({z:o*CS});return x[a?`reused`:`made`]++,n.set(t.scope,{name:t.name,effect:s}),s},re=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?s:ne(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()]},E=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:Bh(n.effect,...t)}]})},D=r===null?[]:[{timeline:Wp.play(r.idleSince),effect:Vee(r.fill,r.text,Bee(r.timeoutS))}],ie=e=>e===`menu`?D:[];return{placed:h===`off`?(e,t)=>t:w,row:(e,n,r)=>{let i=(r.some(e=>e.placement.effect!==`bar`)?re(r):[{...s,owners:void 0}]).filter(_S),o=E(r),c=ie(n);if(i.length===0&&o.length===0&&c.length===0)return mS;let l=`${this.key}#${e}`;return{kind:`moving`,time:t.wall,wrap:e=>new Ah(e,vS([...i.map(e=>{let t=T(l,e);return{timeline:a(e.t),effect:e.owners===void 0?t:xS(t,e.owners)}}),...o,...c]),{key:l,theme:yS})}},drawn:()=>{this.anchor=t.timeline,this.inForce=o,this.placements=l,this.made=d,this.passages=h===`off`?null:v,this.frame=x}}}},Hee=class{sessions=new Map;constructor(e=256){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new wS(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 Uee=`${dS}${uS}`;function TS(e){return`⚠ cc-candybar: ${Gee(e)}`}function Wee(e){return`${Uee}${TS(e)}[0m\n`}function Gee(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: ${oS(e.message,60)}`;case`render_failed`:return`render failed: ${oS(e.message,60)}`;case`switched_off`:return`switched off: ${oS(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${oS(e.message,60)}`}}function ES(e,t){return{depth:e.depth,rows:t,nextChange:1/0,motion:e.motion===`still`?`still`:`can-move`,pending:[]}}function DS(e,t){return{depth:`truecolor`,rows:[{kind:`diagnostic`,runs:[{text:aS(e),...t}]}],nextChange:1/0,motion:`still`,pending:[]}}function OS(e){return DS(TS({kind:`permanent`,cause:`render_failed`,message:e}),sS)}function kS(e,t){try{return e(t)}catch(t){return e(DS(`⚠ cc-candybar ${t instanceof Error?t.message:String(t)}`,sS))}}function AS(e){return e.type===V.TRUECOLOR?e.value.hex:e.number===void 0?e.name:`color(${e.number})`}const jS=Object.keys(new U().attributes);function MS(e,t){let{color:n,bgcolor:r}=e.drawnColors(t),i=jS.filter(t=>e[t]===!0);return{...n!==void 0&&{fg:AS(n)},...r!==void 0&&{bg:AS(r)},...i.length>0&&{attrs:i}}}function NS({text:e,style:t},n){return{text:e,...t!==void 0&&n!==null&&MS(t,n),...t?.link!==void 0&&{link:t.link}}}function PS(e,t){let n=e.filter(e=>!e.isControl&&e.text.length>0);return W.splitLines(n).map(e=>e.map(e=>NS(e,t)))}function FS({text:e,fg:t,bg:n,attrs:r=[],link:i}){return new W(e,new U({color:t,bgcolor:n,link:i,...Object.fromEntries(r.map(e=>[e,!0]))}))}function IS(e,t){let n=Ql(t);return e.map(e=>Eh(e.map(FS),n)).join(`
|
|
59
|
+
`)}function Eb(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 ${jb(i)}`,line:q(e.source,[...t.split(`.`),r])}),null)}function Lee(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 ${jb(i)}`,line:q(e.source,[...t.split(`.`),`default`])});return}return i}}function Db(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 ${jb(i)}`,line:q(e.source,[...t.split(`.`),r])});return}return i}}function Ob(e,t,n){let r=Db(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${dy(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:q(e.source,[...t.split(`.`),`palette`])});return}return r}}function kb(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 ${J(a)}`,line:q(e.source,[...t.split(`.`),r])});return}return a}}function Ab(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jb(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function J(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function Mb(e,t,n,r){return Ab(r)?(Ib(e,n,r,t.noun,new Set(Object.keys(t.fields)),Nb(e,t.removed??{},n,r)),Pb(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${jb(r)}`,line:q(e.source,n.split(`.`))}),null)}function Nb(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)Lb(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function Pb(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 Fb=new Set;function Ib(e,t,n,r,i,a=Fb){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:q(e.source,[...t.split(`.`),o])})}function Lb(e,t,n){return e.issues.push({path:t,message:n,line:q(e.source,t.split(`.`))}),null}function Rb(e,t,n,r){if(!Ab(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${jb(r)}`,line:q(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:q(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:q(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:q(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function zb(e,t,n,r){if(!Ab(r))return e.issues.push({path:n,message:`${n} must be an object, got ${jb(r)}`,line:q(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 ${jb(i)}`,line:q(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:q(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 Ib(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function Bb(e,t,n){return{json:ex(Qb(n),e,t),keys:new Set([e,...Object.keys(n)])}}function Vb(e){return(...t)=>e()(...t)}function Hb(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:q(n.source,o.split(`.`))}),null}return a}}function Ub(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Db(e,t,r,n)}}function Wb(){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 ${jb(i)}`,line:q(e.source,[n])});return}return i}}}}function Gb(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 ${J(o)}`,line:q(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 ${J(a)}`,line:q(e.source,[r])});return}return a}}}}function qb(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Ob(e,t,r)}}function Jb(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Eb(e,t,r,n)??void 0}}function Yb(e,t){return l(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function Xb(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=Eb(e,t,r,n);if(i===null)return;let a=Yb(`${t}.${n}`,i);return a===null?i:Lb(e,`${t}.${n}`,a)??void 0}}}function Zb(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>kb(t,n,i,r,e)}}function Qb(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 $b(e){return Qb(e.fields)}function ex(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function tx(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function nx(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const rx=[`claude`,`tmux`],ix=`ne .tmux.pane ""`,ax={band:{switch:{setting:`experimentalBand`,on:!0,inTmux:!1},label:`🧪 band (A)`,handsOff:!0,rows:null},statusline:{switch:{setting:`experimentalStatusline`,on:!0,inTmux:!1},label:`🧪 statusline (B)`,handsOff:!1,rows:null},pane:{switch:{setting:`experimentalPane`,on:!0,inTmux:!1},label:`🧪 tmux pane (C)`,handsOff:!0,rows:null},tmuxStatus:{switch:{setting:`renderer`,on:`tmux`,inTmux:!0},label:`tmux status line`,handsOff:!0,rows:5}},ox=Object.keys(ax),sx=ox.filter(e=>ax[e].switch.on===!0),cx={by:`request`},lx=e=>`drawing.${e}`,ux={subscribers:0,fps:0,shown:!0},dx=(e,t)=>`feeds.${e}.${t}`;function fx(e){return Object.fromEntries(ox.map(t=>[t,e(t)]))}const px=fx(()=>ux);function mx(e){return typeof e==`string`&&Object.hasOwn(ax,e)?e:null}const hx=(e,t)=>Array.from({length:e*2},(e,n)=>({lit:n%2==0,seconds:t})),gx=[...hx(3,1),...hx(3,.25)],_x=gx.reduce((e,{seconds:t})=>e+t,0),Ree={min:15,max:600,step:15},zee=(e,t)=>e+t,Bee=e=>e-_x,vx=(e,t,{previews:n=[],shown:r=`true`}={})=>({label:e,place:t,previews:n,shown:r}),yx=(e,t,n={})=>({spec:Zb(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e,...n}}}),bx=e=>t=>e.includes(t)?`🧪 ${t}`:t,xx={spec:Wb(),domain:`bool`,parse:Jy},Sx=e=>({spec:Gb(e),domain:e,parse:t=>Yy(t,e)});function Cx(e,t,n,r={}){return{kind:`session`,...yx(e,r.optionDomain,{library:r.library,labelOf:r.labelOf}),floor:t,control:n,themeDefault:r.themeDefault??!1}}function wx(e,t){return{kind:`session`,...xx,floor:e,control:t,themeDefault:!1}}function Tx(e,t,n){return{kind:`session`,...Sx(e),floor:t,control:n,themeDefault:!1}}function Ex(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const Dx=e=>({kind:`text`,spec:e}),Ox={required:!1,json:{enum:[...zy]},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: ${zy.join(`, `)}`,line:q(e.source,[...t.split(`.`),n])});return}return kb(e,t,r,n,zy)}},kx={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=Db(e,t,r,n);return by(i)?i:Ob(e,t,r)}},Ax={required:!1,json:{anyOf:[{enum:[...ky]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&by(i)?i:kb(e,t,r,n,ky)}},jx=/^[^\r\n]*\S[^\r\n]*$/u,Mx=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),Nx={required:!1,json:{type:`string`,pattern:jx.source,not:{pattern:Mx.source}},parse:(e,t,n,r)=>{let i=Db(e,t,r,n);if(i===void 0||jx.test(i)&&!Mx.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:q(e.source,[...t.split(`.`),n])})}},Px=Object.fromEntries(sx.map(e=>[ax[e].switch.setting,wx(!1,vx(ax[e].label,`toggles`))])),Fx={claude:`Claude Code's status line`,tmux:`the tmux status line, while this pane is shown`},Ix={groups:[{id:`renderer`,label:`draw the bar in`}],entry:e=>({group:`renderer`,description:Fx[e]})},Lx={palette:Ex(`theme`,kx,{themes:`themes`},vx(`🎨 theme`,`door`)),preset:Ex(`preset`,Ub(),{from:`presets`},vx(`▦ preset`,`door`,{previews:[`layout`,`presetDelete`]})),style:Ex(`style`,Ub(),{from:`styles`},vx(`◐ style`,`gear`,{previews:[`palette`]}),{themeDefault:!0}),effect:Ex(`effect`,Ax,{from:ky},vx(`✨ effect`,`look`)),endcaps:Cx(Iy,`powerline`,vx(`✦ endcaps`,`look`),{optionDomain:`endcaps`}),variation:Cx(Hy,`accent`,vx(`🎼 variation`,`gear`,{previews:[`layout`]}),{optionDomain:`variations`,labelOf:bx(uv),themeDefault:!0}),shade:Cx(Uy,`middle`,vx(`🔆 shade`,`gear`,{previews:[`layout`]}),{optionDomain:`shades`,labelOf:bx($_),themeDefault:!0}),transitions:wx(!1,vx(`fade in/out`,`look`)),animationSpeed:Cx(jy,`1x`,vx(`speed`,`look`)),autoWrap:wx(!0,vx(`wrap`,`config`)),padding:Tx({...qy,step:1},1,vx(`padding`,`config`)),updateNotice:wx(!0,vx(`update notice`,`config`)),menuTimeout:Tx(Ree,120,vx(`menu timeout`,`config`)),renderer:Cx(rx,`claude`,vx(`renderer`,`config`,{shown:ix}),{optionDomain:`renderers`,library:Ix}),...Px,colorCompatibility:{kind:`config`,...yx(zy,`colorCompatibilities`),spec:Ox,floor:`truecolor`},default_empty_value:Dx(Ub()),default_separator:Dx(Ub()),menuGlyph:Dx(Nx)},Rx=Object.entries(Lx),zx=Rx.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),Bx=Rx.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),Vx=Rx.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),Hx=Rx.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function Ux(e){return Lx[e]}const Wx=e=>Ux(e).floor;function Gx(e){let t=Lx[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const Kx=e=>`${e}.effective`,qx=e=>{let t=Lx[e];return t.kind===`selection`?t.sessionKey:e},Jx=Object.fromEntries(Bx.map(e=>{let t=qx(e);return[t,{configKey:e,sessionKey:t,effectiveVar:Kx(t),...Lx[e].control}]})),Yx=Object.keys(Jx),Xx=Object.values(Jx),Zx=zx.filter(e=>Lx[e].kind===`config`).map(e=>({configKey:e,effectiveVar:Kx(e)})),Vee=new Set(Zx.map(e=>e.configKey)),Qx=new Map([...Xx,...Zx].map(e=>[e.configKey,e.effectiveVar])),$x=new Map(Xx.map(e=>[e.sessionKey,e.effectiveVar]));function eS(e){return Object.fromEntries(Yx.map(t=>[t,e(t)]))}const tS=new Map(Yx.map(e=>[Jx[e].sessionKey,e])),nS=[[0,31],[127,159],[8234,8238],[8294,8303]];function rS(e){return nS.some(([t,n])=>e>=t&&e<=n)}function iS(e){let t=``;for(let n of e)t+=rS(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function aS(e,t){let n=iS(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const oS={fg:`#ffffff`,bg:`#c82828`},sS={fg:`#000000`,bg:`#dca028`};function cS(e,t){return`\x1b[${e};2;${[1,3,5].map(e=>Number.parseInt(t.slice(e,e+2),16)).join(`;`)}m`}const lS=cS(38,oS.fg),uS=cS(48,oS.bg),dS=new Gf({"strip.separator":`default`,"strip.rail":`default`});function fS(e){return dS.resolve(e)}const pS={kind:`still`},mS=e=>Wp.at(e.timeline,e.wall),hS=Symbol(`bar`);function gS(e){return e.name!==Ey}function _S(e){return t=>G.map(G.all(e.map(({timeline:e,effect:n})=>Wp.run(e,n(t)))),e=>(t,n)=>e.reduce((e,t)=>t(e,n),t))}const vS=tf;function yS(e,t){let n=new xu(t,vS.foregroundColor,vS.ansiColors,vS.palette);return t=>e({...t,theme:n})}function bS(e,t){return n=>Bh(()=>e(n),...t)(n)}function xS(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 SS=4096;function Hee(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=gx.reduceRight((e,{lit:t,seconds:n})=>G.sequence(G.constant(t?r:i),n,e),G.constant(i)),o=G.sequence(G.constant(i),n,a);return()=>o}var CS=class{inForce=null;anchor=Wp.play(0);placements=new Map;made=new Map;passages=null;frame={effect:Ey,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:Wp.withRate(this.anchor,e,t)}}motion(e,t,n,r=null){let i=mS(t),a=e=>Wp.seek(t.timeline,t.wall,e),o=this.inForce?.name===e?this.inForce:{name:e,since:i},s={scope:hS,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=a_.transitions[e]({z:xS(`${this.key}@${t}`)*SS});return{name:e,since:i,done:e=>r.done(e),effect:yS(r.effect,n)}},C=({since:e,done:t})=>t(i-e),ee=(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}),te=(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)}},w=(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?te(e,r):ee(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)},ne=(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}},T=(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=xS(t.scope===hS?e:`${e}@${t.scope}`),s=a?i.effect:a_.loops[t.name]({z:o*SS});return x[a?`reused`:`made`]++,n.set(t.scope,{name:t.name,effect:s}),s},re=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?s:ne(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()]},E=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:Bh(n.effect,...t)}]})},D=r===null?[]:[{timeline:Wp.play(r.idleSince),effect:Hee(r.fill,r.text,Bee(r.timeoutS))}],ie=e=>e===`menu`?D:[];return{placed:h===`off`?(e,t)=>t:w,row:(e,n,r)=>{let i=(r.some(e=>e.placement.effect!==`bar`)?re(r):[{...s,owners:void 0}]).filter(gS),o=E(r),c=ie(n);if(i.length===0&&o.length===0&&c.length===0)return pS;let l=`${this.key}#${e}`;return{kind:`moving`,time:t.wall,wrap:e=>new Ah(e,_S([...i.map(e=>{let t=T(l,e);return{timeline:a(e.t),effect:e.owners===void 0?t:bS(t,e.owners)}}),...o,...c]),{key:l,theme:vS})}},drawn:()=>{this.anchor=t.timeline,this.inForce=o,this.placements=l,this.made=d,this.passages=h===`off`?null:v,this.frame=x}}}},Uee=class{sessions=new Map;constructor(e=256){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new CS(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 Wee=`${uS}${lS}`;function wS(e){return`⚠ cc-candybar: ${TS(e)}`}function Gee(e){return`${Wee}${wS(e)}[0m\n`}function TS(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: ${aS(e.message,60)}`;case`render_failed`:return`render failed: ${aS(e.message,60)}`;case`switched_off`:return`switched off: ${aS(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${aS(e.message,60)}`}}function ES(e,t){return{depth:e.depth,rows:t,nextChange:1/0,motion:e.motion===`still`?`still`:`can-move`,pending:[]}}function DS(e,t){return{depth:`truecolor`,rows:[{kind:`diagnostic`,runs:[{text:iS(e),...t}]}],nextChange:1/0,motion:`still`,pending:[]}}function OS(e){return DS(wS({kind:`permanent`,cause:`render_failed`,message:e}),oS)}function kS(e,t){try{return e(t)}catch(t){return e(DS(`⚠ cc-candybar ${t instanceof Error?t.message:String(t)}`,oS))}}function AS(e){return e.type===V.TRUECOLOR?e.value.hex:e.number===void 0?e.name:`color(${e.number})`}const jS=Object.keys(new U().attributes);function MS(e,t){let{color:n,bgcolor:r}=e.drawnColors(t),i=jS.filter(t=>e[t]===!0);return{...n!==void 0&&{fg:AS(n)},...r!==void 0&&{bg:AS(r)},...i.length>0&&{attrs:i}}}function NS({text:e,style:t},n){return{text:e,...t!==void 0&&n!==null&&MS(t,n),...t?.link!==void 0&&{link:t.link}}}function PS(e,t){let n=e.filter(e=>!e.isControl&&e.text.length>0);return W.splitLines(n).map(e=>e.map(e=>NS(e,t)))}function FS({text:e,fg:t,bg:n,attrs:r=[],link:i}){return new W(e,new U({color:t,bgcolor:n,link:i,...Object.fromEntries(r.map(e=>[e,!0]))}))}function IS(e,t){let n=Ql(t);return e.map(e=>Eh(e.map(FS),n)).join(`
|
|
60
60
|
`)}function LS(e){return IS(e.rows.map(e=>e.runs),e.depth)}function RS(e){return LS(e)+`
|
|
61
|
-
`}const zS=(e,t)=>e.fg===t.fg&&e.bg===t.bg&&e.link===t.link&&e.attrs?.join()===t.attrs?.join();function BS({runs:e}){let t=[];for(let n of e){let e=t.at(-1);e!==void 0&&zS(e,n)?t[t.length-1]={...e,text:e.text+n.text}:t.push(n)}return t}function VS(e){return e.map(e=>e.text).join(``)}const HS={};function US(e,t){let n=Ql(t.colorSystem),{time:r}=t,i=1/0,a=[...gp(e,{maxWidth:t.width??80,isTerminal:!1,asciiOnly:!1,theme:fS,colorSystem:n.colorSystem,...r===void 0?{}:{frame:{time:r,host:HS}},onStyleError:e=>{throw e},onHold:({nextChange:e})=>{i=Math.min(i,e)}})];return{lines:PS(a,n.colorSystem),nextChange:Math.min(W.nextChange(a),i)}}const WS=new Map;function GS(e){let t=WS.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}=Ch.plain,a=new qm({glyph:n(r.glyph),ascii:r.ascii},i);return WS.set(e,a),a}function KS(e,t){return e===`plain`&&t!==void 0?GS(t):Ch[e]}const qS=new Map;function JS(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=qS.get(t);if(n!==void 0)return n;let r=KS(e.endcaps,e.separator),i=e=>new K(`x`,{end:``,overflow:`ignore`,style:new U({bgcolor:e})}),a=e=>{let{lines:t}=US(new xm(e,r),{colorSystem:null});return new K(VS(t.flat())).cellLength},o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return qS.set(t,s),s}function YS(e){return JS(e).chrome}function XS(e){return JS(e).seam}const ZS=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function QS(e){return[...new Set(e.match(ZS)??[])].join(``)}function $S(e){let t=KS(e.endcaps,e.separator),n=e=>new K(`x`,{end:``,style:new U({bgcolor:e})}),{lines:r}=US(new xm([n(`#101010`),n(`#202020`)],t),{colorSystem:null});return QS(VS(r.flat()))}function eC(e){return e.wrap?e.width:1/0}function tC(e,t){return US(new K(e,{overflow:`fold`,end:``}),{colorSystem:null,width:t}).lines.map(VS)}function nC(e,t,n=mS){if(e.length===0)return{lines:[[]],nextChange:1/0};let r=KS(t.endcaps,t.separator),i=Number.isFinite(eC(t)),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new R_([...e],{joiner:r}):new xm([...e],r),s=n.kind===`still`?US(o,a):US(n.wrap(o),{...a,time:n.time});if(s.lines.length===0)throw Error(`drawStripCells: rich-js strip drew no line`);return s}function rC(e,t){return IS(nC(e,t).lines,t.colorCompatibility)}const iC={level:`error`,glyph:`⚠`,colors:sS},aC={level:`warning`,glyph:`⚠`,colors:cS},oC={level:`warning`,glyph:`⬆`,colors:cS},sC={level:`warning`,glyph:`🔒`,colors:cS},cC={level:`warning`,glyph:`🧪`,colors:cS};function lC(e,t){return{text:aS(e),link:t}}function uC(e,t,n,r,i){let a=new Set,o=(e,t)=>{let n=dC(e,t);for(let e of n)a.add(e);return n},s=[...n.flatMap(e=>o(e,iC)),...r,...i.flatMap(e=>o(e,aC))],c=fC(s);return s.map((n,r)=>a.has(n)?{...n,lines:[[lC(n.lines[0][0].text,pC(e,t,c[r],r+1))],...n.lines.slice(1)]}:n)}function dC({about:e,text:t,copy:n},r){let[i,...a]=t.split(/\r\n|\r|\n/).map(e=>lC(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 fC(e){return _C(e).map(e=>String(e*hC+1))}function pC(e,t,n,r){return Ea([{verb:ha,args:[e,t,n]}],`copy diagnostic ${r}`)}function mC(e){return e.length===0?null:e.some(e=>e.severity.level===`error`)?`error`:`warning`}const hC=4096;function gC(e){let t=w(`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 _C(e){let t=new Map;return e.map(e=>{let n=gC(e),r=t.get(n)??0;return t.set(n,r+1),n*256+Math.min(r,255)})}function vC(e,t,n){return String(_C(e)[t]*hC+n+1)}const yC={error:sS,warning:cS};function bC(e){let t=mC(e),n=e.length,r=yC[t??`warning`];return{label:t===null?``:`⚠ ${n>9?`9+`:n}`,fg:r.fg,bg:r.bg,open:e.length===0?`0`:vC(e,0,0)}}function xC(e,t){let n=Number(e)-1,r=_C(t).indexOf(Math.floor(n/hC));return e===null||r===-1?null:{index:r+1,page:n%hC}}function SC(e,t){return Math.min(20,e??20,...t)}function CC(e,t,n,r,i){let{index:a}=t,o=e[a-1],s=EC(i),c=kC(o,s,[]),l=new U({bgcolor:o.severity.colors.bg,color:o.severity.colors.fg}),u=(e,t)=>DC(e,t===null?l:l.withLink(t)),d=(t,r)=>r===null?u(` `,null):u(t,TC(n,vC(e,r.index-1,r.page),`show diagnostic ${r.index} of ${e.length} page ${r.page+1}`)),f=(t,i)=>{let o=i>0?{index:a,page:i-1}:a>1?{index:a-1,page:0}:null,c=i<t-1?{index:a,page:i+1}:a<e.length?{index:a+1,page:0}:null,l=e.length>1||t>1,f=t>1?`[${a}/${e.length} ${i+1}/${t}]`:`[${a}/${e.length}]`;return OC([u(`✕`,TC(n,`0`)),...l?[d(`‹`,o)]:[],u(f,null),...l?[d(`›`,c)]:[],u(`⧉ copy`,pC(n,r,vC(e,a-1,0),a))],s)},p=1;for(;;){let e=Math.max(1,i.rows-p),n=Math.min(hC,Math.ceil(c.length/e)),r=Math.min(t.page,n-1),a=f(n,r);if(a.length>p){p=a.length;continue}let o=c.slice(r*e,(r+1)*e),l=c.length-(r+1)*e,d=r===n-1&&l>0?[...o.slice(0,-1),...OC([u(`… ${l+1} more rows: ⧉ copy has them all`,null)],{...s,wrap:!1})]:o;return[...a,...d]}}function wC(e,t,n,r){let{label:i,fg:a,bg:o,open:s}=bC(t),c=i===``?[]:[DC(i,new U({bgcolor:o,color:a}).withLink(TC(n,s)))];return kC(e,EC(r),c)}function TC(e,t,n){return Ea([{verb:Wi,args:[e,Vi,t]}],n)}function EC(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,colorCompatibility:e.colorCompatibility}}const DC=(e,t)=>new K(`${e} `,{style:t,end:``,overflow:`ignore`}),OC=(e,t)=>nC(e,t).lines.map(e=>({kind:`diagnostic`,runs:e}));function kC(e,t,n){let r=new U({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),i=e=>e===null?r:r.withLink(e),a=bl(Math.max(2,t.width-1));return e.lines.flatMap((o,s)=>{let c=DC(s===0?e.severity.glyph:` `,r),l=o.flatMap(e=>e.text.split(` `).flatMap(e=>Tl(e,a)).map(t=>DC(t,i(e.link)))),u=s===0?n:[];return OC([c,...l,...u],t)})}function AC(e,t){let n=w(`sha256`).update(t).digest(`hex`).slice(0,16);return o.join(e,`update-act`,n)}const jC={kind:`idle`};function MC(e){if(e===null)return jC;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 NC=e=>({stdout:o.join(e,`stdout`),stderr:o.join(e,`stderr`),status:o.join(e,`status`)}),PC=e=>o.join(e,`record.json`);function FC(e){let t;try{t=f.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 IC(e){let t=qo(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 LC(e,t){let n=o.join(e,`.removed-${t}-${process.pid}`);try{f.renameSync(o.join(e,String(t)),n)}catch(e){if(e.code===`ENOENT`)return;throw e}f.rmSync(n,{recursive:!0,force:!0})}const RC=()=>Date.now()-D.uptime()*1e3;async function zC(e,t,n=RC()){if(e.started<=n||!Un(e.pid))return!1;let r=await t(e.pid);return e.startTime===null||r.kind===`unavailable`||r.token===e.startTime}function BC(e){try{return JSON.parse(f.readFileSync(PC(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}const VC=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function HC(e,t){let n=null;async function r(r){let i=o.join(e,String(r)),a=BC(i);if(a===null)return null;if((n===null||!VC(n.record,a))&&(n={record:a,ours:await zC(a,t),final:null}),n.final!==null)return n.final;n.ours=n.ours&&Un(a.pid);let s=NC(i),c=Vn(s.status),l=c===null?null:IC(s.stderr)??IC(s.stdout);if(!f.existsSync(i))return null;let u={act:r,record:a,alive:n.ours,end:c,lastLine:l};return u.alive||(n.final=u),u}return{async read(){let t=null;for(;;){let n=FC(e).at(-1);if(n===void 0)return null;if(n===t)throw Error(`${o.join(e,String(n))}: an act with no record`);let i=await r(n);if(i!==null)return i;t=n}}}}function UC(e,t,n){f.mkdirSync(e,{recursive:!0});let r=f.mkdtempSync(o.join(e,`.claim-`));try{return f.writeFileSync(PC(r),JSON.stringify(n)),f.renameSync(r,t),!0}catch(e){let t=e.code;if(t===`ENOTEMPTY`||t===`EEXIST`)return!1;throw e}finally{f.rmSync(r,{recursive:!0,force:!0})}}async function WC(e,t,n,r,i,a,s,c){let l=(n??0)+1,u=o.join(t,String(l)),d=e.launchJobSync(i,NC(u));if(!d.ok)throw Error(`apply-update: ${d.error}`);let f=!1;try{let e=await c(d.pid);if(!UC(t,u,{identity:r,pid:d.pid,startTime:e.kind===`start`?e.token:null,started:s,deadline:s+a}))return GC;if(FC(t).some(e=>e>l))return LC(t,l),GC;f=!0}finally{f?d.release():d.withdraw()}for(let e of FC(t).filter(e=>e<l))LC(t,e);return{ok:!0,act:l}}const GC={ok:!1,reason:`another act claimed this bundle first`};function KC(e,t){let n=NC(o.join(e,String(t.act))).status;return Gn(t.record.pid,n,{kind:`timeout`})}var qC=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)})}},Y=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}},JC=class extends Error{constructor(e){super(`the daemon closed: ${e} refused`),this.name=`DaemonClosing`}},YC=class extends Error{constructor(e){super(`the client left: ${e} not run`),this.name=`ClickAbandoned`}};function XC(e){try{return e()}catch(e){throw e instanceof URIError?new Y(`malformed wire encoding: ${e.message}`):e}}const ZC=new Map;function QC(e){let t=ew(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 $C(e,t){return e===`bar`?t:QC(e)}function ew(e){let t=ZC.get(e);if(t!==void 0)return t;let n=Jd(e);return n===null?null:(ZC.set(e,n),n)}function tw(e,t){return nw(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>sf(e,t))}const nw=z_();function rw(e){let t=ew(e);return t===null?null:{kind:`decided`,name:e,value:t}}function iw(e,t,n){let r=rw(e);return r===null?(n(Oy(t,`palette`,`"${e}" names no installed theme${dy(e)}`)),ow()):r}function aw(e,t,n){return xy(e,t,n,ow(),rw)}function ow(){return{kind:`decided`,name:fy,value:QC(fy)}}const sw=/^[A-Za-z_][A-Za-z0-9_]*$/;function cw(e){return`#${e+1}`}const lw={rows:{}};function uw(e){return`rows`in e}function dw(e){return Object.fromEntries(e.map((e,t)=>[cw(t),e]))}function fw(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:dw(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:dw([n])}}function pw(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function mw(e){return uw(e)?pw(e):e}function*hw(e,t){if(!uw(e)){yield*ab(e,t);return}yield[pw(e),t];for(let[n,r]of Object.entries(e.rows))yield*ab(r,`${t}.rows.${n}`)}function gw(e,t){return uw(e)?{...t,...e,rows:{...t.rows,...e.rows}}:fw(e)}function _w(e,t){return t.reduce((e,t)=>{let n=t.id??t.seg,r=[...nb(pw(e.root))].flatMap(e=>e.kind===`segment`?[e]:[]);if(r.some(e=>e.name===t.seg&&(t.id===void 0||Qy(e)===t.id)))return e;let i=r.find(e=>Qy(e)===n);if(i!==void 0)return vw(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,yw(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]))}}:vw(e,t,`${t.relation} "${t.anchor}", but there is no placement "${t.anchor}"`)},{root:e,unplaced:[]})}function vw(e,t,n){return{...e,unplaced:[...e.unplaced,{cell:t,reason:n}]}}function yw(e,t,n,r){if(e.kind===`segment`&&Qy(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`?bw(e,t,n,r):xw(e,t,n,r)}function bw(e,t,n,r){let i=e.children.findIndex(e=>e.kind===`segment`&&Qy(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`?bw(a,t,n,r):xw(a,t,n,r);if(o!==null)return{...e,children:e.children.map((e,t)=>t===i?o:e)}}return null}function xw(e,t,n,r){let i=!1,a=tb(e,e=>{let a=bw(e,t,n,r);return i=a!==null,a??e});return i?a:null}function Sw(e){if(!uw(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const Cw=`default`,ww={};function Tw(e){return[...new Set([Cw,...Object.keys(e)])]}function Ew(e,t,n){return vy(void 0,e,t,Cw,n)}function Dw(e,t){let n={[Cw]:ww,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${Cw}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function Ow(e,t){let n=Dw(e.presets,t).root??lw;return{node:pw(gw(n,e.root)),path:Sw(n)?`presets.${t}.root`:`root`}}function kw(e,t,n){if(t.length===0)return{config:e,notices:[]};let r=_w(e.root,t),i=Object.entries(e.presets).filter(([,e])=>Sw(e.root??lw)).map(([n,r])=>({name:n,preset:r,..._w(gw(r.root??lw,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:pw(n)}]))}},notices:[...a].flatMap(([e,t])=>[...t].map(([t,n])=>Aw(e,`${t} (in ${n.join(`, `)})`)))}}function Aw(e,t){return`${e.by.file}: ${e.by.entry} places "${e.seg}" ${t}`}function jw(e,t){return{...e.globals,...Dw(e.presets,t).globals}}const Mw=new Map;function Nw(e,t,n={}){Mw.set(e,{permanent:!0,resolve:t,...n})}Nw(`themes`,()=>my(),{paletteOf:e=>QC(e)});const Pw=`placementThemes`;Nw(Pw,hy,{paletteOf:(e,t)=>$C(e,t.palette)});for(let{name:e,members:t,library:n,labelOf:r}of Hx)Nw(e,()=>t,{library:n,labelOf:r});function Fw(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>tw(n.basePalette,e.styles[t])}],[`presets`,{members:Tw(e.presets)}]])}function Iw(e){return[...new Set([...Mw.keys(),...e.keys()])]}function Lw(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=Mw.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf,library:r.library,labelOf:r.labelOf};throw Error(zw(e,t))}const Rw=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function zw(e,t){let n=Rw.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${Iw(t).join(`, `)})`}const Bw=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`slash`,`run`,`do`];function Vw(e){return JSON.stringify([e.run,Object.entries(e.env),e.cwd,e.refreshes])}function*Hw(e){let t=[];Uw(e,(e,n)=>(t.push([n,e]),e)),yield*t}function Uw(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 Ww(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}const Gw=[`plugins`,`repo`];function Kw({scope:e,name:t}){return`${e}.${t}`}function qw(e){return t=>t===e||t.startsWith(`${e}.`)}const Jw=`self`;function Yw(e){return Gw.find(t=>e===t||e.startsWith(`${t}.`))}function Xw(e,t){let n=Yw(e);if(n===void 0||n===e)return``;let r=Gw.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 Zw=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*Qw(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 $w=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,eT=RegExp(`^(?:(\\$)(?:\\.(${$w}))?|\\.(${$w})?)(?=[\\s)]|$)`);function tT(e,t,n){let r=eT.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 nT=/^(\w+)\b\s*([\s\S]*)$/;function*rT(e,t){let n=[t];for(let r of Qw(e)){let e=r.text.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=nT.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:tT(i[1],s,t);continue}yield{code:e,dot:o,block:r},i===`if`&&n.push(o),i===`with`&&n.push(tT(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const Kee=/(?<![.$])\btemplate\s+$/;function*iT(e,t,n){let r=0;for(let i of[...e.matchAll(Zw)]){let a=i.index+i[0].length;Kee.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:tT(e.slice(a),t,n),index:i.index}),r=a}}function*qee(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...rT(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...iT(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 aT(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const oT=new WeakMap;function sT(e,t){let n=oT.get(t);return n===void 0&&(n=aT(e=>[...qee(e,t)]),oT.set(t,n)),n(e)}const Jee=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${$w})`,`g`);function*Yee({code:e,dot:t,root:n}){let r=e.replace(Zw,``);for(let e of[...r.matchAll(Jee)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function cT(e,t){let n=new Map;for(let r of sT(e,t))for(let e of Yee(r))n.has(e)||n.set(e,r.via);return n}const Xee=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,lT={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*uT(e){let t=0,n=0,r=`action`;for(let i of[...e.matchAll(Zw)]){let a=e.slice(t,i.index),o=Xee.exec(a);o===null?a.trim()!==``&&(n=0):(n=lT[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 dT(e,t){let n=new Map;for(let{code:r,via:i}of sT(e,t))for(let{name:e,site:t}of uT(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}const fT=e=>Object.keys(lT).filter(t=>lT[t]>=e).join(`|`),Zee=RegExp(`(?<![\\w.$])(?:(?:${fT(1)})\\s+|(?:${fT(2)})\\s+""\\s+)(?=[^\\s"\`)|}])`);function Qee(e,t){for(let{code:n}of sT(e,t))if(Zee.test(n.replace(Zw,`""`)))return!0;return!1}const $ee=/(?<![\w.$])[A-Za-z_]\w*/g;function ete(e,t){let n=new Set;for(let{code:r}of sT(e,t))for(let[e]of r.replace(Zw,``).matchAll($ee))n.add(e);return n}function tte(e,t){return new Set([...pT(e,t)].filter(e=>Object.hasOwn(t,e)))}function pT(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of sT(e,t))for(let{name:e}of iT(r,i,a))n.add(e);return n}const nte=e=>RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.${e}(?![A-Za-z0-9_])`,`g`);function rte(e,t,n){let r=nte(t),i=qw(t),a=[];for(let{dot:t,block:n}of rT(e,``)){let e=n.text.replace(Zw,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[...iT(n.text,t,``),...uT(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*mT(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*hT(e){for(let[t,n]of mT(e))yield[t,n]}function gT(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 _T(e,t){return gT(e,t.names).some(n=>!e.startsWith(`${n}.`)||t.documents.has(n))}function vT(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),ite(r)&&n.add(e)};for(let[t,n]of hT(e))r(t,n);return{names:t,documents:n,helpers:e.helpers}}function ite(e){return e.kind===`dropped`||e.kind===`source`||(e.kind===`shell`||e.kind===`file`)&&sb(e.parse)===`json`}function yT(e){let t=o.basename(e),n=o.dirname(e);for(;;){let r=bT(n);if(r!==null)return{dir:r,name:t,leaf:n===o.dirname(e)};t=o.basename(n),n=o.dirname(n)}}function bT(e){try{return f.statSync(e).isDirectory()?f.realpathSync(e):null}catch{return null}}const ate=(e,t)=>k(t);function xT(e){let t=[],n=!0,r=new Map;for(let i of e.named){let{hops:e,stopped:a}=ut(i);a!==null&&t.push({path:i,reason:a.message});for(let t of e){let{dir:e,name:i,leaf:a}=yT(t);n&&=a;let o=r.has(e)?r.get(e):new Set;o?.add(i),r.set(e,o)}}for(let t of e.whole.map(bT))t!==null&&r.set(t,null);let i={dirs:[...r.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})},a=new Map(i.dirs.map(e=>{let t=Yc(e.path);return[e.path,Zc(t)?Xc(t):null]}));return{key:JSON.stringify([i,[...a]]),targets:i,unbound:[...a.values()].includes(null),bound:a,reached:n,unresolved:t}}function ST(e,t,n){let r=[...t.derived.unresolved.map(e=>`cannot follow a link chain — ${e.reason}`),...t.held.handle.deaf.map(e=>e.kind===`refused`?`cannot watch ${e.path} — ${e.reason}`:`watching ${e.path} failed — ${e.reason}`),...n===null?[]:[n]];return r.length===0?null:`${e}: ${r.join(`; `)}`}function CT(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 wT=(e,t)=>t===null?{kind:`unknown`}:{kind:`changed`,paths:new Set([o.join(e,t)])},TT=e=>({kind:`failed`,reason:`${e.path}: ${e.reason}`}),ET=(e,t)=>e.kind===`listening`&&e.handle===t,DT=e=>`${e.recursive===!0?`tree`:`dir`}:${e.path}`;var OT=class{slots=new Map;dirs=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??ate}acquire(e,t,n){if(this.closed)return{release:()=>{},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)}return this.slots.set(e,n),this.counters&&(n.listeners.every(e=>e.dir.state.kind===`listening`)?this.counters.watchersOpened++:this.counters.watchRefusals++),n}dirFor(e){let t=DT(e),n=this.dirs.get(t);if(n!==void 0)return this.judged(n,`acquire`),n;let r={path:e.path,recursive:e.recursive===!0},i={id:t,...r,listeners:new Set,state:this.open(r,()=>i,`acquire`,null)};return this.dirs.set(t,i),i}judged(e,t){if(e.state.kind===`deaf`){this.reopen(e,t);return}let n=Yc(e.path);Zc(n)&&Xc(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),e.state.kind===`listening`?this.tell(e,{kind:`unknown`}):n.kind===`listening`&&this.tell(e,TT(e.state.deafness))}open(e,t,n,r){let i=e.path,a=Xc(Yc(i));try{f.opendirSync(i).closeSync();let r=f.watch(i,{persistent:!1,recursive:e.recursive},(e,n)=>this.heard(t(),r,n));return r.on(`error`,e=>{this.logger(`warn`,`watcher error ${i}: ${e.message}`),this.counters&&this.counters.watchErrors++;let n=t();if(!ET(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,TT(a))}),this.counters&&this.counters.dirWatchesOpened++,this.logger(`info`,`dir watch opened path=${R(i)} cause=${R(n)}`),{kind:`listening`,handle:r,bound:a}}catch(e){let t=e.message;return r?.kind===`deaf`&&r.deafness.kind===`refused`&&r.deafness.reason===t||this.logger(`warn`,`watch failed ${i}: ${t}`),{kind:`deaf`,deafness:{kind:`refused`,path:i,reason:t}}}}heard(e,t,n){let{state:r}=e;if(!ET(r,t))return;let i=n===o.basename(e.path)&&Xc(Yc(e.path))!==r.bound;for(let{slot:t,filter:r}of e.listeners)(r===null||n===null||r.has(n)||i)&&this.fire(t,wT(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=CT(e.debounce.window,t);return}let n={window:t,timer:setTimeout(()=>{e.debounce=null;for(let t of e.holders)try{t.onInvalidate(n.window)}catch(t){this.logger(`warn`,`watcher invalidate threw key=${R(e.key)}: ${t.message}`)}},50)};n.timer.unref(),e.debounce=n}makeHandle(e,t){return{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=${R(e)} cause=${R(n)}`)}closeSlot(e,t){e.debounce!==null&&(clearTimeout(e.debounce.timer),e.debounce=null);for(let n of e.listeners){let{dir:e}=n;e.listeners.delete(n),!(e.listeners.size>0)&&(e.state.kind===`listening`&&this.closeHandle(e.path,e.state.handle,t),this.dirs.delete(e.id))}this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}dirWatches(){return[...this.dirs.values()].filter(e=>e.state.kind===`listening`).length}watchedDirs(){return[...this.dirs.values()].map(e=>e.path)}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e,`close`);this.slots.clear()}},kT=Ae((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()===Vt}function s(e){let t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function c(e,t,n){Lt(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 Rt.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=Ht,n=Ht){let r=new Gt(e);return t!==Ht&&(r.onBOL=new Set([t])),n!==Ht&&(r.onBUOL=new Set([n])),r}function _(e,t){return At(e,t)}function v(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||$e(e)?e:Array.isArray(e)?cn.array(e,{name:n}):o(e)?cn.object(e,void 0,{name:n}):u(e)?cn.map(e,{name:n}):d(e)?cn.set(e,{name:n}):typeof e!=`function`||He(e)||Xe(e)?e:s(e)?Kn(e):Rn(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:He(n.value)?1:(Lt(r,t,ee(e,this,t,n,!1)),2)}function S(e,t,n,r){let i=ee(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 _e(s.i?.name??a.toString(),e,(t=s.i?.autoAction)!=null&&t)};return i==`field`?function(e){var t;let n=e;return He(n)||(n=c(n)),(t=s.i)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n}:i==`method`?(He(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 ee(e,t,n,r,i=M.safeDescriptors){var a,o,s;let{value:c}=r;return(a=t.i)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:_e(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 te(e,t){return{t:e,i:t,o:w,u:ne}}function w(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)||!Xe(e.h[t]))&&this.u(e,t,n,!1)===null?0:Xe(n.value)?1:(Lt(r,t,re(e,0,0,n,!1,!1)),2)}function ne(e,t,n,r){let i=re(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function T(e,t,n){var r;let{name:i,addInitializer:a}=n;return Xe(t)||(t=Kn(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 re(e,t,n,r,i,a=M.safeDescriptors){let{value:o}=r;return Xe(o)||(o=Kn(o)),i&&(o=o.bind(e.v??e.h),o.isMobXFlow=!0),{value:o,configurable:!a||e.p,enumerable:!1,writable:!a}}function E(e,t){return{t:e,i:t,o:D,u:ie}}function D(e,t,n){return this.u(e,t,n,!1)===null?0:1}function ie(e,t,n,r){return e.m(t,Ft({},this.i,{get:n.get,set:n.set}),r)}function O(e,t,n){function r(e){let n=Ft({},i.i,{get:t,context:e});return n.name||=`ObservableObject.${a.toString()}`,new bn(n)}let i=e,{name:a,addInitializer:o}=n,s;return o(function(){let e=Ct(this)[A],n=this,i=e.j.get(a);i instanceof bn&&i.derivation!==t&&e.j.delete(a),(e.O??=new Map).set(a,()=>r(n))}),function(){let e=this[A],n=e.j.get(a);if(n instanceof bn&&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 ae(e,t){return{t:e,i:t,o:oe,u:se}}function oe(e,t,n){return this.u(e,t,n,!1)===null?0:1}function se(e,t,n,r){return e.S(t,n.value,this.i?.A??v,r)}function ce(e,t,n){function r(e,t){let n=Ct(e)[A];return(n.V??=new Map).set(o,()=>new vn(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[A]??r(this,t.get.call(this)))._(o)},set(e){return(this[A]??r(this,e)).M(o,e)},init(e){return r(this,e),e}}}function le(e){return{t:Yt,i:e,o:ue,u:de}}function ue(e,t,n,r){var i,a,o;if(n.get)return fn.o(e,t,n,r);if(n.set){let i=He(n.set)?n.set:_e(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!M.safeDescriptors||e.p,set:i})===null?0:2:(Lt(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?qn:Kn).o(e,t,n,r):((a=this.i)!=null&&a.autoBind?Bn:Rn).o(e,t,n,r);let c=!1===this.i?.deep?rn:cn;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 de(e,t,n,r){var i;return n.get?fn.u(e,t,n,r):n.set?e.l(t,{configurable:!M.safeDescriptors||e.p,set:_e(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?rn:cn).u(e,t,n,r))}function fe(e,t){return Ft(function(n,r){if(r&&typeof r.kind==`string`)return t(e,n,r)},e)}function pe(e){return e||Zt}function me(e){return fe(e,ce)}function he(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 ge(e){return fe(e,O)}function _e(e,t,n=!1,r){function i(){return ve(0,n,t,r||this,arguments)}return i.isMobxAction=!0,i.toString=()=>t.toString(),gn&&(_n.value=e,Lt(i,`name`,_n)),i}function ve(e,t,n,r,i){let a=ye(0,t);try{return n.apply(r,i)}catch(e){throw a.N=e,e}finally{be(a)}}function ye(e,t){let n=M.trackingDerivation,r=!t||!n;Ne();let i=M.allowStateChanges;r&&De();let a={R:r,k:n,C:i,I:M.allowStateReads,P:!1,T:0,B:hn++,D:mn};return mn=a.B,a}function be(e){mn!==e.B&&t(30),mn=e.D,e.N!==void 0&&(M.suppressReactionErrors=!0),Pe(),e.R&&Oe(e.k),M.suppressReactionErrors=!1}function xe(e,t){let n=function(e){let t=M.allowStateChanges;return M.allowStateChanges=e,t}(e);try{return t()}finally{(function(e){M.allowStateChanges=e})(n)}}function Se(e){return e instanceof Sn}function Ce(e){switch(e.K){case 0:return!1;case-1:case 2:return!0;case 1:{let t=De(),n=e.L,r=n.length;for(let i=0;i<r;i++){let r=n[i];if(xn(r)){if(M.disableErrorBoundaries)r.get();else try{r.get()}catch{return Oe(t),!0}if(e.K===2)return Oe(t),!0}}return ke(e),Oe(t),!1}}}function we(e,t,n){ke(e),e.$=Array(e.U===0?100:e.L.length),e.W=0,e.U=++M.runId;let r=M.trackingDerivation,i;if(M.trackingDerivation=e,M.inBatch++,!0===M.disableErrorBoundaries)i=t.call(n);else try{i=t.call(n)}catch(e){i=new Sn(e)}return M.inBatch--,M.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&&je(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,Ae(t,e))}r!==0&&(e.K=r,e.q())}(e),i}function Te(e){let t=e.L;e.L=[];let n=t.length;for(;n--;)je(t[n],e);e.K=-1}function Ee(e){let t=De();try{return e()}finally{Oe(t)}}function De(){let e=M.trackingDerivation;return M.trackingDerivation=null,e}function Oe(e){M.trackingDerivation=e}function ke(e){if(e.K===0)return;e.K=0;let t=e.L,n=t.length;for(;n--;)t[n].F=0}function Ae(e,t){(e.H??=new Set).add(t),e.F>t.K&&(e.F=t.K)}function je(e,t){let n=e.H;n&&(n.delete(t),n.size===0&&Me(e))}function Me(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,M.pendingUnobservations.push(e))}function Ne(){M.inBatch++}function Pe(){--M.inBatch===0&&(Le(),!M.isRunningUnobservations&&M.pendingUnobservations.length>0&&function(){M.isRunningUnobservations=!0;try{let e=M.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 bn&&n.G())}M.pendingUnobservations=[]}finally{M.isRunningUnobservations=!1}}())}function k(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.L)==null||t.forEach(k))}function Fe(e){let t=M.trackingDerivation;return t===null?((!e.H||e.H.size===0)&&M.inBatch>0&&Me(e),!1):(t.U!==e.J&&(e.J=t.U,t.$[t.W++]=e,!e.isBeingObserved&&M.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function Ie(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 Le(){M.inBatch>0||M.isRunningReactions||kn(Re)}function Re(){M.isRunningReactions=!0;let e=M.pendingReactions,t=0;for(;e.length>0;){++t===On&&(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()}M.isRunningReactions=!1}function ze(e){return fe(e,C)}function Be(e){return function(t,n){return n&&typeof n.kind==`string`?C(e?Fn:Nn,t,n):r(t)?_e(t.name||`<unnamed action>`,t,e):r(n)?_e(t,n,e):i(t)?ze(b(e?Mn:jn,{name:t,autoAction:e})):void 0}}function Ve(e){return ve(0,!1,e,this,void 0)}function He(e){return r(e)&&!0===e.isMobxAction}function Ue(e,t=Bt){function n(){e(a)}var r;let i=t?.name??`Autorun`,a;if(t.scheduler||t.delay){let e=We(t),r=!1;a=new Dn(i,()=>{r||(r=!0,e(()=>{r=!1,a.isDisposed||a.track(n)}))},t.onError,t.requiresObservable)}else a=new Dn(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 We(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Vn}function Ge(e,t,n,i){let a=typeof i==`function`?Et(t,n):Et(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 Ke(e,t,n,r){let i=Wt(t);return kt(()=>{let t=Ct(e,r)[A];Ut(i).forEach(e=>{t.u(e,i[e],!n||!(e in n)||n[e])})}),e}function qe(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(qe)),t}function Je(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),Je)),t}function Ye(e){r(e.cancel)&&e.cancel()}function Xe(e){return!0===e?.isMobXFlow}function Ze(e,t){var n;if(t===void 0)return xn(e);if(!1===Tt(e))return!1;let r=e[A];return(n=r.O)!=null&&n.has(t)?!0:r.j.has(t)?xn(Et(e,t)):!1}function Qe(e,t){if(!e)return!1;if(t!==void 0){if(Tt(e)){var n,r;let i=e[A];return i.j.has(t)||!((n=i.O)==null||!n.has(t))||!((r=i.V)==null||!r.has(t))}return!1}return Tt(e)||!!e[A]||Kt(e)||An(e)||xn(e)}function $e(e){return Qe(e)}function et(e){return Tt(e)?e[A].nt():ar(e)||cr(e)?Array.from(e.keys()):bt(e)?e.map((e,t)=>t):void t(5)}function tt(e,n){return Tt(e)?e[A].et(n):ar(e)||cr(e)?e.has(n):bt(e)?n>=0&&n<e.length:void t(10)}function nt(e){if(Tt(e))return e[A].it();t(38)}function rt(e,t,n){if(xn(e)){let r,i=!0;return Ue(()=>{let a=e.get();if(!i||n){let n=De();t({observableKind:`computed`,debugObjectName:e.tt,type:Zn,object:e,newValue:a,oldValue:r}),Oe(n)}i=!1,r=a})}return n&&t({observableKind:`value`,debugObjectName:e.tt,object:e,type:Zn,newValue:e.rt,oldValue:void 0}),pt(e,t)}function it(e,t,n){return e.set(t,n),n}function at(e,t){if(typeof e!=`object`||!e||e instanceof Date||!$e(e))return e;if(yn(e)||xn(e))return at(e.get(),t);if(t.has(e))return t.get(e);if(bt(e)){let n=it(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=at(e,t)}),n}if(cr(e)){let n=it(t,e,new Set);return e.forEach(e=>{n.add(at(e,t))}),n}if(ar(e)){let n=it(t,e,new Map);return e.forEach((e,r)=>{n.set(r,at(e,t))}),n}{let n=it(t,e,{});return nt(e).forEach(r=>{Rt.propertyIsEnumerable.call(e,r)&&(n[r]=at(e[r],t))}),n}}function ot(e,t){Ne();try{return e.apply(t)}finally{Pe()}}function st(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)throw e;n.onError(e)}},n.timeout)}n.name=`When`;let i=_e(`When-effect`,t);var a=Ue(t=>{xe(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function ct(e){return e[A]}function lt(e){return e.st!==void 0&&e.st.length>0}function ut(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 dt(e,n){let r=De();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{Oe(r)}}function ft(e){return e.ot!==void 0&&e.ot.length>0}function pt(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 mt(e,t){let n=De(),r=e.ot;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Oe(n)}}function ht(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!==Rt;){let t=It(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 gt(e,t){typeof Array.prototype[e]==`function`&&(er[e]=t(e))}function _t(e){return function(){let t=this[A];t.ct.reportObserved();let n=t.ht(t.j);return n[e].apply(n,arguments)}}function vt(e){return function(t,n){let r=this[A];return r.ct.reportObserved(),r.ht(r.j)[e]((e,r)=>t.call(n,e,r,this))}}function yt(e){return function(){let t=this[A];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 bt(e){return a(e)&&tr(e[A])}function xt(e){return e[Symbol.toStringTag]=`MapIterator`,Nt(e)}function St(e){return e[Symbol.toStringTag]=`SetIterator`,Nt(e)}function Ct(e,t){if(p(e,A))return e;let n=t?.name??`ObservableObject`;return c(e,A,new dr(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 j[r]??(j[r]=le({deep:t,autoBind:n}))}(e):void 0}(t))),e}function wt(e){return lr[e]||(lr[e]={get(){return this[A]._(e)},set(t){return this[A].M(e,t)}})}function Tt(e){return!!a(e)&&fr(e[A])}function Et(e,n){if(typeof e==`object`&&e){if(bt(e))return n!==void 0&&t(23),e[A].ct;if(cr(e))return e.ct;if(ar(e)){if(n===void 0)return e.lt;let r=e.ft.get(n)||e.dt.get(n);return r||t(25,n,Ot(e)),r}if(Tt(e)){if(!n)return t(26);let r=e[A],i=r.j.get(n)??r.vt(n)??r.bt(n);return i||t(27,n,Ot(e)),i}if(Kt(e)||xn(e)||An(e))return e}else if(r(e)&&An(e[A]))return e[A];t(28)}function Dt(e,n){return e||t(29),n===void 0?Kt(e)||xn(e)||An(e)||ar(e)||cr(e)?e:e[A]?e[A]:void t(24,e):Dt(Et(e,n))}function Ot(e,t){let n;if(t!==void 0)n=Et(e,t);else{if(He(e))return e.name;n=Tt(e)||ar(e)||cr(e)?Dt(e):Et(e)}return n.tt}function kt(e){let t=De();Ne();try{return e()}finally{Pe(),Oe(t)}}function At(e,t,n=-1){return jt(e,t,n)}function jt(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=pr.call(e);if(s!==pr.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=Mt(e),t=Mt(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(!jt(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)||!jt(e[o],t[o],n-1,i,a))return!1}}return i.pop(),a.pop(),!0}function Mt(e){return bt(e)?e.slice():u(e)||ar(e)||d(e)||cr(e)?Array.from(e.entries()):e}function Nt(e){return e[Symbol.iterator]=Pt,Ft(Object.create(mr),e)}function Pt(){return this}Object.defineProperty(e,`__esModule`,{value:!0});let Ft=Object.assign,It=Object.getOwnPropertyDescriptor,Lt=Object.defineProperty,Rt=Object.prototype,zt=[];Object.freeze(zt);let Bt={};Object.freeze(Bt);let Vt=Object.toString(),Ht=()=>{},Ut=Reflect.ownKeys,Wt=Object.getOwnPropertyDescriptors,A=Symbol(`mobx administration`);var Gt=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 Fe(this)}reportChanged(){Ne(),Ie(this),Pe()}toString(){return this.tt}};let Kt=l(`Atom`,Gt),qt=Object.is,Jt={t:`override`,o:function(){return 0},u:function(){t(44,this.t)}},Yt=`true`,Xt=le(),j=[Xt],Zt={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Zt);let Qt=ae(`observable`),$t=ae(`observable.ref`,{A:y}),en=ae(`observable.shallow`,{A:function(e,t,n){return e==null||Tt(e)||bt(e)||ar(e)||cr(e)?e:Array.isArray(e)?cn.array(e,{name:n,deep:!1}):o(e)?cn.object(e,void 0,{name:n,deep:!1}):u(e)?cn.map(e,{name:n,deep:!1}):d(e)?cn.set(e,{name:n,deep:!1}):void 0}}),tn=ae(`observable.struct`,{A:function(e,t){return At(e,t)?t:e}}),nn={box(e,t){let n=pe(t);return new vn(e,he(n),n.name,!0,n.equals)},array(e,t){let n=pe(t);return function(e,t,n=`ObservableArray`,r=!1){return kt(()=>{let i=new $n(n,t,r);Lt(i.j,A,{enumerable:!1,writable:!1,configurable:!0,value:i});let a=new Proxy(i.j,Qn);return i.v=a,e&&e.length&&i.wt(0,0,e),a})}(e,he(n),n.name)},map(e,t){let n=pe(t);return new ir(e,he(n),n.name)},set(e,t){let n=pe(t);return new sr(e,he(n),n.name)},object:(e,t,n)=>kt(()=>Ke(function(e,t){var n;return(n=(e=Ct(e,t))[A]).v??(n.v=new Proxy(e,Jn))}({},n),e,t))},rn=me($t),an=me(en),on=me(Qt),sn=me(tn);var cn=Ft(function(e,t,n){return t&&typeof t.kind==`string`?ce(Qt,e,t):$e(e)?e:o(e)?cn.object(e,t,n):Array.isArray(e)?cn.array(e,t):u(e)?cn.map(e,t):d(e)?cn.set(e,t):typeof e==`object`&&e?e:cn.box(e,t)},Qt,nn);let ln=`computed`,un=E(ln),dn=ge(E(`computed.struct`,{equals:_})),fn=function(e,t){if(t&&typeof t.kind==`string`)return O(un,e,t);if(o(e))return ge(E(ln,e));let n=o(t)?t:{};return n.get=e,n.name||=e.name||``,new bn(n)};var pn;Ft(fn,un);let mn=0,hn=1,gn=(pn=It(()=>{},`name`)?.configurable)!=null&&pn,_n={value:`action`,configurable:!0,writable:!1,enumerable:!1};var vn=class extends Gt{constructor(e,t,n=`ObservableValue`,r=!0,i=qt){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))!==M.UNCHANGED&&this.Ot(e)}jt(e){if(lt(this)){let t=dt(this,{object:this,type:Zn,newValue:e});if(!t)return M.UNCHANGED;e=t.newValue}return e=this.A(e,this.rt,this.tt),this.xt(this.rt,e)?M.UNCHANGED:e}Ot(e){let t=this.rt;this.rt=e,this.reportChanged(),ft(this)&&mt(this,{type:Zn,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 yn=l(`ObservableValue`,vn);var bn=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 Sn(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=_e(`ComputedValue-setter`,e.set)),this.xt=e.equals||qt,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),M.inBatch!==0||this.H&&this.H.size!==0||this.Mt){let e=this.isBeingObserved;if(Fe(this),Ce(this)){let e=M.trackingContext;e||!this.Mt&&!this.isBeingObserved||(M.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),M.trackingContext=e}else !e&&this.isBeingObserved&&this.L.forEach(k)}else Ce(this)&&(this.Nt(),Ne(),this.rt=this.Rt(!1),Pe());let e=this.rt;if(Se(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||Se(e)||Se(n)||!this.xt(e,n);return r&&(this.rt=n),r}Rt(e){let t;if(this.isComputing=!0,e)t=we(this,this.derivation,this.At);else if(!0===M.disableErrorBoundaries)t=this.derivation.call(this.At);else try{t=this.derivation.call(this.At)}catch(e){t=new Sn(e)}return this.isComputing=!1,t}G(){this.Mt||(Te(this),this.rt=void 0)}Nt(){}toString(){return`${this.tt}[${this.derivation.toString()}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let xn=l(`ComputedValue`,bn);var Sn=class{constructor(e){this.cause=void 0,this.cause=e}};let Cn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var wn=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 Tn=!0,En=!1,M=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Tn=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(Tn=!1),Tn?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new wn):(setTimeout(()=>{En||t(35)},1),new wn)}();var Dn=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,M.pendingReactions.push(this),Le())}X(){if(!this.isDisposed){Ne(),this.isScheduled=!1;let e=M.trackingContext;if(M.trackingContext=this,Ce(this)){this.isTrackPending=!0;try{this.Et()}catch(e){this.Pt(e)}}M.trackingContext=e,Pe()}}track(e){if(this.isDisposed)return;Ne(),this.isRunning=!0;let t=M.trackingContext;M.trackingContext=this;let n=we(this,e,void 0);M.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Te(this),Se(n)&&this.Pt(n.cause),Pe()}Pt(e){if(this.kt)this.kt(e,this);else{if(M.disableErrorBoundaries)throw e;M.suppressReactionErrors||console.error(`[mobx] uncaught error in '${this}'`,e),M.globalReactionErrorHandlers.forEach(t=>t(e,this))}}dispose(){var e;this.isDisposed||(this.isDisposed=!0,(e=this.It)==null||e.call(this),this.isRunning||(Ne(),Te(this),Pe()))}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[A]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.tt}]`}};let On=100,kn=e=>e(),An=l(`Reaction`,Dn),jn=`action`,Mn=`autoAction`,Nn=b(jn),Pn=b(`action.bound`,{bound:!0}),Fn=b(Mn,{autoAction:!0}),In=b(`autoAction.bound`,{autoAction:!0,bound:!0}),Ln=Be(!1);Ft(Ln,Nn);let Rn=Be(!0);Ft(Rn,Fn);let zn=ze(Pn),Bn=ze(In),Vn=e=>e(),Hn=`always`;var Un=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};let Wn=te(`flow`),Gn=te(`flow.bound`,{bound:!0}),Kn=Ft(function(e,t){if(t&&typeof t.kind==`string`)return T(Wn,e,t);let n=e,i=n.name||`flow`,a=function(){let e=arguments,t=Ln(i,n).apply(this,e),a,o,s=new Promise(function(e,n){function s(e){let r;o=void 0;try{r=Ln(i,t.next).call(t,e)}catch(e){return n(e)}l(r)}function c(e){let r;o=void 0;try{r=Ln(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=Ln(i,function(){try{o&&Ye(o);let e=t.return(void 0),n=Promise.resolve(e.value);n.then(Ht,Ht),Ye(n),a(new Un)}catch(e){a(e)}}),s};return a.isMobXFlow=!0,a},Wn),qn=fe(Gn,T),Jn={has:(e,t)=>ct(e).et(t),get:(e,t)=>ct(e).Tt(t),set(e,t,n){var r;return!!i(t)&&((r=ct(e).Bt(t,n,!0))==null||r)},deleteProperty(e,t){var n;return!!i(t)&&((n=ct(e).Dt(t,!0))==null||n)},defineProperty(e,t,n){var r;return(r=ct(e).l(t,n))==null||r},ownKeys:e=>ct(e).it(),preventExtensions(e){t(13)}},Yn=Symbol(`mobx-keys`),Xn=`splice`,Zn=`update`,Qn={get(e,t){let n=e[A];return t===A?n:t===`length`?n.Kt():typeof t!=`string`||isNaN(t)?p(er,t)?er[t]:e[t]:n.Tt(parseInt(t))},set(e,t,n){let r=e[A];return t===`length`?r.Lt(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.Bt(parseInt(t),n),!0},preventExtensions(){t(15)}};var $n=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 Gt(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=zt),lt(this)){let r=dt(this,{object:this.v,type:Xn,index:e,removedCount:t,added:n});if(!r)return zt;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=ft(this),i=r?{observableKind:`array`,object:this.v,type:Zn,debugObjectName:this.ct.tt,index:e,newValue:t,oldValue:n}:null;this.ct.reportChanged(),r&&mt(this,i)}Ft(e,t,n){let r=ft(this),i=r?{observableKind:`array`,object:this.v,debugObjectName:this.ct.tt,type:Xn,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;this.ct.reportChanged(),r&&mt(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(lt(this)){let n=dt(this,{type:Zn,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)}}},er={clear(){return this.splice(0)},replace(e){let t=this[A];return t.wt(0,t.j.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[A];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[A].wt(e,t,n)},push(...e){let t=this[A];return t.wt(t.j.length,0,e),t.j.length},pop(){return this.splice(Math.max(this[A].j.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[A];return t.wt(0,0,e),t.j.length},reverse(){return M.trackingDerivation&&t(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){M.trackingDerivation&&t(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[A],n=t.ht(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};gt(`at`,_t),gt(`concat`,_t),gt(`flat`,_t),gt(`includes`,_t),gt(`indexOf`,_t),gt(`join`,_t),gt(`lastIndexOf`,_t),gt(`slice`,_t),gt(`toString`,_t),gt(`toLocaleString`,_t),gt(`toSorted`,_t),gt(`toSpliced`,_t),gt(`with`,_t),gt(`every`,vt),gt(`filter`,vt),gt(`find`,vt),gt(`findIndex`,vt),gt(`findLast`,vt),gt(`findLastIndex`,vt),gt(`flatMap`,vt),gt(`forEach`,vt),gt(`map`,vt),gt(`some`,vt),gt(`toReversed`,vt),gt(`reduce`,yt),gt(`reduceRight`,yt);let tr=l(`ObservableArrayAdministration`,$n),nr={},rr=`delete`;var ir=class{constructor(e,t=v,n=`ObservableMap`){this.A=void 0,this.tt=void 0,this[A]=nr,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,kt(()=>{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(!M.trackingDerivation)return this.et(e);let t=this.dt.get(e);if(!t){let n=t=new vn(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(lt(this)){let r=dt(this,{type:n?Zn:`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(lt(this)&&!dt(this,{type:rr,object:this,name:e}))return!1;if(this.et(e)){let t=ft(this),n=t?{observableKind:`map`,debugObjectName:this.tt,type:rr,object:this,oldValue:this.ft.get(e).rt,name:e}:null;return ot(()=>{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&&mt(this,n),!0}return!1}Gt(e,t){let n=this.ft.get(e);if((t=n.jt(t))!==M.UNCHANGED){let r=ft(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:Zn,object:this,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&mt(this,i)}}Jt(e,t){ot(()=>{var n;let r=new vn(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=ft(this);n&&mt(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 xt({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 xt({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 ar(e)&&(e=new Map(e)),ot(()=>{o(e)?function(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>Rt.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(){ot(()=>{Ee(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return ot(()=>{let n=function(e){if(u(e)||ar(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`}},ar=l(`ObservableMap`,ir);let or={};var sr=class{constructor(e,t=v,n=`ObservableSet`){this.tt=void 0,this[A]=or,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),kt(()=>{this.ct=g(this.tt),e&&this.replace(e)})}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){ot(()=>{Ee(()=>{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(lt(this)){let t=dt(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){ot(()=>{e=this.A(e,void 0),this.ft.add(e),this.ct.reportChanged()});let t=ft(this);t&&mt(this,t?{observableKind:`set`,debugObjectName:this.tt,type:`add`,object:this,newValue:e}:null)}return this}delete(e){if(lt(this)&&!dt(this,{type:rr,object:this,oldValue:e}))return!1;if(this.has(e)){let t=ft(this),n=t?{observableKind:`set`,debugObjectName:this.tt,type:rr,object:this,oldValue:e}:null;return ot(()=>{this.ct.reportChanged(),this.ft.delete(e)}),t&&mt(this,n),!0}return!1}has(e){return this.ct.reportObserved(),this.ft.has(this.Wt(e))}entries(){let e=this.values();return St({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 St({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 cr(e)&&(e=new Set(e)),Array.isArray(e)||d(e)?ot(()=>{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`}},cr=l(`ObservableSet`,sr);let lr=Object.create(null),ur=`remove`;var dr=class{constructor(e,t=new Map,n,r=Xt){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 Gt(`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 bn)return n.set(t),!0;if(lt(this)){let n=dt(this,{type:Zn,object:this.v||this.h,name:e,newValue:t});if(!n)return null;t=n.newValue}if((t=n.jt(t))!==M.UNCHANGED){let r=ft(this),i=r?{type:Zn,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&mt(this,i)}return!0}Tt(e){return M.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(!M.trackingDerivation)return e in this.h;this.Qt||=new Map;let t=this.Qt.get(e);return t||(t=new vn(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{Ne();let r=this.Dt(e);if(!r)return r;if(lt(this)){let n=dt(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=Ft({},t,{value:r}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else Lt(this.h,e,t);this.Yt(e,t.value)}finally{Pe()}return!0}S(e,t,n,r=!1){try{Ne();let i=this.Dt(e);if(!i)return i;if(lt(this)){let n=dt(this,{object:this.v||this.h,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let a=wt(e),o={configurable:!M.safeDescriptors||this.p,enumerable:!0,get:a.get,set:a.set};if(r){if(!Reflect.defineProperty(this.h,e,o))return!1}else Lt(this.h,e,o);let s=new vn(t,n,`ObservableObject.key`,!1);this.j.set(e,s),this.Yt(e,s.rt)}finally{Pe()}return!0}m(e,t,n=!1){try{Ne();let r=this.Dt(e);if(!r)return r;if(lt(this)&&!dt(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=wt(e),a={configurable:!M.safeDescriptors||this.p,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.h,e,a))return!1}else Lt(this.h,e,a);this.j.set(e,new bn(t)),this.Yt(e,void 0)}finally{Pe()}return!0}Dt(e,t=!1){if(!p(this.h,e))return!0;if(lt(this)&&!dt(this,{object:this.v||this.h,name:e,type:ur}))return null;try{var n;Ne();let r=ft(this),i=this.j.get(e),a;if(i||!r||(a=It(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 vn&&(a=i.rt),Ie(i)),this.lt.reportChanged(),(n=this.Qt)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&mt(this,{type:ur,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{Pe()}return!0}Yt(e,t){var n;let r=ft(this);r&&r&&mt(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(),Ut(this.h)}nt(){return this.lt.reportObserved(),Object.keys(this.h)}};let fr=l(`ObservableObjectAdministration`,dr),pr=Rt.toString,mr=globalThis.Iterator?.prototype||{};e.$mobx=A,e.FlowCancellationError=Un,e.ObservableMap=ir,e.ObservableSet=sr,e.Reaction=Dn,e._allowStateChanges=xe,e._allowStateChangesInsideComputed=Ve,e._allowStateReadsEnd=function(e){M.allowStateReads=e},e._allowStateReadsStart=function(e){let t=M.allowStateReads;return M.allowStateReads=e,t},e._autoAction=Rn,e._autoActionBound=Bn,e._endAction=be,e._getAdministration=Dt,e._getGlobalState=function(){return M},e._interceptReads=function(e,t,n){let r;return ar(e)||bt(e)||yn(e)?r=Dt(e):Tt(e)&&(r=Dt(e,t)),r.dehancer=typeof t==`function`?t:n,()=>{r.dehancer=void 0}},e._isComputingDerivation=function(){return M.trackingDerivation!==null},e._resetGlobalState=function(){let e=new wn;for(let t in e)Cn.indexOf(t)===-1&&(M[t]=e[t]);M.allowStateChanges=!M.enforceActions},e._startAction=ye,e.action=Ln,e.actionBound=zn,e.autorun=Ue,e.compareDefault=qt,e.compareIdentity=function(e,t){return e===t},e.compareShallow=function(e,t){return At(e,t,1)},e.compareStructural=_,e.computed=fn,e.computedStruct=dn,e.configure=function(e){!0===e.isolateGlobalState&&function(){if((M.pendingReactions.length||M.inBatch||M.isRunningReactions)&&t(36),En=!0,Tn){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),M=new wn}}();let{enforceActions:n}=e;if(n!==void 0){let e=n===Hn?Hn:n===`observed`;M.enforceActions=e,M.allowStateChanges=!0!==e&&e!==Hn}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(M[t]=!!e[t])}),M.allowStateReads=!M.observableRequiresReaction,e.reactionScheduler&&function(e){let t=kn;kn=n=>e(()=>t(n))}(e.reactionScheduler)},e.createAtom=g,e.defineProperty=function(e,n,r){if(Tt(e))return e[A].l(n,r);t(39)},e.entries=function(e){return Tt(e)?et(e).map(t=>[t,e[t]]):ar(e)?et(e).map(t=>[t,e.get(t)]):cr(e)?Array.from(e.entries()):bt(e)?e.map((e,t)=>[t,e]):void t(7)},e.extendObservable=Ke,e.flow=Kn,e.flowBound=qn,e.flowResult=function(e){return e},e.get=function(e,n){if(tt(e,n))return Tt(e)?e[A].Tt(n):ar(e)?e.get(n):bt(e)?e[n]:void t(11)},e.getAtom=Et,e.getDebugName=Ot,e.getDependencyTree=function(e,t){return qe(Et(e,t))},e.getObserverTree=function(e,t){return Je(Et(e,t))},e.has=tt,e.intercept=function(e,t,n){return r(n)?function(e,t,n){return ut(Dt(e,t),n)}(e,t,n):function(e,t){return ut(Dt(e),t)}(e,t)},e.isAction=He,e.isBoxedObservable=yn,e.isComputed=function(e){return Ze(e)},e.isComputedProp=function(e,t){return Ze(e,t)},e.isFlow=Xe,e.isFlowCancellationError=function(e){return e instanceof Un},e.isObservable=$e,e.isObservableArray=bt,e.isObservableMap=ar,e.isObservableObject=Tt,e.isObservableProp=function(e,t){return Qe(e,t)},e.isObservableSet=cr,e.keys=et,e.makeAutoObservable=function(e,t,n){return o(e)?Ke(e,e,t,n):(kt(()=>{let r=Ct(e,n)[A];if(!e[Yn]){let t=Object.getPrototypeOf(e),n=new Set([...Ut(e),...Ut(t)]);n.delete(`constructor`),n.delete(A),c(t,Yn,n)}e[Yn].forEach(e=>ht(r,e,!t||!(e in t)||t[e]))}),e)},e.makeObservable=function(e,t,n){return kt(()=>{let r=Ct(e,n)[A];Ut(t).forEach(e=>ht(r,e,t[e]))}),e},e.observable=cn,e.observableDeep=on,e.observableRef=rn,e.observableShallow=an,e.observableStruct=sn,e.observe=function(e,t,n,i){return r(n)?function(e,t,n,r){return rt(Dt(e,t),n,r)}(e,t,n,i):function(e,t,n){let r=Dt(e);if(bt(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(!ar(e)&&!cr(e)&&!Tt(e))return rt(r,t,n);return pt(r,t)}(e,t,n)},e.onBecomeObserved=function(e,t,n){return Ge(`onBO`,e,t,n)},e.onBecomeUnobserved=function(e,t,n){return Ge(`onBUO`,e,t,n)},e.onReactionError=function(e){return M.globalReactionErrorHandlers.push(e),()=>{let t=M.globalReactionErrorHandlers.indexOf(e);t>=0&&M.globalReactionErrorHandlers.splice(t,1)}},e.override=Jt,e.ownKeys=nt,e.reaction=function(e,t,n=Bt){function r(){if(p=!1,h.isDisposed)return;let t=!1,r=d;h.track(()=>{let n=xe(!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=Ln(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=We(n),d,f=!0,p=!1,m=n.equals||qt,h=new Dn(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){Tt(e)?e[A].Dt(n):ar(e)||cr(e)?e.delete(n):bt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=Ve,e.set=function e(n,r,i){if(arguments.length===2&&!cr(n)){Ne();let t=r;try{for(let r in t)e(n,r,t[r])}finally{Pe()}return}Tt(n)?n[A].Bt(r,i):ar(n)?n.set(r,i):cr(n)?n.add(r):bt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(42,r),Ne(),r>=n.length&&(n.length=r+1),n[r]=i,Pe()):t(8)},e.spy=function(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}},e.toJS=function(e){return at(e,new Map)},e.transaction=ot,e.untracked=Ee,e.values=function(e){return Tt(e)?et(e).map(t=>e[t]):ar(e)?et(e).map(t=>e.get(t)):cr(e)?Array.from(e.values()):bt(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 Ft(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let r,i,a=new Promise((n,a)=>{var o;let s=st(e,n,Ft({},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):st(e,t,n||{})}})),AT=Ae((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++j.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=T(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 ee(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let te=Reflect.ownKeys;function w(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function ne(e){return e===null?null:typeof e==`object`?``+e:e}function T(e,t){return o.hasOwnProperty.call(e,t)}let re=Object.getOwnPropertyDescriptors;function E(e,t){return!!(e&t)}function D(e,t,n){return n?e|=t:e&=~t,e}function ie(e,t){t.includes(e.kind)||n(`The decorator applied to '${String(e.name)}' cannot be used on a ${e.kind} element`)}let O=Symbol(`mobx administration`);var ae=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 E(this.flags_,1)}set isBeingObserved(e){this.flags_=D(this.flags_,1,e)}get isPendingUnobservation(){return E(this.flags_,2)}set isPendingUnobservation(e){this.flags_=D(this.flags_,2,e)}get diffValue(){return+!!E(this.flags_,4)}set diffValue(e){this.flags_=D(this.flags_,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return un(this)}reportChanged(){on(),dn(this),sn()}toString(){return this.name_}};let oe=b(`Atom`,ae);function se(e,t=f,n=f){let r=new ae(e);return t!==f&&(r.onBOL=new Set([t])),n!==f&&(r.onBUOL=new Set([n])),r}function ce(e,t){return e===t}function le(e,t){return Li(e,t)}function ue(e,t){return Li(e,t,1)}let de=Object.is;function fe(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||Sr(e)?e:Array.isArray(e)?dt.array(e,{name:n}):g(e)?dt.object(e,void 0,{name:n}):x(e)?dt.map(e,{name:n}):C(e)?dt.set(e,{name:n}):typeof e==`function`&&!Bn(e)&&!pr(e)?_(e)?lr(e):In(n,e):e}function pe(e,t,r){if(e==null||Ai(e)||mi(e)||N(e)||Si(e))return e;if(Array.isArray(e))return dt.array(e,{name:r,deep:!1});if(g(e))return dt.object(e,void 0,{name:r,deep:!1});if(x(e))return dt.map(e,{name:r,deep:!1});if(C(e))return dt.set(e,{name:r,deep:!1});n(`The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets`)}function me(e){return e}function he(e,t){return Sr(e)&&n(`observable.struct should not be used with observable values`),Li(e,t)?t:e}let ge=`override`,_e={annotationType_:ge,make_:ye,extend_:be};function ve(e){return e.annotationType_===ge}function ye(e,t){return e.isPlainObject_&&n(`Cannot apply '${this.annotationType_}' to '${e.name_}.${t.toString()}':\n'${this.annotationType_}' cannot be used on plain objects.`),T(e.appliedAnnotations_,t)||n(`'${e.name_}.${t.toString()}' is annotated with '${this.annotationType_}', but no such annotated member was found on prototype.`),0}function be(e,t,r,i){n(44,this.annotationType_)}function xe(e,t){return{annotationType_:e,options_:t,make_:Se,extend_:Ce}}function Se(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:Bn(n.value)?1:(a(r,t,Ee(e,this,t,n,!1)),2)}function Ce(e,t,n,r){let i=Ee(e,this,t,n);return e.defineProperty_(t,i,r)}function we(e,t,r){ie(r,[`method`,`field`]);let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>xt(s.options_?.name??a.toString(),e,s.options_?.autoAction??!1);if(i==`field`)return function(e){var t;let n=e;return Bn(n)||(n=c(n)),(t=s.options_)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n};if(i==`method`){var l;return Bn(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 Te(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 Ee(e,t,n,r,i=j.safeDescriptors){var a,o;Te(e,t,n,r);let{value:s}=r;return(a=t.options_)!=null&&a.bound&&(s=s.bind(e.proxy_??e.target_)),{value:xt(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 De(e,t){return{annotationType_:e,options_:t,make_:Oe,extend_:ke}}function Oe(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&&(!T(e.target_,t)||!pr(e.target_[t]))&&this.extend_(e,t,n,!1)===null?0:pr(n.value)?1:(a(r,t,Me(e,this,t,n,!1,!1)),2)}function ke(e,t,n,r){let i=Me(e,this,t,n,this.options_?.bound);return e.defineProperty_(t,i,r)}function Ae(e,t,n){var r;ie(n,[`method`]);let{name:i,addInitializer:a}=n;return pr(t)||(t=lr(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 je(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 Me(e,t,n,r,i,a=j.safeDescriptors){je(e,t,n,r);let{value:o}=r;return pr(o)||(o=lr(o)),i&&(o=o.bind(e.proxy_??e.target_),o.isMobXFlow=!0),{value:o,configurable:a?e.isPlainObject_:!0,enumerable:!1,writable:!a}}function Ne(e,t){return{annotationType_:e,options_:t,make_:Pe,extend_:k}}function Pe(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function k(e,t,n,i){return Ie(e,this,t,n),e.defineComputedProperty_(t,r({},this.options_,{get:n.get,set:n.set}),i)}function Fe(e,t,n){ie(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 At(o)}return o(function(){let e=Di(this)[O],n=this,r=e.values_.get(a);r instanceof At&&r.derivation!==t&&e.values_.delete(a),(e.lazyComputedKeys_??=new Map).set(a,()=>c(n,e))}),function(){let e=this[O],n=e.values_.get(a);if(n instanceof At&&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 Ie(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 Le(e,t){return{annotationType_:e,options_:t,make_:Re,extend_:ze}}function Re(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function ze(e,t,n,r){return Ve(e,this,t,n),e.defineObservableProperty_(t,n.value,this.options_?.enhancer_??fe,r)}function Be(e,t,r){if(r.kind===`field`)throw n(`Please use \`@observable accessor ${String(r.name)}\` instead of \`@observable ${String(r.name)}\``);ie(r,[`accessor`]);let i=e,{kind:a,name:o}=r;if(a!==`accessor`)return;function s(e,t){let n=Di(e)[O];return(n.lazyObservableKeys_??=new Map).set(o,()=>new Ot(t,i.options_?.enhancer_??fe,`${n.name_}.${o.toString()}`,!1)),n}return{get(){return(this[O]??s(this,t.get.call(this))).getObservablePropValue_(o)},set(e){return(this[O]??s(this,e)).setObservablePropValue_(o,e)},init(e){return s(this,e),e}}}function Ve(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 He=Ue();function Ue(e){return{annotationType_:`true`,options_:e,make_:Ke,extend_:qe}}let We=[He];function Ge(e){let t=e.deep!==!1,n=!!e.autoBind,r=!t|(n?2:0);return We[r]??(We[r]=Ue({deep:t,autoBind:n}))}function Ke(e,t,n,r){var i;if(n.get)return gt.make_(e,t,n,r);if(n.set){let i=Bn(n.set)?n.set:xt(t.toString(),n.set);return r===e.target_?e.defineProperty_(t,{configurable:j.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?ur:lr).make_(e,t,n,r)}return((o=this.options_)!=null&&o.autoBind?Rn:In).make_(e,t,n,r)}let c=this.options_?.deep===!1?st:dt;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 qe(e,t,n,r){var i;return n.get?gt.extend_(e,t,n,r):n.set?e.defineProperty_(t,{configurable:j.safeDescriptors?e.isPlainObject_:!0,set:xt(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?st:dt).extend_(e,t,n,r))}function Je(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 Ye={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Ye);function Xe(e){return e||Ye}let Ze=Le(`observable`),Qe=Le(`observable.ref`,{enhancer_:me}),$e=Le(`observable.shallow`,{enhancer_:pe}),et=Le(`observable.struct`,{enhancer_:he});function tt(e){return Je(e,Be)}function nt(e){return e.deep===!0?fe:e.deep===!1?me:it(e.defaultDecorator)}function rt(e){return e?e.defaultDecorator??Ge(e):void 0}function it(e){return e?e.options_?.enhancer_??fe:fe}function at(e,t,n){return t&&typeof t.kind==`string`?Be(Ze,e,t):Sr(e)?e:g(e)?dt.object(e,t,n):Array.isArray(e)?dt.array(e,t):x(e)?dt.map(e,t):C(e)?dt.set(e,t):typeof e==`object`&&e?e:dt.box(e,t)}let ot={box(e,t){let n=Xe(t);return new Ot(e,nt(n),n.name,!0,n.equals)},array(e,t){let n=Xe(t);return si(e,nt(n),n.name)},map(e,t){let n=Xe(t);return new _i(e,nt(n),n.name)},set(e,t){let n=Xe(t);return new xi(e,nt(n),n.name)},object(e,t,n){return P(()=>Zn(Kr({},n),e,t))}},st=tt(Qe),ct=tt($e),lt=tt(Ze),ut=tt(et);var dt=r(at,Ze,ot);let ft=`computed`;function pt(e){return Je(e,Fe)}let mt=Ne(ft),ht=pt(Ne(`computed.struct`,{equals:le})),gt=function(e,t){if(t&&typeof t.kind==`string`)return Fe(mt,e,t);if(g(e))return pt(Ne(ft,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 At(r)};r(gt,mt);let _t=0,vt=1,yt=i(()=>{},`name`)?.configurable??!1,bt={value:`action`,configurable:!0,writable:!1,enumerable:!1};function xt(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 St(e,r,t,i||this,arguments)}return o.isMobxAction=!0,o.toString=()=>t.toString(),yt&&(bt.value=e,a(o,`name`,bt)),o}function St(e,t,n,r,i){let a=Ct(e,t,r,i);try{return n.apply(r,i)}catch(e){throw a.error_=e,e}finally{wt(a)}}function Ct(e,t,n,r){let i=xn()&&!!e,a=0;i&&(a=Date.now(),Cn({type:M,name:e,object:n,arguments:r?Array.from(r):s}));let o=j.trackingDerivation,c=!t||!o;on();let l=j.allowStateChanges;c&&(Ut(),l=Et(!0));let u=j.allowStateReads;A(!0);let d={runAsAction_:c,prevDerivation_:o,prevAllowStateChanges_:l,prevAllowStateReads_:u,notifySpy_:i,startTime_:a,actionId_:vt++,parentActionId_:_t};return _t=d.actionId_,d}function wt(e){_t!==e.actionId_&&n(30),_t=e.parentActionId_,e.error_!==void 0&&(j.suppressReactionErrors=!0),Dt(e.prevAllowStateChanges_),Gt(e.prevAllowStateReads_),sn(),e.runAsAction_&&Wt(e.prevDerivation_),e.notifySpy_&&Tn({time:Date.now()-e.startTime_}),j.suppressReactionErrors=!1}function Tt(e,t){let n=Et(e);try{return t()}finally{Dt(n)}}function Et(e){let t=j.allowStateChanges;return j.allowStateChanges=e,t}function Dt(e){j.allowStateChanges=e}var Ot=class extends ae{constructor(e,t,n=`ObservableValue@`+u(),r=!0,i=de){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&&xn()&&Sn({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!==j.UNCHANGED){let n=xn();n&&Cn({type:ii,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:e,oldValue:t}),this.setNewValue_(e),n&&Tn()}}prepareNewValue_(e){if(It(this),qr(this)){let t=Yr(this,{object:this,type:ii,newValue:e});if(!t)return j.UNCHANGED;e=t.newValue}return e=this.enhancer_(e,this.value_,this.name_),this.equals_(this.value_,e)?j.UNCHANGED:e}setNewValue_(e){let t=this.value_;this.value_=e,this.reportChanged(),Xr(this)&&Qr(this,{type:ii,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 ne(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let kt=b(`ObservableValue`,Ot);var At=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 Mt(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_=xt(this.name_+`-setter`,e.set)),this.equals_=e.equals||de,this.scope_=e.context,this.requiresReaction_=e.requiresReaction,this.keepAlive_=!!e.keepAlive}onBecomeStale_(){pn(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return E(this.flags_,1)}set isComputing(e){this.flags_=D(this.flags_,1,e)}get isRunningSetter(){return E(this.flags_,2)}set isRunningSetter(e){this.flags_=D(this.flags_,2,e)}get isBeingObserved(){return E(this.flags_,4)}set isBeingObserved(e){this.flags_=D(this.flags_,4,e)}get isPendingUnobservation(){return E(this.flags_,8)}set isPendingUnobservation(e){this.flags_=D(this.flags_,8,e)}get diffValue(){return+!!E(this.flags_,16)}set diffValue(e){this.flags_=D(this.flags_,16,e===1)}get(){if(this.isComputing&&n(32,this.name_,this.derivation),j.inBatch===0&&(!this.observers_||this.observers_.size===0)&&!this.keepAlive_)Pt(this)&&(this.warnAboutUntrackedRead_(),on(),this.value_=this.computeValue_(!1),sn());else{let e=this.isBeingObserved;if(un(this),Pt(this)){let e=j.trackingContext;!e&&(this.keepAlive_||this.isBeingObserved)&&(j.trackingContext=this),this.trackAndCompute()&&fn(this),j.trackingContext=e}else !e&&this.isBeingObserved&&this.observing_.forEach(ln)}let e=this.value_;if(Nt(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||Nt(e)||Nt(n)||!this.equals_(e,n);return r&&(this.value_=n,xn()&&Sn({observableKind:`computed`,debugObjectName:this.name_,object:this.scope_,type:`update`,oldValue:e,newValue:n})),r}computeValue_(e){this.isComputing=!0;let t=Et(!1),n;if(e)n=Rt(this,this.derivation,this.scope_);else if(j.disableErrorBoundaries===!0)n=this.derivation.call(this.scope_);else try{n=this.derivation.call(this.scope_)}catch(e){n=new Mt(e)}return Dt(t),this.isComputing=!1,n}suspend_(){this.keepAlive_||(Vt(this),this.value_=void 0)}warnAboutUntrackedRead_(){(typeof this.requiresReaction_==`boolean`?this.requiresReaction_:j.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 ne(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let jt=b(`ComputedValue`,At);var Mt=class{constructor(e){this.cause=void 0,this.cause=e}};function Nt(e){return e instanceof Mt}function Pt(e){switch(e.dependenciesState_){case 0:return!1;case-1:case 2:return!0;case 1:{let t=A(!0),n=Ut(),r=e.observing_,i=r.length;for(let a=0;a<i;a++){let i=r[a];if(jt(i)){if(j.disableErrorBoundaries)i.get();else try{i.get()}catch{return Wt(n),Gt(t),!0}if(e.dependenciesState_===2)return Wt(n),Gt(t),!0}}return Kt(e),Wt(n),Gt(t),!1}}}function Ft(){return j.trackingDerivation!==null}function It(e){let t=!!e.observers_&&e.observers_.size>0;!j.allowStateChanges&&(t||j.enforceActions===`always`)&&console.warn(`[MobX] `+(j.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 Lt(e){!j.allowStateReads&&j.observableRequiresReaction&&console.warn(`[mobx] Observable '${e.name_}' being read outside a reactive context.`)}function Rt(e,t,n){let r=A(!0);Kt(e),e.newObserving_=Array(e.runId_===0?100:e.observing_.length),e.unboundDepsCount_=0,e.runId_=++j.runId;let i=j.trackingDerivation;j.trackingDerivation=e,j.inBatch++;let a;if(j.disableErrorBoundaries===!0)a=t.call(n);else try{a=t.call(n)}catch(e){a=new Mt(e)}return j.inBatch--,j.trackingDerivation=i,Bt(e),zt(e),Gt(r),a}function zt(e){e.observing_.length===0&&(typeof e.requiresObservable_==`boolean`?e.requiresObservable_:j.reactionRequiresObservable)&&console.warn(`[mobx] Derivation '${e.name_}' is created/updated without reading any observable value.`)}function Bt(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&&rn(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,nn(t,e))}r!==0&&(e.dependenciesState_=r,e.onBecomeStale_())}function Vt(e){let t=e.observing_;e.observing_=[];let n=t.length;for(;n--;)rn(t[n],e);e.dependenciesState_=-1}function Ht(e){let t=Ut();try{return e()}finally{Wt(t)}}function Ut(){let e=j.trackingDerivation;return j.trackingDerivation=null,e}function Wt(e){j.trackingDerivation=e}function A(e){let t=j.allowStateReads;return j.allowStateReads=e,t}function Gt(e){j.allowStateReads=e}function Kt(e){if(e.dependenciesState_===0)return;e.dependenciesState_=0;let t=e.observing_,n=t.length;for(;n--;)t[n].lowestObserverState_=0}let qt=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Jt=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 Yt=!0,Xt=!1,j=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Yt=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(Yt=!1),Yt?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Jt):(setTimeout(()=>{Xt||n(35)},1),new Jt)}();function Zt(){if((j.pendingReactions.length||j.inBatch||j.isRunningReactions)&&n(36),Xt=!0,Yt){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),j=new Jt}}function Qt(){return j}function $t(){let e=new Jt;for(let t in e)qt.indexOf(t)===-1&&(j[t]=e[t]);j.allowStateChanges=!j.enforceActions}function en(e){return!!e.observers_&&e.observers_.size>0}function tn(e){return e.observers_??new Set}function nn(e,t){(e.observers_??=new Set).add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function rn(e,t){let n=e.observers_;n&&(n.delete(t),n.size===0&&an(e))}function an(e){e.isPendingUnobservation===!1&&(e.isPendingUnobservation=!0,j.pendingUnobservations.push(e))}function on(){j.inBatch++}function sn(){--j.inBatch===0&&(_n(),!j.isRunningUnobservations&&j.pendingUnobservations.length>0&&cn())}function cn(){j.isRunningUnobservations=!0;try{let e=j.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 At&&n.suspend_())}j.pendingUnobservations=[]}finally{j.isRunningUnobservations=!1}}function ln(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.observing_)==null||t.forEach(ln))}function un(e){Lt(e);let t=j.trackingDerivation;return t===null?((!e.observers_||e.observers_.size===0)&&j.inBatch>0&&an(e),!1):(t.runId_!==e.lastAccessedBy_&&(e.lastAccessedBy_=t.runId_,t.newObserving_[t.unboundDepsCount_++]=e,!e.isBeingObserved&&j.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function dn(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 fn(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 pn(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 mn=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 E(this.flags_,1)}set isDisposed(e){this.flags_=D(this.flags_,1,e)}get isScheduled(){return E(this.flags_,2)}set isScheduled(e){this.flags_=D(this.flags_,2,e)}get isTrackPending(){return E(this.flags_,4)}set isTrackPending(e){this.flags_=D(this.flags_,4,e)}get isRunning(){return E(this.flags_,8)}set isRunning(e){this.flags_=D(this.flags_,8,e)}get diffValue(){return+!!E(this.flags_,16)}set diffValue(e){this.flags_=D(this.flags_,16,e===1)}onBecomeStale_(){this.schedule_()}schedule_(){this.isScheduled||(this.isScheduled=!0,j.pendingReactions.push(this),_n())}runReaction_(){if(!this.isDisposed){on(),this.isScheduled=!1;let e=j.trackingContext;if(j.trackingContext=this,Pt(this)){this.isTrackPending=!0;try{this.onInvalidate_(),this.isTrackPending&&xn()&&Sn({name:this.name_,type:`scheduled-reaction`})}catch(e){this.reportExceptionInDerivation_(e)}}j.trackingContext=e,sn()}}track(e){if(this.isDisposed)return;on();let t=xn(),n;t&&(n=Date.now(),Cn({name:this.name_,type:`reaction`})),this.isRunning=!0;let r=j.trackingContext;j.trackingContext=this;let i=Rt(this,e,void 0);j.trackingContext=r,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Vt(this),Nt(i)&&this.reportExceptionInDerivation_(i.cause),t&&Tn({time:Date.now()-n}),sn()}reportExceptionInDerivation_(e){if(this.errorHandler_){this.errorHandler_(e,this);return}if(j.disableErrorBoundaries)throw e;let t=`[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '${this}'`;j.suppressReactionErrors?console.warn(`[mobx] (error in reaction '${this.name_}' suppressed, fix error of causing action below)`):console.error(t,e),xn()&&Sn({type:`error`,name:this.name_,message:t,error:``+e}),j.globalReactionErrorHandlers.forEach(t=>t(e,this))}dispose(){if(!this.isDisposed){var e;this.isDisposed=!0,(e=this.removeAbortListener_)==null||e.call(this),this.isRunning||(on(),Vt(this),sn())}}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[O]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.name_}]`}};function hn(e){return j.globalReactionErrorHandlers.push(e),()=>{let t=j.globalReactionErrorHandlers.indexOf(e);t>=0&&j.globalReactionErrorHandlers.splice(t,1)}}let gn=e=>e();function _n(){j.inBatch>0||j.isRunningReactions||gn(vn)}function vn(){j.isRunningReactions=!0;let e=j.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_()}j.isRunningReactions=!1}let yn=b(`Reaction`,mn);function bn(e){let t=gn;gn=n=>e(()=>t(n))}function xn(){return!!j.spyListeners.length}function Sn(e){if(!j.spyListeners.length)return;let t=j.spyListeners;for(let n=0,r=t.length;n<r;n++)t[n](e)}function Cn(e){Sn(r({},e,{spyReportStart:!0}))}let wn={type:`report-end`,spyReportEnd:!0};function Tn(e){Sn(e?r({},e,{type:`report-end`,spyReportEnd:!0}):wn)}function En(e){return j.spyListeners.push(e),d(()=>{j.spyListeners=j.spyListeners.filter(t=>t!==e)})}let M=`action`,Dn=`autoAction`,On=`<unnamed action>`,kn=xe(M),An=xe(`action.bound`,{bound:!0}),jn=xe(Dn,{autoAction:!0}),Mn=xe(`autoAction.bound`,{autoAction:!0,bound:!0});function Nn(e){return Je(e,we)}function Pn(e){return function(t,r){if(r&&typeof r.kind==`string`)return we(e?jn:kn,t,r);if(p(t))return xt(t.name||On,t,e);if(p(r))return xt(t,r,e);if(m(t))return Nn(xe(e?Dn:M,{name:t,autoAction:e}));n("Invalid arguments for `action`")}}let Fn=Pn(!1);r(Fn,kn);let In=Pn(!0);r(In,jn);let Ln=Nn(An),Rn=Nn(Mn);function zn(e){return St(e.name||On,!1,e,this,void 0)}function Bn(e){return p(e)&&e.isMobxAction===!0}function Vn(e,t=c){var r;p(e)||n(`Autorun expects a function as first argument`),Bn(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 mn(i,function(){this.track(s)},t.onError,t.requiresObservable);else{let e=Un(t),n=!1;o=new mn(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 Hn=e=>e();function Un(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Hn}function Wn(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=Fn(a,r.onError?Gn(r.onError,t):t),s=!r.scheduler&&!r.delay,l=Un(r),d=!0,f=!1,m,h=r.equals||de,_=new mn(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=Tt(!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 Gn(e,t){return function(){try{return t.apply(this,arguments)}catch(t){e.call(this,t)}}}function Kn(e,t,n){return Jn(`onBO`,e,t,n)}function qn(e,t,n){return Jn(`onBUO`,e,t,n)}function Jn(e,t,n,r){let i=typeof r==`function`?Ni(t,n):Ni(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 Yn=`always`;function Xn(e){e.isolateGlobalState===!0&&Zt();let{enforceActions:t}=e;if(t!==void 0){let e=t===Yn?Yn:t===`observed`;j.enforceActions=e,j.allowStateChanges=!(e===!0||e===Yn)}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(j[t]=!!e[t])}),j.allowStateReads=!j.observableRequiresReaction,j.disableErrorBoundaries===!0&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),e.reactionScheduler&&bn(e.reactionScheduler)}function Zn(e,t,r,i){arguments.length>4&&n(`'extendObservable' expected 2-4 arguments`),typeof e!=`object`&&n(`'extendObservable' expects an object as first argument`),N(e)&&n(`'extendObservable' should not be used on maps, use map.merge instead`),g(t)||n(`'extendObservable' only accepts plain objects as second argument`),(Sr(t)||Sr(r))&&n(`Extending an object with another observable (object) is not supported`);let a=re(t);return P(()=>{let t=Di(e,i)[O];te(a).forEach(e=>{t.extend_(e,a[e],r&&e in r?r[e]:!0)})}),e}function Qn(e,t){return $n(Ni(e,t))}function $n(e){let t={name:e.name_};return e.observing_&&e.observing_.length>0&&(t.dependencies=nr(e.observing_).map($n)),t}function er(e,t){return tr(Ni(e,t))}function tr(e){let t={name:e.name_};return en(e)&&(t.observers=Array.from(tn(e),tr)),t}function nr(e){return Array.from(new Set(e))}let rr=0;var ir=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};function ar(e){return e instanceof ir}function or(e){return Je(e,Ae)}let sr=De(`flow`),cr=De(`flow.bound`,{bound:!0}),lr=r(function(e,t){if(t&&typeof t.kind==`string`)return Ae(sr,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=++rr,a=Fn(`${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=Fn(`${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=Fn(`${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=Fn(`${i} - runid: ${n} - cancel`,function(){try{s&&dr(s);let e=a.return(void 0),t=Promise.resolve(e.value);t.then(f,f),dr(t),o(new ir)}catch(e){o(e)}}),c};return a.isMobXFlow=!0,a},sr),ur=or(cr);function dr(e){p(e.cancel)&&e.cancel()}function fr(e){return e}function pr(e){return e?.isMobXFlow===!0}function mr(e,t,r){let i;if(N(e)||mi(e)||kt(e))i=Pi(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=Pi(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 hr(e,t,n){return p(n)?_r(e,t,n):gr(e,t)}function gr(e,t){return Jr(Pi(e),t)}function _r(e,t,n){return Jr(Pi(e,t),n)}function vr(e,t){var n;if(t===void 0)return jt(e);if(Ai(e)===!1)return!1;let r=e[O];return(n=r.lazyComputedKeys_)!=null&&n.has(t)?!0:r.values_.has(t)?jt(Ni(e,t)):!1}function yr(e){return arguments.length>1?n(`isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property`):vr(e)}function br(e,t){return m(t)?vr(e,t):n(`isComputed expected a property name as second argument`)}function xr(e,t){if(!e)return!1;if(t!==void 0){if(N(e)||mi(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[O];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[O]||oe(e)||yn(e)||jt(e)}function Sr(e){return arguments.length!==1&&n(`isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property`),xr(e)}function Cr(e,t){return m(t)?xr(e,t):n(`expected a property name as second argument`)}function wr(e){if(Ai(e))return e[O].keys_();if(N(e)||Si(e))return Array.from(e.keys());if(mi(e))return e.map((e,t)=>t);n(5)}function Tr(e){if(Ai(e))return wr(e).map(t=>e[t]);if(N(e))return wr(e).map(t=>e.get(t));if(Si(e))return Array.from(e.values());if(mi(e))return e.slice();n(6)}function Er(e){if(Ai(e))return wr(e).map(t=>[t,e[t]]);if(N(e))return wr(e).map(t=>[t,e.get(t)]);if(Si(e))return Array.from(e.entries());if(mi(e))return e.map((e,t)=>[t,e]);n(7)}function Dr(e,t,r){if(arguments.length===2&&!Si(e)){on();let n=t;try{for(let t in n)Dr(e,t,n[t])}finally{sn()}return}Ai(e)?e[O].set_(t,r):N(e)?e.set(t,r):Si(e)?e.add(t):mi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),t<0&&n(42,t),on(),t>=e.length&&(e.length=t+1),e[t]=r,sn()):n(8)}function Or(e,t){Ai(e)?e[O].delete_(t):N(e)||Si(e)?e.delete(t):mi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),e.splice(t,1)):n(9)}function kr(e,t){if(Ai(e))return e[O].has_(t);if(N(e)||Si(e))return e.has(t);if(mi(e))return t>=0&&t<e.length;n(10)}function Ar(e,t){if(kr(e,t)){if(Ai(e))return e[O].get_(t);if(N(e))return e.get(t);if(mi(e))return e[t];n(11)}}function jr(e,t,r){if(Ai(e))return e[O].defineProperty_(t,r);n(39)}function Mr(e){if(Ai(e))return e[O].ownKeys_();n(38)}function Nr(e,t,n,r){return p(n)?Fr(e,t,n,r):Pr(e,t,n)}function Pr(e,t,r){let i=Pi(e);if(mi(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(N(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 Ir(i,t,r);return Zr(i,t)}function Fr(e,t,n,r){return Ir(Pi(e,t),n,r)}function Ir(e,t,n){if(jt(e)){let r=!0,i;return Vn(()=>{let a=e.get();if(!r||n){let n=Ut();t({observableKind:`computed`,debugObjectName:e.name_,type:ii,object:e,newValue:a,oldValue:i}),Wt(n)}r=!1,i=a})}return n&&t({observableKind:`value`,debugObjectName:e.name_,object:e,type:ii,newValue:e.value_,oldValue:void 0}),Zr(e,t)}function Lr(e,t,n){return e.set(t,n),n}function Rr(e,t){if(typeof e!=`object`||!e||e instanceof Date||!Sr(e))return e;if(kt(e)||jt(e))return Rr(e.get(),t);if(t.has(e))return t.get(e);if(mi(e)){let n=Lr(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=Rr(e,t)}),n}if(Si(e)){let n=Lr(t,e,new Set);return e.forEach(e=>{n.add(Rr(e,t))}),n}if(N(e)){let n=Lr(t,e,new Map);return e.forEach((e,r)=>{n.set(r,Rr(e,t))}),n}else{let n=Lr(t,e,{});return Mr(e).forEach(r=>{o.propertyIsEnumerable.call(e,r)&&(n[r]=Rr(e[r],t))}),n}}function zr(e,t){return t&&n(`toJS no longer supports options`),Rr(e,new Map)}function Br(e,t=void 0){on();try{return e.apply(t)}finally{sn()}}function Vr(e,t,n){return arguments.length===1||t&&typeof t==`object`?Ur(e,t):Hr(e,t,n||{})}function Hr(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[O].isDisposed)if(a(),n.onError)n.onError(e);else throw e},n.timeout)}n.name=n.name||`When@`+u();let i=xt(n.name+`-effect`,t);var a=Vn(t=>{Tt(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function Ur(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=Hr(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 Wr(e){return e[O]}let Gr={has(e,t){return Wr(e).has_(t)},get(e,t){return Wr(e).get_(t)},set(e,t,n){return m(t)?Wr(e).set_(t,n,!0)??!0:!1},deleteProperty(e,t){return m(t)?Wr(e).delete_(t,!0)??!0:!1},defineProperty(e,t,n){return Wr(e).defineProperty_(t,n)??!0},ownKeys(e){return Wr(e).ownKeys_()},preventExtensions(e){n(13)}};function Kr(e,t){var n;return e=Di(e,t),(n=e[O]).proxy_??(n.proxy_=new Proxy(e,Gr))}function qr(e){return e.interceptors_!==void 0&&e.interceptors_.length>0}function Jr(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 Yr(e,t){let r=Ut();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{Wt(r)}}function Xr(e){return e.changeListeners_!==void 0&&e.changeListeners_.length>0}function Zr(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 Qr(e,t){let n=Ut(),r=e.changeListeners_;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Wt(n)}}function $r(e,t,n){return P(()=>{let r=Di(e,n)[O];te(t).forEach(e=>ni(r,e,t[e]))}),e}let ei=Symbol(`mobx-keys`);function ti(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)?Zn(e,e,t,r):(P(()=>{let n=Di(e,r)[O];if(!e[ei]){let t=Object.getPrototypeOf(e),n=new Set([...te(e),...te(t)]);n.delete(`constructor`),n.delete(O),v(t,ei,n)}e[ei].forEach(e=>ni(n,e,t&&e in t?t[e]:!0))}),e)}function ni(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 ri=`splice`,ii=`update`,ai={get(e,t){let n=e[O];return t===O?n:t===`length`?n.getArrayLength_():typeof t==`string`&&!isNaN(t)?n.get_(parseInt(t)):T(ci,t)?ci[t]:e[t]},set(e,t,n){let r=e[O];return t===`length`?r.setArrayLength_(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.set_(parseInt(t),n),!0},preventExtensions(){n(15)}};var oi=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 ae(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){It(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),qr(this)){let r=Yr(this,{object:this.proxy_,type:ri,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_&&xn(),i=Xr(this),a=i||r?{observableKind:`array`,object:this.proxy_,type:ii,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&Cn(a),this.atom_.reportChanged(),i&&Qr(this,a),r&&Tn()}notifyArraySplice_(e,t,n){let r=!this.owned_&&xn(),i=Xr(this),a=i||r?{observableKind:`array`,object:this.proxy_,debugObjectName:this.atom_.name_,type:ri,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&Cn(a),this.atom_.reportChanged(),i&&Qr(this,a),r&&Tn()}get_(e){return this.atom_.reportObserved(),this.dehanceValue_(this.values_[e])}set_(e,t){let n=this.values_;if(e<n.length){It(this.atom_);let r=n[e];if(qr(this)){let n=Yr(this,{type:ii,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 si(e,t,n=`ObservableArray@`+u(),r=!1){return P(()=>{let i=new oi(n,t,r);y(i.values_,O,i);let a=new Proxy(i.values_,ai);return i.proxy_=a,e&&e.length&&i.spliceWithArray_(0,0,e),a})}var ci={clear(){return this.splice(0)},replace(e){let t=this[O];return t.spliceWithArray_(0,t.values_.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[O];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[O].spliceWithArray_(e,t,n)},push(...e){let t=this[O];return t.spliceWithArray_(t.values_.length,0,e),t.values_.length},pop(){return this.splice(Math.max(this[O].values_.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[O];return t.spliceWithArray_(0,0,e),t.values_.length},reverse(){return j.trackingDerivation&&n(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){j.trackingDerivation&&n(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[O],n=t.dehanceValues_(t.values_).indexOf(e);return n>-1?(this.splice(n,1),!0):!1}};li(`at`,ui),li(`concat`,ui),li(`flat`,ui),li(`includes`,ui),li(`indexOf`,ui),li(`join`,ui),li(`lastIndexOf`,ui),li(`slice`,ui),li(`toString`,ui),li(`toLocaleString`,ui),li(`toSorted`,ui),li(`toSpliced`,ui),li(`with`,ui),li(`every`,di),li(`filter`,di),li(`find`,di),li(`findIndex`,di),li(`findLast`,di),li(`findLastIndex`,di),li(`flatMap`,di),li(`forEach`,di),li(`map`,di),li(`some`,di),li(`toReversed`,di),li(`reduce`,fi),li(`reduceRight`,fi);function li(e,t){typeof Array.prototype[e]==`function`&&(ci[e]=t(e))}function ui(e){return function(){let t=this[O];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_);return n[e].apply(n,arguments)}}function di(e){return function(t,n){let r=this[O];return r.atom_.reportObserved(),r.dehanceValues_(r.values_)[e]((e,r)=>t.call(n,e,r,this))}}function fi(e){return function(){let t=this[O];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 pi=b(`ObservableArrayAdministration`,oi);function mi(e){return h(e)&&pi(e[O])}let hi={},gi=`delete`;var _i=class{constructor(e,t=fe,n=`ObservableMap@`+u()){this.enhancer_=void 0,this.name_=void 0,this[O]=hi,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,P(()=>{this.keysAtom_=se(`${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(!j.trackingDerivation)return this.has_(e);let t=this.hasMap_.get(e);if(!t){let n=t=new Ot(this.has_(e),me,`${this.name_}.${w(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(qr(this)){let r=Yr(this,{type:n?ii:`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(It(this.keysAtom_),qr(this)&&!Yr(this,{type:gi,object:this,name:e}))return!1;if(this.has_(e)){let t=xn(),n=Xr(this),r=n||t?{observableKind:`map`,debugObjectName:this.name_,type:gi,object:this,oldValue:this.data_.get(e).value_,name:e}:null;return t&&Cn(r),Br(()=>{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&&Qr(this,r),t&&Tn(),!0}return!1}updateValue_(e,t){let n=this.data_.get(e);if(t=n.prepareNewValue_(t),t!==j.UNCHANGED){let r=xn(),i=Xr(this),a=i||r?{observableKind:`map`,debugObjectName:this.name_,type:ii,object:this,oldValue:n.value_,name:e,newValue:t}:null;r&&Cn(a),n.setNewValue_(t),i&&Qr(this,a),r&&Tn()}}addValue_(e,t){It(this.keysAtom_),Br(()=>{var n;let r=new Ot(t,this.enhancer_,`${this.name_}.${w(e)}`,!1);this.data_.set(e,r),t=r.value_,(n=this.hasMap_.get(e))==null||n.setNewValue_(!0),this.keysAtom_.reportChanged()});let n=xn(),r=Xr(this),i=r||n?{observableKind:`map`,debugObjectName:this.name_,type:`add`,object:this,name:e,newValue:t}:null;n&&Cn(i),r&&Qr(this,i),n&&Tn()}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 N(e)&&(e=new Map(e)),Br(()=>{g(e)?ee(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(){Br(()=>{Ht(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return Br(()=>{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`}},N=b(`ObservableMap`,_i);function vi(e){return e[Symbol.toStringTag]=`MapIterator`,Vi(e)}function yi(e){if(x(e)||N(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=fe,n=`ObservableSet@`+u()){this.name_=void 0,this[O]=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),P(()=>{this.atom_=se(this.name_),e&&this.replace(e)})}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){Br(()=>{Ht(()=>{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(It(this.atom_),qr(this)){let t=Yr(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){Br(()=>{e=this.enhancer_(e,void 0),this.data_.add(e),this.atom_.reportChanged()});let t=xn(),n=Xr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:`add`,object:this,newValue:e}:null;t&&Cn(r),n&&Qr(this,r),t&&Tn()}return this}delete(e){if(qr(this)&&!Yr(this,{type:gi,object:this,oldValue:e}))return!1;if(this.has(e)){let t=xn(),n=Xr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:gi,object:this,oldValue:e}:null;return t&&Cn(r),Br(()=>{this.atom_.reportChanged(),this.data_.delete(e)}),n&&Qr(this,r),t&&Tn(),!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)?Br(()=>{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=He){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 ae(`${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 At)return n.set(t),!0;if(qr(this)){let n=Yr(this,{type:ii,object:this.proxy_||this.target_,name:e,newValue:t});if(!n)return null;t=n.newValue}if(t=n.prepareNewValue_(t),t!==j.UNCHANGED){let r=Xr(this),i=xn(),a=r||i?{type:ii,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,oldValue:n.value_,name:e,newValue:t}:null;i&&Cn(a),n.setNewValue_(t),r&&Qr(this,a),i&&Tn()}return!0}get_(e){return j.trackingDerivation&&!T(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return T(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(!j.trackingDerivation)return e in this.target_;this.pendingKeys_||=new Map;let t=this.pendingKeys_.get(e);return t||(t=new Ot(e in this.target_,me,`${this.name_}.${w(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){It(this.keysAtom_);try{on();let i=this.delete_(e);if(!i)return i;if(qr(this)){let n=Yr(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{sn()}return!0}defineObservableProperty_(e,t,n,r=!1){It(this.keysAtom_);try{on();let i=this.delete_(e);if(!i)return i;if(qr(this)){let n=Yr(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:j.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 Ot(t,n,`${this.name_}.${e.toString()}`,!1);this.values_.set(e,c),this.notifyPropertyAddition_(e,c.value_)}finally{sn()}return!0}defineComputedProperty_(e,t,n=!1){It(this.keysAtom_);try{on();let r=this.delete_(e);if(!r)return r;if(qr(this)&&!Yr(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:j.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 At(t)),this.notifyPropertyAddition_(e,void 0)}finally{sn()}return!0}delete_(e,t=!1){if(It(this.keysAtom_),!T(this.target_,e))return!0;if(qr(this)&&!Yr(this,{object:this.proxy_||this.target_,name:e,type:Ti}))return null;try{var n;on();let r=Xr(this),a=xn(),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 Ot&&(s=o.value_),dn(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&&Cn(t),r&&Qr(this,t),a&&Tn()}}finally{sn()}return!0}notifyPropertyAddition_(e,t){var n;let r=Xr(this),i=xn();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&&Cn(n),r&&Qr(this,n),i&&Tn()}(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(!0),this.keysAtom_.reportChanged()}ownKeys_(){return this.keysAtom_.reportObserved(),te(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.`),T(e,O))return Pi(e)instanceof Ei||n(`Cannot convert '${Fi(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,O,new Ei(e,new Map,String(r),rt(t))),e}let Oi=b(`ObservableObjectAdministration`,Ei);function ki(e){return wi[e]||(wi[e]={get(){return this[O].getObservablePropValue_(e)},set(t){return this[O].setObservablePropValue_(e,t)}})}function Ai(e){return h(e)?Oi(e[O]):!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.`),!ve(t)&&T(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 Ni(e,t){if(typeof e==`object`&&e){if(mi(e))return t!==void 0&&n(23),e[O].atom_;if(Si(e))return e.atom_;if(N(e)){if(t===void 0)return e.keysAtom_;let r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,Fi(e)),r}if(Ai(e)){if(!t)return n(26);let r=e[O],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,Fi(e)),i}if(oe(e)||jt(e)||yn(e))return e}else if(p(e)&&yn(e[O]))return e[O];n(28)}function Pi(e,t){if(e||n(29),t!==void 0)return Pi(Ni(e,t));if(oe(e)||jt(e)||yn(e)||N(e)||Si(e))return e;if(e[O])return e[O];n(24,e)}function Fi(e,t){let n;if(t!==void 0)n=Ni(e,t);else if(Bn(e))return e.name;else n=Ai(e)||N(e)||Si(e)?Pi(e):Ni(e);return n.name_}function P(e){let t=Ut(),n=Et(!0);on();try{return e()}finally{sn(),Dt(n),Wt(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(!(T(t,o)&&Ri(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function zi(e){return mi(e)?e.slice():x(e)||N(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:En,extras:{getDebugName:Fi},$mobx:O}),e.$mobx=O,e.FlowCancellationError=ir,e.ObservableMap=_i,e.ObservableSet=xi,e.Reaction=mn,e._allowStateChanges=Tt,e._allowStateChangesInsideComputed=zn,e._allowStateReadsEnd=Gt,e._allowStateReadsStart=A,e._autoAction=In,e._autoActionBound=Rn,e._endAction=wt,e._getAdministration=Pi,e._getGlobalState=Qt,e._interceptReads=mr,e._isComputingDerivation=Ft,e._resetGlobalState=$t,e._startAction=Ct,e.action=Fn,e.actionBound=Ln,e.autorun=Vn,e.compareDefault=de,e.compareIdentity=ce,e.compareShallow=ue,e.compareStructural=le,e.computed=gt,e.computedStruct=ht,e.configure=Xn,e.createAtom=se,e.defineProperty=jr,e.entries=Er,e.extendObservable=Zn,e.flow=lr,e.flowBound=ur,e.flowResult=fr,e.get=Ar,e.getAtom=Ni,e.getDebugName=Fi,e.getDependencyTree=Qn,e.getObserverTree=er,e.has=kr,e.intercept=hr,e.isAction=Bn,e.isBoxedObservable=kt,e.isComputed=yr,e.isComputedProp=br,e.isFlow=pr,e.isFlowCancellationError=ar,e.isObservable=Sr,e.isObservableArray=mi,e.isObservableMap=N,e.isObservableObject=Ai,e.isObservableProp=Cr,e.isObservableSet=Si,e.keys=wr,e.makeAutoObservable=ti,e.makeObservable=$r,e.observable=dt,e.observableDeep=lt,e.observableRef=st,e.observableShallow=ct,e.observableStruct=ut,e.observe=Nr,e.onBecomeObserved=Kn,e.onBecomeUnobserved=qn,e.onReactionError=hn,e.override=_e,e.ownKeys=Mr,e.reaction=Wn,e.remove=Or,e.runInAction=zn,e.set=Dr,e.spy=En,e.toJS=zr,e.transaction=Br,e.untracked=Ht,e.values=Tr,e.when=Vr})),X=Ae(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=kT():t.exports=AT()}))();function jT(e){if(Array.isArray(e))return Object.freeze(e.map(jT));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]=jT(r);return Object.freeze(t)}return e}function MT(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 NT(e){return typeof e==`string`?e:String(e)}function PT(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 FT(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 IT=class extends Error{constructor(e,t){super(t),this.variable=e}};function LT(e){return e instanceof IT?e:e instanceof Error&&e.cause!==void 0?LT(e.cause):void 0}const RT=e=>e===ko;var zT=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,RT(n)||YT(e,t,n,`initial value`),this.cell=X.observable.box(n,{deep:!1}),this.lastChangedAt=RT(n)?null:Date.now()}read(){let e=this.cell.get();if(RT(e))throw new IT(this.name,`variable "${this.name}" has no value yet: nothing has written it`);return e}set(e){RT(e)||YT(this.name,this.type,e,`set value`),!Object.is(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}stored(){return this.cell.get()}},BT=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_()}},VT=class{constructor(e){this.deriver=e}read(){return this.deriver()}},HT=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new BT(`Variable "${e}"`,()=>{let e=n();return YT(this.name,this.type,e,`computed result`),e})}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}},UT=class{kind=`projection`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new VT(()=>{let e=n();return YT(this.name,this.type,e,`projection result`),e})}read(){return this.cell.read()}lastUpdatedMs(){return null}},WT=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=X.observable.box(JT(t),{deep:!1}),this.lastChangedAt=t.kind===`pending`?null:Date.now()}read(){return this.cell.get()}set(e){let t=JT(e);qT(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}},GT=class{kind=`document`;cell;constructor(e,t){this.name=e,this.cell=new BT(`Variable "${e}"`,()=>JT(t()),qT)}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}};function KT(e){return JSON.stringify(e)}function qT(e,t){return KT(e)===KT(t)}function JT(e){return e.kind===`ok`?{kind:`ok`,value:jT(e.value)}:e}function YT(e,t,n,r){let i=MT(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var XT=class{constructor(e=null){this.parent=e}nodes=X.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new zT(e,t,n))}defineDocument(e,t){this.declare(e,new WT(e,t))}defineDerivedDocument(e,t){this.declare(e,new GT(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`?HT:UT;this.declare(e,new a(e,t,()=>r(i)))}derive(e,t,n){if(this.refuseDisposed(`Derived value "${e}"`),t===`projection`)return new VT(n);let r=new BT(`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 WT))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`?ko:F(KT(e))}try{return F(String(t.read()))}catch(e){return LT(e)===void 0?F(` failed:${e instanceof Error?e.message:String(e)}`):ko}}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 HT||t instanceof GT)&&(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))}},ZT=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?oE(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}},QT=class extends ZT{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},$T=class extends ZT{name=`EvalError`;kind=`EvalError`},eE=class extends $T{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=sE(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}},tE=class extends $T{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}},nE=class extends $T{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}},rE=class extends nE{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)}`}},iE=class extends $T{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},aE=class extends $T{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function oE(e,t){let n=e.split(`
|
|
61
|
+
`}const zS=(e,t)=>e.fg===t.fg&&e.bg===t.bg&&e.link===t.link&&e.attrs?.join()===t.attrs?.join();function BS({runs:e}){let t=[];for(let n of e){let e=t.at(-1);e!==void 0&&zS(e,n)?t[t.length-1]={...e,text:e.text+n.text}:t.push(n)}return t}function VS(e){return e.map(e=>e.text).join(``)}const HS={};function US(e,t){let n=Ql(t.colorSystem),{time:r}=t,i=1/0,a=[...gp(e,{maxWidth:t.width??80,isTerminal:!1,asciiOnly:!1,theme:dS,colorSystem:n.colorSystem,...r===void 0?{}:{frame:{time:r,host:HS}},onStyleError:e=>{throw e},onHold:({nextChange:e})=>{i=Math.min(i,e)}})];return{lines:PS(a,n.colorSystem),nextChange:Math.min(W.nextChange(a),i)}}const WS=new Map;function GS(e){let t=WS.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}=Ch.plain,a=new qm({glyph:n(r.glyph),ascii:r.ascii},i);return WS.set(e,a),a}function KS(e,t){return e===`plain`&&t!==void 0?GS(t):Ch[e]}const qS=new Map;function JS(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=qS.get(t);if(n!==void 0)return n;let r=KS(e.endcaps,e.separator),i=e=>new K(`x`,{end:``,overflow:`ignore`,style:new U({bgcolor:e})}),a=e=>{let{lines:t}=US(new xm(e,r),{colorSystem:null});return new K(VS(t.flat())).cellLength},o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return qS.set(t,s),s}function YS(e){return JS(e).chrome}function XS(e){return JS(e).seam}const ZS=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function QS(e){return[...new Set(e.match(ZS)??[])].join(``)}function $S(e){let t=KS(e.endcaps,e.separator),n=e=>new K(`x`,{end:``,style:new U({bgcolor:e})}),{lines:r}=US(new xm([n(`#101010`),n(`#202020`)],t),{colorSystem:null});return QS(VS(r.flat()))}function eC(e){return e.wrap?e.width:1/0}function tC(e,t){return US(new K(e,{overflow:`fold`,end:``}),{colorSystem:null,width:t}).lines.map(VS)}function nC(e,t,n=pS){if(e.length===0)return{lines:[[]],nextChange:1/0};let r=KS(t.endcaps,t.separator),i=Number.isFinite(eC(t)),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new R_([...e],{joiner:r}):new xm([...e],r),s=n.kind===`still`?US(o,a):US(n.wrap(o),{...a,time:n.time});if(s.lines.length===0)throw Error(`drawStripCells: rich-js strip drew no line`);return s}function rC(e,t){return IS(nC(e,t).lines,t.colorCompatibility)}const iC={level:`error`,glyph:`⚠`,colors:oS},aC={level:`warning`,glyph:`⚠`,colors:sS},oC={level:`warning`,glyph:`⬆`,colors:sS},sC={level:`warning`,glyph:`🔒`,colors:sS},cC={level:`warning`,glyph:`🧪`,colors:sS};function lC(e,t){return{text:iS(e),link:t}}function uC(e,t,n,r,i){let a=new Set,o=(e,t)=>{let n=dC(e,t);for(let e of n)a.add(e);return n},s=[...n.flatMap(e=>o(e,iC)),...r,...i.flatMap(e=>o(e,aC))],c=fC(s);return s.map((n,r)=>a.has(n)?{...n,lines:[[lC(n.lines[0][0].text,pC(e,t,c[r],r+1))],...n.lines.slice(1)]}:n)}function dC({about:e,text:t,copy:n},r){let[i,...a]=t.split(/\r\n|\r|\n/).map(e=>lC(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 fC(e){return _C(e).map(e=>String(e*hC+1))}function pC(e,t,n,r){return Ea([{verb:ha,args:[e,t,n]}],`copy diagnostic ${r}`)}function mC(e){return e.length===0?null:e.some(e=>e.severity.level===`error`)?`error`:`warning`}const hC=4096;function gC(e){let t=w(`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 _C(e){let t=new Map;return e.map(e=>{let n=gC(e),r=t.get(n)??0;return t.set(n,r+1),n*256+Math.min(r,255)})}function vC(e,t,n){return String(_C(e)[t]*hC+n+1)}const yC={error:oS,warning:sS};function bC(e){let t=mC(e),n=e.length,r=yC[t??`warning`];return{label:t===null?``:`⚠ ${n>9?`9+`:n}`,fg:r.fg,bg:r.bg,open:e.length===0?`0`:vC(e,0,0)}}function xC(e,t){let n=Number(e)-1,r=_C(t).indexOf(Math.floor(n/hC));return e===null||r===-1?null:{index:r+1,page:n%hC}}function SC(e,t){return Math.min(20,e??20,...t)}function CC(e,t,n,r,i){let{index:a}=t,o=e[a-1],s=EC(i),c=kC(o,s,[]),l=new U({bgcolor:o.severity.colors.bg,color:o.severity.colors.fg}),u=(e,t)=>DC(e,t===null?l:l.withLink(t)),d=(t,r)=>r===null?u(` `,null):u(t,TC(n,vC(e,r.index-1,r.page),`show diagnostic ${r.index} of ${e.length} page ${r.page+1}`)),f=(t,i)=>{let o=i>0?{index:a,page:i-1}:a>1?{index:a-1,page:0}:null,c=i<t-1?{index:a,page:i+1}:a<e.length?{index:a+1,page:0}:null,l=e.length>1||t>1,f=t>1?`[${a}/${e.length} ${i+1}/${t}]`:`[${a}/${e.length}]`;return OC([u(`✕`,TC(n,`0`)),...l?[d(`‹`,o)]:[],u(f,null),...l?[d(`›`,c)]:[],u(`⧉ copy`,pC(n,r,vC(e,a-1,0),a))],s)},p=1;for(;;){let e=Math.max(1,i.rows-p),n=Math.min(hC,Math.ceil(c.length/e)),r=Math.min(t.page,n-1),a=f(n,r);if(a.length>p){p=a.length;continue}let o=c.slice(r*e,(r+1)*e),l=c.length-(r+1)*e,d=r===n-1&&l>0?[...o.slice(0,-1),...OC([u(`… ${l+1} more rows: ⧉ copy has them all`,null)],{...s,wrap:!1})]:o;return[...a,...d]}}function wC(e,t,n,r){let{label:i,fg:a,bg:o,open:s}=bC(t),c=i===``?[]:[DC(i,new U({bgcolor:o,color:a}).withLink(TC(n,s)))];return kC(e,EC(r),c)}function TC(e,t,n){return Ea([{verb:Wi,args:[e,Vi,t]}],n)}function EC(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,colorCompatibility:e.colorCompatibility}}const DC=(e,t)=>new K(`${e} `,{style:t,end:``,overflow:`ignore`}),OC=(e,t)=>nC(e,t).lines.map(e=>({kind:`diagnostic`,runs:e}));function kC(e,t,n){let r=new U({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),i=e=>e===null?r:r.withLink(e),a=bl(Math.max(2,t.width-1));return e.lines.flatMap((o,s)=>{let c=DC(s===0?e.severity.glyph:` `,r),l=o.flatMap(e=>e.text.split(` `).flatMap(e=>Tl(e,a)).map(t=>DC(t,i(e.link)))),u=s===0?n:[];return OC([c,...l,...u],t)})}function AC(e,t){let n=w(`sha256`).update(t).digest(`hex`).slice(0,16);return o.join(e,`update-act`,n)}const jC={kind:`idle`};function MC(e){if(e===null)return jC;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 NC=e=>({stdout:o.join(e,`stdout`),stderr:o.join(e,`stderr`),status:o.join(e,`status`)}),PC=e=>o.join(e,`record.json`);function FC(e){let t;try{t=f.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 IC(e){let t=qo(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 LC(e,t){let n=o.join(e,`.removed-${t}-${process.pid}`);try{f.renameSync(o.join(e,String(t)),n)}catch(e){if(e.code===`ENOENT`)return;throw e}f.rmSync(n,{recursive:!0,force:!0})}const RC=()=>Date.now()-D.uptime()*1e3;async function zC(e,t,n=RC()){if(e.started<=n||!Un(e.pid))return!1;let r=await t(e.pid);return e.startTime===null||r.kind===`unavailable`||r.token===e.startTime}function BC(e){try{return JSON.parse(f.readFileSync(PC(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}const VC=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function HC(e,t){let n=null;async function r(r){let i=o.join(e,String(r)),a=BC(i);if(a===null)return null;if((n===null||!VC(n.record,a))&&(n={record:a,ours:await zC(a,t),final:null}),n.final!==null)return n.final;n.ours=n.ours&&Un(a.pid);let s=NC(i),c=Vn(s.status),l=c===null?null:IC(s.stderr)??IC(s.stdout);if(!f.existsSync(i))return null;let u={act:r,record:a,alive:n.ours,end:c,lastLine:l};return u.alive||(n.final=u),u}return{async read(){let t=null;for(;;){let n=FC(e).at(-1);if(n===void 0)return null;if(n===t)throw Error(`${o.join(e,String(n))}: an act with no record`);let i=await r(n);if(i!==null)return i;t=n}}}}function UC(e,t,n){f.mkdirSync(e,{recursive:!0});let r=f.mkdtempSync(o.join(e,`.claim-`));try{return f.writeFileSync(PC(r),JSON.stringify(n)),f.renameSync(r,t),!0}catch(e){let t=e.code;if(t===`ENOTEMPTY`||t===`EEXIST`)return!1;throw e}finally{f.rmSync(r,{recursive:!0,force:!0})}}async function WC(e,t,n,r,i,a,s,c){let l=(n??0)+1,u=o.join(t,String(l)),d=e.launchJobSync(i,NC(u));if(!d.ok)throw Error(`apply-update: ${d.error}`);let f=!1;try{let e=await c(d.pid);if(!UC(t,u,{identity:r,pid:d.pid,startTime:e.kind===`start`?e.token:null,started:s,deadline:s+a}))return GC;if(FC(t).some(e=>e>l))return LC(t,l),GC;f=!0}finally{f?d.release():d.withdraw()}for(let e of FC(t).filter(e=>e<l))LC(t,e);return{ok:!0,act:l}}const GC={ok:!1,reason:`another act claimed this bundle first`};function KC(e,t){let n=NC(o.join(e,String(t.act))).status;return Gn(t.record.pid,n,{kind:`timeout`})}var qC=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)})}},Y=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}},JC=class extends Error{constructor(e){super(`the daemon closed: ${e} refused`),this.name=`DaemonClosing`}},YC=class extends Error{constructor(e){super(`the client left: ${e} not run`),this.name=`ClickAbandoned`}};function XC(e){try{return e()}catch(e){throw e instanceof URIError?new Y(`malformed wire encoding: ${e.message}`):e}}const ZC=new Map;function QC(e){let t=ew(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 $C(e,t){return e===`bar`?t:QC(e)}function ew(e){let t=ZC.get(e);if(t!==void 0)return t;let n=Jd(e);return n===null?null:(ZC.set(e,n),n)}function tw(e,t){return nw(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>sf(e,t))}const nw=z_();function rw(e){let t=ew(e);return t===null?null:{kind:`decided`,name:e,value:t}}function iw(e,t,n){let r=rw(e);return r===null?(n(Oy(t,`palette`,`"${e}" names no installed theme${dy(e)}`)),ow()):r}function aw(e,t,n){return xy(e,t,n,ow(),rw)}function ow(){return{kind:`decided`,name:fy,value:QC(fy)}}const sw=/^[A-Za-z_][A-Za-z0-9_]*$/;function cw(e){return`#${e+1}`}const lw={rows:{}};function uw(e){return`rows`in e}function dw(e){return Object.fromEntries(e.map((e,t)=>[cw(t),e]))}function fw(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:dw(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:dw([n])}}function pw(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function mw(e){return uw(e)?pw(e):e}function*hw(e,t){if(!uw(e)){yield*ab(e,t);return}yield[pw(e),t];for(let[n,r]of Object.entries(e.rows))yield*ab(r,`${t}.rows.${n}`)}function gw(e,t){return uw(e)?{...t,...e,rows:{...t.rows,...e.rows}}:fw(e)}function _w(e,t){return t.reduce((e,t)=>{let n=t.id??t.seg,r=[...nb(pw(e.root))].flatMap(e=>e.kind===`segment`?[e]:[]);if(r.some(e=>e.name===t.seg&&(t.id===void 0||Qy(e)===t.id)))return e;let i=r.find(e=>Qy(e)===n);if(i!==void 0)return vw(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,yw(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]))}}:vw(e,t,`${t.relation} "${t.anchor}", but there is no placement "${t.anchor}"`)},{root:e,unplaced:[]})}function vw(e,t,n){return{...e,unplaced:[...e.unplaced,{cell:t,reason:n}]}}function yw(e,t,n,r){if(e.kind===`segment`&&Qy(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`?bw(e,t,n,r):xw(e,t,n,r)}function bw(e,t,n,r){let i=e.children.findIndex(e=>e.kind===`segment`&&Qy(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`?bw(a,t,n,r):xw(a,t,n,r);if(o!==null)return{...e,children:e.children.map((e,t)=>t===i?o:e)}}return null}function xw(e,t,n,r){let i=!1,a=tb(e,e=>{let a=bw(e,t,n,r);return i=a!==null,a??e});return i?a:null}function Sw(e){if(!uw(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const Cw=`default`,ww={};function Tw(e){return[...new Set([Cw,...Object.keys(e)])]}function Ew(e,t,n){return vy(void 0,e,t,Cw,n)}function Dw(e,t){let n={[Cw]:ww,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${Cw}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function Ow(e,t){let n=Dw(e.presets,t).root??lw;return{node:pw(gw(n,e.root)),path:Sw(n)?`presets.${t}.root`:`root`}}function kw(e,t,n){if(t.length===0)return{config:e,notices:[]};let r=_w(e.root,t),i=Object.entries(e.presets).filter(([,e])=>Sw(e.root??lw)).map(([n,r])=>({name:n,preset:r,..._w(gw(r.root??lw,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:pw(n)}]))}},notices:[...a].flatMap(([e,t])=>[...t].map(([t,n])=>Aw(e,`${t} (in ${n.join(`, `)})`)))}}function Aw(e,t){return`${e.by.file}: ${e.by.entry} places "${e.seg}" ${t}`}function jw(e,t){return{...e.globals,...Dw(e.presets,t).globals}}const Mw=new Map;function Nw(e,t,n={}){Mw.set(e,{permanent:!0,resolve:t,...n})}Nw(`themes`,()=>my(),{paletteOf:e=>QC(e)});const Pw=`placementThemes`;Nw(Pw,hy,{paletteOf:(e,t)=>$C(e,t.palette)});for(let{name:e,members:t,library:n,labelOf:r}of Hx)Nw(e,()=>t,{library:n,labelOf:r});function Fw(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>tw(n.basePalette,e.styles[t])}],[`presets`,{members:Tw(e.presets)}]])}function Iw(e){return[...new Set([...Mw.keys(),...e.keys()])]}function Lw(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=Mw.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf,library:r.library,labelOf:r.labelOf};throw Error(zw(e,t))}const Rw=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function zw(e,t){let n=Rw.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${Iw(t).join(`, `)})`}const Bw=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`slash`,`run`,`do`];function Vw(e){return JSON.stringify([e.run,Object.entries(e.env),e.cwd,e.refreshes])}function*Hw(e){let t=[];Uw(e,(e,n)=>(t.push([n,e]),e)),yield*t}function Uw(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 Ww(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}const Gw=[`plugins`,`repo`];function Kw({scope:e,name:t}){return`${e}.${t}`}function qw(e){return t=>t===e||t.startsWith(`${e}.`)}const Jw=`self`;function Yw(e){return Gw.find(t=>e===t||e.startsWith(`${t}.`))}function Xw(e,t){let n=Yw(e);if(n===void 0||n===e)return``;let r=Gw.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 Zw=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*Qw(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 $w=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,eT=RegExp(`^(?:(\\$)(?:\\.(${$w}))?|\\.(${$w})?)(?=[\\s)]|$)`);function tT(e,t,n){let r=eT.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 nT=/^(\w+)\b\s*([\s\S]*)$/;function*rT(e,t){let n=[t];for(let r of Qw(e)){let e=r.text.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=nT.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:tT(i[1],s,t);continue}yield{code:e,dot:o,block:r},i===`if`&&n.push(o),i===`with`&&n.push(tT(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const Kee=/(?<![.$])\btemplate\s+$/;function*iT(e,t,n){let r=0;for(let i of[...e.matchAll(Zw)]){let a=i.index+i[0].length;Kee.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:tT(e.slice(a),t,n),index:i.index}),r=a}}function*qee(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...rT(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...iT(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 aT(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const oT=new WeakMap;function sT(e,t){let n=oT.get(t);return n===void 0&&(n=aT(e=>[...qee(e,t)]),oT.set(t,n)),n(e)}const Jee=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${$w})`,`g`);function*Yee({code:e,dot:t,root:n}){let r=e.replace(Zw,``);for(let e of[...r.matchAll(Jee)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function cT(e,t){let n=new Map;for(let r of sT(e,t))for(let e of Yee(r))n.has(e)||n.set(e,r.via);return n}const Xee=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,lT={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*uT(e){let t=0,n=0,r=`action`;for(let i of[...e.matchAll(Zw)]){let a=e.slice(t,i.index),o=Xee.exec(a);o===null?a.trim()!==``&&(n=0):(n=lT[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 dT(e,t){let n=new Map;for(let{code:r,via:i}of sT(e,t))for(let{name:e,site:t}of uT(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}const fT=e=>Object.keys(lT).filter(t=>lT[t]>=e).join(`|`),Zee=RegExp(`(?<![\\w.$])(?:(?:${fT(1)})\\s+|(?:${fT(2)})\\s+""\\s+)(?=[^\\s"\`)|}])`);function Qee(e,t){for(let{code:n}of sT(e,t))if(Zee.test(n.replace(Zw,`""`)))return!0;return!1}const $ee=/(?<![\w.$])[A-Za-z_]\w*/g;function ete(e,t){let n=new Set;for(let{code:r}of sT(e,t))for(let[e]of r.replace(Zw,``).matchAll($ee))n.add(e);return n}function tte(e,t){return new Set([...pT(e,t)].filter(e=>Object.hasOwn(t,e)))}function pT(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of sT(e,t))for(let{name:e}of iT(r,i,a))n.add(e);return n}const nte=e=>RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.${e}(?![A-Za-z0-9_])`,`g`);function rte(e,t,n){let r=nte(t),i=qw(t),a=[];for(let{dot:t,block:n}of rT(e,``)){let e=n.text.replace(Zw,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[...iT(n.text,t,``),...uT(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*mT(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*hT(e){for(let[t,n]of mT(e))yield[t,n]}function gT(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 _T(e,t){return gT(e,t.names).some(n=>!e.startsWith(`${n}.`)||t.documents.has(n))}function vT(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),ite(r)&&n.add(e)};for(let[t,n]of hT(e))r(t,n);return{names:t,documents:n,helpers:e.helpers}}function ite(e){return e.kind===`dropped`||e.kind===`source`||(e.kind===`shell`||e.kind===`file`)&&sb(e.parse)===`json`}function yT(e){let t=o.basename(e),n=o.dirname(e);for(;;){let r=bT(n);if(r!==null)return{dir:r,name:t,leaf:n===o.dirname(e)};t=o.basename(n),n=o.dirname(n)}}function bT(e){try{return f.statSync(e).isDirectory()?f.realpathSync(e):null}catch{return null}}const ate=(e,t)=>k(t);function xT(e){let t=[],n=!0,r=new Map;for(let i of e.named){let{hops:e,stopped:a}=ut(i);a!==null&&t.push({path:i,reason:a.message});for(let t of e){let{dir:e,name:i,leaf:a}=yT(t);n&&=a;let o=r.has(e)?r.get(e):new Set;o?.add(i),r.set(e,o)}}for(let t of e.whole.map(bT))t!==null&&r.set(t,null);let i={dirs:[...r.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})},a=new Map(i.dirs.map(e=>{let t=Yc(e.path);return[e.path,Zc(t)?Xc(t):null]}));return{key:JSON.stringify([i,[...a]]),targets:i,unbound:[...a.values()].includes(null),bound:a,reached:n,unresolved:t}}function ST(e,t,n){let r=[...t.derived.unresolved.map(e=>`cannot follow a link chain — ${e.reason}`),...t.held.handle.deaf.map(e=>e.kind===`refused`?`cannot watch ${e.path} — ${e.reason}`:`watching ${e.path} failed — ${e.reason}`),...n===null?[]:[n]];return r.length===0?null:`${e}: ${r.join(`; `)}`}function CT(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 wT=(e,t)=>t===null?{kind:`unknown`}:{kind:`changed`,paths:new Set([o.join(e,t)])},TT=e=>({kind:`failed`,reason:`${e.path}: ${e.reason}`}),ET=(e,t)=>e.kind===`listening`&&e.handle===t,DT=e=>`${e.recursive===!0?`tree`:`dir`}:${e.path}`;var OT=class{slots=new Map;dirs=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??ate}acquire(e,t,n){if(this.closed)return{release:()=>{},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)}return this.slots.set(e,n),this.counters&&(n.listeners.every(e=>e.dir.state.kind===`listening`)?this.counters.watchersOpened++:this.counters.watchRefusals++),n}dirFor(e){let t=DT(e),n=this.dirs.get(t);if(n!==void 0)return this.judged(n,`acquire`),n;let r={path:e.path,recursive:e.recursive===!0},i={id:t,...r,listeners:new Set,state:this.open(r,()=>i,`acquire`,null)};return this.dirs.set(t,i),i}judged(e,t){if(e.state.kind===`deaf`){this.reopen(e,t);return}let n=Yc(e.path);Zc(n)&&Xc(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),e.state.kind===`listening`?this.tell(e,{kind:`unknown`}):n.kind===`listening`&&this.tell(e,TT(e.state.deafness))}open(e,t,n,r){let i=e.path,a=Xc(Yc(i));try{f.opendirSync(i).closeSync();let r=f.watch(i,{persistent:!1,recursive:e.recursive},(e,n)=>this.heard(t(),r,n));return r.on(`error`,e=>{this.logger(`warn`,`watcher error ${i}: ${e.message}`),this.counters&&this.counters.watchErrors++;let n=t();if(!ET(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,TT(a))}),this.counters&&this.counters.dirWatchesOpened++,this.logger(`info`,`dir watch opened path=${R(i)} cause=${R(n)}`),{kind:`listening`,handle:r,bound:a}}catch(e){let t=e.message;return r?.kind===`deaf`&&r.deafness.kind===`refused`&&r.deafness.reason===t||this.logger(`warn`,`watch failed ${i}: ${t}`),{kind:`deaf`,deafness:{kind:`refused`,path:i,reason:t}}}}heard(e,t,n){let{state:r}=e;if(!ET(r,t))return;let i=n===o.basename(e.path)&&Xc(Yc(e.path))!==r.bound;for(let{slot:t,filter:r}of e.listeners)(r===null||n===null||r.has(n)||i)&&this.fire(t,wT(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=CT(e.debounce.window,t);return}let n={window:t,timer:setTimeout(()=>{e.debounce=null;for(let t of e.holders)try{t.onInvalidate(n.window)}catch(t){this.logger(`warn`,`watcher invalidate threw key=${R(e.key)}: ${t.message}`)}},50)};n.timer.unref(),e.debounce=n}makeHandle(e,t){return{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=${R(e)} cause=${R(n)}`)}closeSlot(e,t){e.debounce!==null&&(clearTimeout(e.debounce.timer),e.debounce=null);for(let n of e.listeners){let{dir:e}=n;e.listeners.delete(n),!(e.listeners.size>0)&&(e.state.kind===`listening`&&this.closeHandle(e.path,e.state.handle,t),this.dirs.delete(e.id))}this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}dirWatches(){return[...this.dirs.values()].filter(e=>e.state.kind===`listening`).length}watchedDirs(){return[...this.dirs.values()].map(e=>e.path)}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e,`close`);this.slots.clear()}},kT=Ae((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()===Vt}function s(e){let t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function c(e,t,n){Lt(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 Rt.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=Ht,n=Ht){let r=new Gt(e);return t!==Ht&&(r.onBOL=new Set([t])),n!==Ht&&(r.onBUOL=new Set([n])),r}function _(e,t){return At(e,t)}function v(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||$e(e)?e:Array.isArray(e)?cn.array(e,{name:n}):o(e)?cn.object(e,void 0,{name:n}):u(e)?cn.map(e,{name:n}):d(e)?cn.set(e,{name:n}):typeof e!=`function`||He(e)||Xe(e)?e:s(e)?Kn(e):Rn(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:He(n.value)?1:(Lt(r,t,ee(e,this,t,n,!1)),2)}function S(e,t,n,r){let i=ee(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 _e(s.i?.name??a.toString(),e,(t=s.i?.autoAction)!=null&&t)};return i==`field`?function(e){var t;let n=e;return He(n)||(n=c(n)),(t=s.i)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n}:i==`method`?(He(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 ee(e,t,n,r,i=M.safeDescriptors){var a,o,s;let{value:c}=r;return(a=t.i)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:_e(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 te(e,t){return{t:e,i:t,o:w,u:ne}}function w(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)||!Xe(e.h[t]))&&this.u(e,t,n,!1)===null?0:Xe(n.value)?1:(Lt(r,t,re(e,0,0,n,!1,!1)),2)}function ne(e,t,n,r){let i=re(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function T(e,t,n){var r;let{name:i,addInitializer:a}=n;return Xe(t)||(t=Kn(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 re(e,t,n,r,i,a=M.safeDescriptors){let{value:o}=r;return Xe(o)||(o=Kn(o)),i&&(o=o.bind(e.v??e.h),o.isMobXFlow=!0),{value:o,configurable:!a||e.p,enumerable:!1,writable:!a}}function E(e,t){return{t:e,i:t,o:D,u:ie}}function D(e,t,n){return this.u(e,t,n,!1)===null?0:1}function ie(e,t,n,r){return e.m(t,Ft({},this.i,{get:n.get,set:n.set}),r)}function O(e,t,n){function r(e){let n=Ft({},i.i,{get:t,context:e});return n.name||=`ObservableObject.${a.toString()}`,new bn(n)}let i=e,{name:a,addInitializer:o}=n,s;return o(function(){let e=Ct(this)[A],n=this,i=e.j.get(a);i instanceof bn&&i.derivation!==t&&e.j.delete(a),(e.O??=new Map).set(a,()=>r(n))}),function(){let e=this[A],n=e.j.get(a);if(n instanceof bn&&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 ae(e,t){return{t:e,i:t,o:oe,u:se}}function oe(e,t,n){return this.u(e,t,n,!1)===null?0:1}function se(e,t,n,r){return e.S(t,n.value,this.i?.A??v,r)}function ce(e,t,n){function r(e,t){let n=Ct(e)[A];return(n.V??=new Map).set(o,()=>new vn(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[A]??r(this,t.get.call(this)))._(o)},set(e){return(this[A]??r(this,e)).M(o,e)},init(e){return r(this,e),e}}}function le(e){return{t:Yt,i:e,o:ue,u:de}}function ue(e,t,n,r){var i,a,o;if(n.get)return fn.o(e,t,n,r);if(n.set){let i=He(n.set)?n.set:_e(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!M.safeDescriptors||e.p,set:i})===null?0:2:(Lt(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?qn:Kn).o(e,t,n,r):((a=this.i)!=null&&a.autoBind?Bn:Rn).o(e,t,n,r);let c=!1===this.i?.deep?rn:cn;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 de(e,t,n,r){var i;return n.get?fn.u(e,t,n,r):n.set?e.l(t,{configurable:!M.safeDescriptors||e.p,set:_e(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?rn:cn).u(e,t,n,r))}function fe(e,t){return Ft(function(n,r){if(r&&typeof r.kind==`string`)return t(e,n,r)},e)}function pe(e){return e||Zt}function me(e){return fe(e,ce)}function he(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 ge(e){return fe(e,O)}function _e(e,t,n=!1,r){function i(){return ve(0,n,t,r||this,arguments)}return i.isMobxAction=!0,i.toString=()=>t.toString(),gn&&(_n.value=e,Lt(i,`name`,_n)),i}function ve(e,t,n,r,i){let a=ye(0,t);try{return n.apply(r,i)}catch(e){throw a.N=e,e}finally{be(a)}}function ye(e,t){let n=M.trackingDerivation,r=!t||!n;Ne();let i=M.allowStateChanges;r&&De();let a={R:r,k:n,C:i,I:M.allowStateReads,P:!1,T:0,B:hn++,D:mn};return mn=a.B,a}function be(e){mn!==e.B&&t(30),mn=e.D,e.N!==void 0&&(M.suppressReactionErrors=!0),Pe(),e.R&&Oe(e.k),M.suppressReactionErrors=!1}function xe(e,t){let n=function(e){let t=M.allowStateChanges;return M.allowStateChanges=e,t}(e);try{return t()}finally{(function(e){M.allowStateChanges=e})(n)}}function Se(e){return e instanceof Sn}function Ce(e){switch(e.K){case 0:return!1;case-1:case 2:return!0;case 1:{let t=De(),n=e.L,r=n.length;for(let i=0;i<r;i++){let r=n[i];if(xn(r)){if(M.disableErrorBoundaries)r.get();else try{r.get()}catch{return Oe(t),!0}if(e.K===2)return Oe(t),!0}}return ke(e),Oe(t),!1}}}function we(e,t,n){ke(e),e.$=Array(e.U===0?100:e.L.length),e.W=0,e.U=++M.runId;let r=M.trackingDerivation,i;if(M.trackingDerivation=e,M.inBatch++,!0===M.disableErrorBoundaries)i=t.call(n);else try{i=t.call(n)}catch(e){i=new Sn(e)}return M.inBatch--,M.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&&je(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,Ae(t,e))}r!==0&&(e.K=r,e.q())}(e),i}function Te(e){let t=e.L;e.L=[];let n=t.length;for(;n--;)je(t[n],e);e.K=-1}function Ee(e){let t=De();try{return e()}finally{Oe(t)}}function De(){let e=M.trackingDerivation;return M.trackingDerivation=null,e}function Oe(e){M.trackingDerivation=e}function ke(e){if(e.K===0)return;e.K=0;let t=e.L,n=t.length;for(;n--;)t[n].F=0}function Ae(e,t){(e.H??=new Set).add(t),e.F>t.K&&(e.F=t.K)}function je(e,t){let n=e.H;n&&(n.delete(t),n.size===0&&Me(e))}function Me(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,M.pendingUnobservations.push(e))}function Ne(){M.inBatch++}function Pe(){--M.inBatch===0&&(Le(),!M.isRunningUnobservations&&M.pendingUnobservations.length>0&&function(){M.isRunningUnobservations=!0;try{let e=M.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 bn&&n.G())}M.pendingUnobservations=[]}finally{M.isRunningUnobservations=!1}}())}function k(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.L)==null||t.forEach(k))}function Fe(e){let t=M.trackingDerivation;return t===null?((!e.H||e.H.size===0)&&M.inBatch>0&&Me(e),!1):(t.U!==e.J&&(e.J=t.U,t.$[t.W++]=e,!e.isBeingObserved&&M.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function Ie(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 Le(){M.inBatch>0||M.isRunningReactions||kn(Re)}function Re(){M.isRunningReactions=!0;let e=M.pendingReactions,t=0;for(;e.length>0;){++t===On&&(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()}M.isRunningReactions=!1}function ze(e){return fe(e,C)}function Be(e){return function(t,n){return n&&typeof n.kind==`string`?C(e?Fn:Nn,t,n):r(t)?_e(t.name||`<unnamed action>`,t,e):r(n)?_e(t,n,e):i(t)?ze(b(e?Mn:jn,{name:t,autoAction:e})):void 0}}function Ve(e){return ve(0,!1,e,this,void 0)}function He(e){return r(e)&&!0===e.isMobxAction}function Ue(e,t=Bt){function n(){e(a)}var r;let i=t?.name??`Autorun`,a;if(t.scheduler||t.delay){let e=We(t),r=!1;a=new Dn(i,()=>{r||(r=!0,e(()=>{r=!1,a.isDisposed||a.track(n)}))},t.onError,t.requiresObservable)}else a=new Dn(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 We(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Vn}function Ge(e,t,n,i){let a=typeof i==`function`?Et(t,n):Et(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 Ke(e,t,n,r){let i=Wt(t);return kt(()=>{let t=Ct(e,r)[A];Ut(i).forEach(e=>{t.u(e,i[e],!n||!(e in n)||n[e])})}),e}function qe(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(qe)),t}function Je(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),Je)),t}function Ye(e){r(e.cancel)&&e.cancel()}function Xe(e){return!0===e?.isMobXFlow}function Ze(e,t){var n;if(t===void 0)return xn(e);if(!1===Tt(e))return!1;let r=e[A];return(n=r.O)!=null&&n.has(t)?!0:r.j.has(t)?xn(Et(e,t)):!1}function Qe(e,t){if(!e)return!1;if(t!==void 0){if(Tt(e)){var n,r;let i=e[A];return i.j.has(t)||!((n=i.O)==null||!n.has(t))||!((r=i.V)==null||!r.has(t))}return!1}return Tt(e)||!!e[A]||Kt(e)||An(e)||xn(e)}function $e(e){return Qe(e)}function et(e){return Tt(e)?e[A].nt():ar(e)||cr(e)?Array.from(e.keys()):bt(e)?e.map((e,t)=>t):void t(5)}function tt(e,n){return Tt(e)?e[A].et(n):ar(e)||cr(e)?e.has(n):bt(e)?n>=0&&n<e.length:void t(10)}function nt(e){if(Tt(e))return e[A].it();t(38)}function rt(e,t,n){if(xn(e)){let r,i=!0;return Ue(()=>{let a=e.get();if(!i||n){let n=De();t({observableKind:`computed`,debugObjectName:e.tt,type:Zn,object:e,newValue:a,oldValue:r}),Oe(n)}i=!1,r=a})}return n&&t({observableKind:`value`,debugObjectName:e.tt,object:e,type:Zn,newValue:e.rt,oldValue:void 0}),pt(e,t)}function it(e,t,n){return e.set(t,n),n}function at(e,t){if(typeof e!=`object`||!e||e instanceof Date||!$e(e))return e;if(yn(e)||xn(e))return at(e.get(),t);if(t.has(e))return t.get(e);if(bt(e)){let n=it(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=at(e,t)}),n}if(cr(e)){let n=it(t,e,new Set);return e.forEach(e=>{n.add(at(e,t))}),n}if(ar(e)){let n=it(t,e,new Map);return e.forEach((e,r)=>{n.set(r,at(e,t))}),n}{let n=it(t,e,{});return nt(e).forEach(r=>{Rt.propertyIsEnumerable.call(e,r)&&(n[r]=at(e[r],t))}),n}}function ot(e,t){Ne();try{return e.apply(t)}finally{Pe()}}function st(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)throw e;n.onError(e)}},n.timeout)}n.name=`When`;let i=_e(`When-effect`,t);var a=Ue(t=>{xe(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function ct(e){return e[A]}function lt(e){return e.st!==void 0&&e.st.length>0}function ut(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 dt(e,n){let r=De();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{Oe(r)}}function ft(e){return e.ot!==void 0&&e.ot.length>0}function pt(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 mt(e,t){let n=De(),r=e.ot;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Oe(n)}}function ht(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!==Rt;){let t=It(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 gt(e,t){typeof Array.prototype[e]==`function`&&(er[e]=t(e))}function _t(e){return function(){let t=this[A];t.ct.reportObserved();let n=t.ht(t.j);return n[e].apply(n,arguments)}}function vt(e){return function(t,n){let r=this[A];return r.ct.reportObserved(),r.ht(r.j)[e]((e,r)=>t.call(n,e,r,this))}}function yt(e){return function(){let t=this[A];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 bt(e){return a(e)&&tr(e[A])}function xt(e){return e[Symbol.toStringTag]=`MapIterator`,Nt(e)}function St(e){return e[Symbol.toStringTag]=`SetIterator`,Nt(e)}function Ct(e,t){if(p(e,A))return e;let n=t?.name??`ObservableObject`;return c(e,A,new dr(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 j[r]??(j[r]=le({deep:t,autoBind:n}))}(e):void 0}(t))),e}function wt(e){return lr[e]||(lr[e]={get(){return this[A]._(e)},set(t){return this[A].M(e,t)}})}function Tt(e){return!!a(e)&&fr(e[A])}function Et(e,n){if(typeof e==`object`&&e){if(bt(e))return n!==void 0&&t(23),e[A].ct;if(cr(e))return e.ct;if(ar(e)){if(n===void 0)return e.lt;let r=e.ft.get(n)||e.dt.get(n);return r||t(25,n,Ot(e)),r}if(Tt(e)){if(!n)return t(26);let r=e[A],i=r.j.get(n)??r.vt(n)??r.bt(n);return i||t(27,n,Ot(e)),i}if(Kt(e)||xn(e)||An(e))return e}else if(r(e)&&An(e[A]))return e[A];t(28)}function Dt(e,n){return e||t(29),n===void 0?Kt(e)||xn(e)||An(e)||ar(e)||cr(e)?e:e[A]?e[A]:void t(24,e):Dt(Et(e,n))}function Ot(e,t){let n;if(t!==void 0)n=Et(e,t);else{if(He(e))return e.name;n=Tt(e)||ar(e)||cr(e)?Dt(e):Et(e)}return n.tt}function kt(e){let t=De();Ne();try{return e()}finally{Pe(),Oe(t)}}function At(e,t,n=-1){return jt(e,t,n)}function jt(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=pr.call(e);if(s!==pr.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=Mt(e),t=Mt(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(!jt(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)||!jt(e[o],t[o],n-1,i,a))return!1}}return i.pop(),a.pop(),!0}function Mt(e){return bt(e)?e.slice():u(e)||ar(e)||d(e)||cr(e)?Array.from(e.entries()):e}function Nt(e){return e[Symbol.iterator]=Pt,Ft(Object.create(mr),e)}function Pt(){return this}Object.defineProperty(e,`__esModule`,{value:!0});let Ft=Object.assign,It=Object.getOwnPropertyDescriptor,Lt=Object.defineProperty,Rt=Object.prototype,zt=[];Object.freeze(zt);let Bt={};Object.freeze(Bt);let Vt=Object.toString(),Ht=()=>{},Ut=Reflect.ownKeys,Wt=Object.getOwnPropertyDescriptors,A=Symbol(`mobx administration`);var Gt=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 Fe(this)}reportChanged(){Ne(),Ie(this),Pe()}toString(){return this.tt}};let Kt=l(`Atom`,Gt),qt=Object.is,Jt={t:`override`,o:function(){return 0},u:function(){t(44,this.t)}},Yt=`true`,Xt=le(),j=[Xt],Zt={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Zt);let Qt=ae(`observable`),$t=ae(`observable.ref`,{A:y}),en=ae(`observable.shallow`,{A:function(e,t,n){return e==null||Tt(e)||bt(e)||ar(e)||cr(e)?e:Array.isArray(e)?cn.array(e,{name:n,deep:!1}):o(e)?cn.object(e,void 0,{name:n,deep:!1}):u(e)?cn.map(e,{name:n,deep:!1}):d(e)?cn.set(e,{name:n,deep:!1}):void 0}}),tn=ae(`observable.struct`,{A:function(e,t){return At(e,t)?t:e}}),nn={box(e,t){let n=pe(t);return new vn(e,he(n),n.name,!0,n.equals)},array(e,t){let n=pe(t);return function(e,t,n=`ObservableArray`,r=!1){return kt(()=>{let i=new $n(n,t,r);Lt(i.j,A,{enumerable:!1,writable:!1,configurable:!0,value:i});let a=new Proxy(i.j,Qn);return i.v=a,e&&e.length&&i.wt(0,0,e),a})}(e,he(n),n.name)},map(e,t){let n=pe(t);return new ir(e,he(n),n.name)},set(e,t){let n=pe(t);return new sr(e,he(n),n.name)},object:(e,t,n)=>kt(()=>Ke(function(e,t){var n;return(n=(e=Ct(e,t))[A]).v??(n.v=new Proxy(e,Jn))}({},n),e,t))},rn=me($t),an=me(en),on=me(Qt),sn=me(tn);var cn=Ft(function(e,t,n){return t&&typeof t.kind==`string`?ce(Qt,e,t):$e(e)?e:o(e)?cn.object(e,t,n):Array.isArray(e)?cn.array(e,t):u(e)?cn.map(e,t):d(e)?cn.set(e,t):typeof e==`object`&&e?e:cn.box(e,t)},Qt,nn);let ln=`computed`,un=E(ln),dn=ge(E(`computed.struct`,{equals:_})),fn=function(e,t){if(t&&typeof t.kind==`string`)return O(un,e,t);if(o(e))return ge(E(ln,e));let n=o(t)?t:{};return n.get=e,n.name||=e.name||``,new bn(n)};var pn;Ft(fn,un);let mn=0,hn=1,gn=(pn=It(()=>{},`name`)?.configurable)!=null&&pn,_n={value:`action`,configurable:!0,writable:!1,enumerable:!1};var vn=class extends Gt{constructor(e,t,n=`ObservableValue`,r=!0,i=qt){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))!==M.UNCHANGED&&this.Ot(e)}jt(e){if(lt(this)){let t=dt(this,{object:this,type:Zn,newValue:e});if(!t)return M.UNCHANGED;e=t.newValue}return e=this.A(e,this.rt,this.tt),this.xt(this.rt,e)?M.UNCHANGED:e}Ot(e){let t=this.rt;this.rt=e,this.reportChanged(),ft(this)&&mt(this,{type:Zn,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 yn=l(`ObservableValue`,vn);var bn=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 Sn(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=_e(`ComputedValue-setter`,e.set)),this.xt=e.equals||qt,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),M.inBatch!==0||this.H&&this.H.size!==0||this.Mt){let e=this.isBeingObserved;if(Fe(this),Ce(this)){let e=M.trackingContext;e||!this.Mt&&!this.isBeingObserved||(M.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),M.trackingContext=e}else !e&&this.isBeingObserved&&this.L.forEach(k)}else Ce(this)&&(this.Nt(),Ne(),this.rt=this.Rt(!1),Pe());let e=this.rt;if(Se(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||Se(e)||Se(n)||!this.xt(e,n);return r&&(this.rt=n),r}Rt(e){let t;if(this.isComputing=!0,e)t=we(this,this.derivation,this.At);else if(!0===M.disableErrorBoundaries)t=this.derivation.call(this.At);else try{t=this.derivation.call(this.At)}catch(e){t=new Sn(e)}return this.isComputing=!1,t}G(){this.Mt||(Te(this),this.rt=void 0)}Nt(){}toString(){return`${this.tt}[${this.derivation.toString()}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let xn=l(`ComputedValue`,bn);var Sn=class{constructor(e){this.cause=void 0,this.cause=e}};let Cn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var wn=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 Tn=!0,En=!1,M=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Tn=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(Tn=!1),Tn?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new wn):(setTimeout(()=>{En||t(35)},1),new wn)}();var Dn=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,M.pendingReactions.push(this),Le())}X(){if(!this.isDisposed){Ne(),this.isScheduled=!1;let e=M.trackingContext;if(M.trackingContext=this,Ce(this)){this.isTrackPending=!0;try{this.Et()}catch(e){this.Pt(e)}}M.trackingContext=e,Pe()}}track(e){if(this.isDisposed)return;Ne(),this.isRunning=!0;let t=M.trackingContext;M.trackingContext=this;let n=we(this,e,void 0);M.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Te(this),Se(n)&&this.Pt(n.cause),Pe()}Pt(e){if(this.kt)this.kt(e,this);else{if(M.disableErrorBoundaries)throw e;M.suppressReactionErrors||console.error(`[mobx] uncaught error in '${this}'`,e),M.globalReactionErrorHandlers.forEach(t=>t(e,this))}}dispose(){var e;this.isDisposed||(this.isDisposed=!0,(e=this.It)==null||e.call(this),this.isRunning||(Ne(),Te(this),Pe()))}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[A]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.tt}]`}};let On=100,kn=e=>e(),An=l(`Reaction`,Dn),jn=`action`,Mn=`autoAction`,Nn=b(jn),Pn=b(`action.bound`,{bound:!0}),Fn=b(Mn,{autoAction:!0}),In=b(`autoAction.bound`,{autoAction:!0,bound:!0}),Ln=Be(!1);Ft(Ln,Nn);let Rn=Be(!0);Ft(Rn,Fn);let zn=ze(Pn),Bn=ze(In),Vn=e=>e(),Hn=`always`;var Un=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};let Wn=te(`flow`),Gn=te(`flow.bound`,{bound:!0}),Kn=Ft(function(e,t){if(t&&typeof t.kind==`string`)return T(Wn,e,t);let n=e,i=n.name||`flow`,a=function(){let e=arguments,t=Ln(i,n).apply(this,e),a,o,s=new Promise(function(e,n){function s(e){let r;o=void 0;try{r=Ln(i,t.next).call(t,e)}catch(e){return n(e)}l(r)}function c(e){let r;o=void 0;try{r=Ln(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=Ln(i,function(){try{o&&Ye(o);let e=t.return(void 0),n=Promise.resolve(e.value);n.then(Ht,Ht),Ye(n),a(new Un)}catch(e){a(e)}}),s};return a.isMobXFlow=!0,a},Wn),qn=fe(Gn,T),Jn={has:(e,t)=>ct(e).et(t),get:(e,t)=>ct(e).Tt(t),set(e,t,n){var r;return!!i(t)&&((r=ct(e).Bt(t,n,!0))==null||r)},deleteProperty(e,t){var n;return!!i(t)&&((n=ct(e).Dt(t,!0))==null||n)},defineProperty(e,t,n){var r;return(r=ct(e).l(t,n))==null||r},ownKeys:e=>ct(e).it(),preventExtensions(e){t(13)}},Yn=Symbol(`mobx-keys`),Xn=`splice`,Zn=`update`,Qn={get(e,t){let n=e[A];return t===A?n:t===`length`?n.Kt():typeof t!=`string`||isNaN(t)?p(er,t)?er[t]:e[t]:n.Tt(parseInt(t))},set(e,t,n){let r=e[A];return t===`length`?r.Lt(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.Bt(parseInt(t),n),!0},preventExtensions(){t(15)}};var $n=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 Gt(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=zt),lt(this)){let r=dt(this,{object:this.v,type:Xn,index:e,removedCount:t,added:n});if(!r)return zt;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=ft(this),i=r?{observableKind:`array`,object:this.v,type:Zn,debugObjectName:this.ct.tt,index:e,newValue:t,oldValue:n}:null;this.ct.reportChanged(),r&&mt(this,i)}Ft(e,t,n){let r=ft(this),i=r?{observableKind:`array`,object:this.v,debugObjectName:this.ct.tt,type:Xn,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;this.ct.reportChanged(),r&&mt(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(lt(this)){let n=dt(this,{type:Zn,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)}}},er={clear(){return this.splice(0)},replace(e){let t=this[A];return t.wt(0,t.j.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[A];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[A].wt(e,t,n)},push(...e){let t=this[A];return t.wt(t.j.length,0,e),t.j.length},pop(){return this.splice(Math.max(this[A].j.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[A];return t.wt(0,0,e),t.j.length},reverse(){return M.trackingDerivation&&t(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){M.trackingDerivation&&t(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[A],n=t.ht(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};gt(`at`,_t),gt(`concat`,_t),gt(`flat`,_t),gt(`includes`,_t),gt(`indexOf`,_t),gt(`join`,_t),gt(`lastIndexOf`,_t),gt(`slice`,_t),gt(`toString`,_t),gt(`toLocaleString`,_t),gt(`toSorted`,_t),gt(`toSpliced`,_t),gt(`with`,_t),gt(`every`,vt),gt(`filter`,vt),gt(`find`,vt),gt(`findIndex`,vt),gt(`findLast`,vt),gt(`findLastIndex`,vt),gt(`flatMap`,vt),gt(`forEach`,vt),gt(`map`,vt),gt(`some`,vt),gt(`toReversed`,vt),gt(`reduce`,yt),gt(`reduceRight`,yt);let tr=l(`ObservableArrayAdministration`,$n),nr={},rr=`delete`;var ir=class{constructor(e,t=v,n=`ObservableMap`){this.A=void 0,this.tt=void 0,this[A]=nr,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,kt(()=>{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(!M.trackingDerivation)return this.et(e);let t=this.dt.get(e);if(!t){let n=t=new vn(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(lt(this)){let r=dt(this,{type:n?Zn:`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(lt(this)&&!dt(this,{type:rr,object:this,name:e}))return!1;if(this.et(e)){let t=ft(this),n=t?{observableKind:`map`,debugObjectName:this.tt,type:rr,object:this,oldValue:this.ft.get(e).rt,name:e}:null;return ot(()=>{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&&mt(this,n),!0}return!1}Gt(e,t){let n=this.ft.get(e);if((t=n.jt(t))!==M.UNCHANGED){let r=ft(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:Zn,object:this,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&mt(this,i)}}Jt(e,t){ot(()=>{var n;let r=new vn(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=ft(this);n&&mt(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 xt({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 xt({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 ar(e)&&(e=new Map(e)),ot(()=>{o(e)?function(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>Rt.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(){ot(()=>{Ee(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return ot(()=>{let n=function(e){if(u(e)||ar(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`}},ar=l(`ObservableMap`,ir);let or={};var sr=class{constructor(e,t=v,n=`ObservableSet`){this.tt=void 0,this[A]=or,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),kt(()=>{this.ct=g(this.tt),e&&this.replace(e)})}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){ot(()=>{Ee(()=>{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(lt(this)){let t=dt(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){ot(()=>{e=this.A(e,void 0),this.ft.add(e),this.ct.reportChanged()});let t=ft(this);t&&mt(this,t?{observableKind:`set`,debugObjectName:this.tt,type:`add`,object:this,newValue:e}:null)}return this}delete(e){if(lt(this)&&!dt(this,{type:rr,object:this,oldValue:e}))return!1;if(this.has(e)){let t=ft(this),n=t?{observableKind:`set`,debugObjectName:this.tt,type:rr,object:this,oldValue:e}:null;return ot(()=>{this.ct.reportChanged(),this.ft.delete(e)}),t&&mt(this,n),!0}return!1}has(e){return this.ct.reportObserved(),this.ft.has(this.Wt(e))}entries(){let e=this.values();return St({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 St({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 cr(e)&&(e=new Set(e)),Array.isArray(e)||d(e)?ot(()=>{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`}},cr=l(`ObservableSet`,sr);let lr=Object.create(null),ur=`remove`;var dr=class{constructor(e,t=new Map,n,r=Xt){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 Gt(`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 bn)return n.set(t),!0;if(lt(this)){let n=dt(this,{type:Zn,object:this.v||this.h,name:e,newValue:t});if(!n)return null;t=n.newValue}if((t=n.jt(t))!==M.UNCHANGED){let r=ft(this),i=r?{type:Zn,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&mt(this,i)}return!0}Tt(e){return M.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(!M.trackingDerivation)return e in this.h;this.Qt||=new Map;let t=this.Qt.get(e);return t||(t=new vn(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{Ne();let r=this.Dt(e);if(!r)return r;if(lt(this)){let n=dt(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=Ft({},t,{value:r}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else Lt(this.h,e,t);this.Yt(e,t.value)}finally{Pe()}return!0}S(e,t,n,r=!1){try{Ne();let i=this.Dt(e);if(!i)return i;if(lt(this)){let n=dt(this,{object:this.v||this.h,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let a=wt(e),o={configurable:!M.safeDescriptors||this.p,enumerable:!0,get:a.get,set:a.set};if(r){if(!Reflect.defineProperty(this.h,e,o))return!1}else Lt(this.h,e,o);let s=new vn(t,n,`ObservableObject.key`,!1);this.j.set(e,s),this.Yt(e,s.rt)}finally{Pe()}return!0}m(e,t,n=!1){try{Ne();let r=this.Dt(e);if(!r)return r;if(lt(this)&&!dt(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=wt(e),a={configurable:!M.safeDescriptors||this.p,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.h,e,a))return!1}else Lt(this.h,e,a);this.j.set(e,new bn(t)),this.Yt(e,void 0)}finally{Pe()}return!0}Dt(e,t=!1){if(!p(this.h,e))return!0;if(lt(this)&&!dt(this,{object:this.v||this.h,name:e,type:ur}))return null;try{var n;Ne();let r=ft(this),i=this.j.get(e),a;if(i||!r||(a=It(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 vn&&(a=i.rt),Ie(i)),this.lt.reportChanged(),(n=this.Qt)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&mt(this,{type:ur,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{Pe()}return!0}Yt(e,t){var n;let r=ft(this);r&&r&&mt(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(),Ut(this.h)}nt(){return this.lt.reportObserved(),Object.keys(this.h)}};let fr=l(`ObservableObjectAdministration`,dr),pr=Rt.toString,mr=globalThis.Iterator?.prototype||{};e.$mobx=A,e.FlowCancellationError=Un,e.ObservableMap=ir,e.ObservableSet=sr,e.Reaction=Dn,e._allowStateChanges=xe,e._allowStateChangesInsideComputed=Ve,e._allowStateReadsEnd=function(e){M.allowStateReads=e},e._allowStateReadsStart=function(e){let t=M.allowStateReads;return M.allowStateReads=e,t},e._autoAction=Rn,e._autoActionBound=Bn,e._endAction=be,e._getAdministration=Dt,e._getGlobalState=function(){return M},e._interceptReads=function(e,t,n){let r;return ar(e)||bt(e)||yn(e)?r=Dt(e):Tt(e)&&(r=Dt(e,t)),r.dehancer=typeof t==`function`?t:n,()=>{r.dehancer=void 0}},e._isComputingDerivation=function(){return M.trackingDerivation!==null},e._resetGlobalState=function(){let e=new wn;for(let t in e)Cn.indexOf(t)===-1&&(M[t]=e[t]);M.allowStateChanges=!M.enforceActions},e._startAction=ye,e.action=Ln,e.actionBound=zn,e.autorun=Ue,e.compareDefault=qt,e.compareIdentity=function(e,t){return e===t},e.compareShallow=function(e,t){return At(e,t,1)},e.compareStructural=_,e.computed=fn,e.computedStruct=dn,e.configure=function(e){!0===e.isolateGlobalState&&function(){if((M.pendingReactions.length||M.inBatch||M.isRunningReactions)&&t(36),En=!0,Tn){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),M=new wn}}();let{enforceActions:n}=e;if(n!==void 0){let e=n===Hn?Hn:n===`observed`;M.enforceActions=e,M.allowStateChanges=!0!==e&&e!==Hn}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(M[t]=!!e[t])}),M.allowStateReads=!M.observableRequiresReaction,e.reactionScheduler&&function(e){let t=kn;kn=n=>e(()=>t(n))}(e.reactionScheduler)},e.createAtom=g,e.defineProperty=function(e,n,r){if(Tt(e))return e[A].l(n,r);t(39)},e.entries=function(e){return Tt(e)?et(e).map(t=>[t,e[t]]):ar(e)?et(e).map(t=>[t,e.get(t)]):cr(e)?Array.from(e.entries()):bt(e)?e.map((e,t)=>[t,e]):void t(7)},e.extendObservable=Ke,e.flow=Kn,e.flowBound=qn,e.flowResult=function(e){return e},e.get=function(e,n){if(tt(e,n))return Tt(e)?e[A].Tt(n):ar(e)?e.get(n):bt(e)?e[n]:void t(11)},e.getAtom=Et,e.getDebugName=Ot,e.getDependencyTree=function(e,t){return qe(Et(e,t))},e.getObserverTree=function(e,t){return Je(Et(e,t))},e.has=tt,e.intercept=function(e,t,n){return r(n)?function(e,t,n){return ut(Dt(e,t),n)}(e,t,n):function(e,t){return ut(Dt(e),t)}(e,t)},e.isAction=He,e.isBoxedObservable=yn,e.isComputed=function(e){return Ze(e)},e.isComputedProp=function(e,t){return Ze(e,t)},e.isFlow=Xe,e.isFlowCancellationError=function(e){return e instanceof Un},e.isObservable=$e,e.isObservableArray=bt,e.isObservableMap=ar,e.isObservableObject=Tt,e.isObservableProp=function(e,t){return Qe(e,t)},e.isObservableSet=cr,e.keys=et,e.makeAutoObservable=function(e,t,n){return o(e)?Ke(e,e,t,n):(kt(()=>{let r=Ct(e,n)[A];if(!e[Yn]){let t=Object.getPrototypeOf(e),n=new Set([...Ut(e),...Ut(t)]);n.delete(`constructor`),n.delete(A),c(t,Yn,n)}e[Yn].forEach(e=>ht(r,e,!t||!(e in t)||t[e]))}),e)},e.makeObservable=function(e,t,n){return kt(()=>{let r=Ct(e,n)[A];Ut(t).forEach(e=>ht(r,e,t[e]))}),e},e.observable=cn,e.observableDeep=on,e.observableRef=rn,e.observableShallow=an,e.observableStruct=sn,e.observe=function(e,t,n,i){return r(n)?function(e,t,n,r){return rt(Dt(e,t),n,r)}(e,t,n,i):function(e,t,n){let r=Dt(e);if(bt(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(!ar(e)&&!cr(e)&&!Tt(e))return rt(r,t,n);return pt(r,t)}(e,t,n)},e.onBecomeObserved=function(e,t,n){return Ge(`onBO`,e,t,n)},e.onBecomeUnobserved=function(e,t,n){return Ge(`onBUO`,e,t,n)},e.onReactionError=function(e){return M.globalReactionErrorHandlers.push(e),()=>{let t=M.globalReactionErrorHandlers.indexOf(e);t>=0&&M.globalReactionErrorHandlers.splice(t,1)}},e.override=Jt,e.ownKeys=nt,e.reaction=function(e,t,n=Bt){function r(){if(p=!1,h.isDisposed)return;let t=!1,r=d;h.track(()=>{let n=xe(!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=Ln(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=We(n),d,f=!0,p=!1,m=n.equals||qt,h=new Dn(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){Tt(e)?e[A].Dt(n):ar(e)||cr(e)?e.delete(n):bt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=Ve,e.set=function e(n,r,i){if(arguments.length===2&&!cr(n)){Ne();let t=r;try{for(let r in t)e(n,r,t[r])}finally{Pe()}return}Tt(n)?n[A].Bt(r,i):ar(n)?n.set(r,i):cr(n)?n.add(r):bt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(42,r),Ne(),r>=n.length&&(n.length=r+1),n[r]=i,Pe()):t(8)},e.spy=function(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}},e.toJS=function(e){return at(e,new Map)},e.transaction=ot,e.untracked=Ee,e.values=function(e){return Tt(e)?et(e).map(t=>e[t]):ar(e)?et(e).map(t=>e.get(t)):cr(e)?Array.from(e.values()):bt(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 Ft(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let r,i,a=new Promise((n,a)=>{var o;let s=st(e,n,Ft({},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):st(e,t,n||{})}})),AT=Ae((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++j.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=T(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 ee(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let te=Reflect.ownKeys;function w(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function ne(e){return e===null?null:typeof e==`object`?``+e:e}function T(e,t){return o.hasOwnProperty.call(e,t)}let re=Object.getOwnPropertyDescriptors;function E(e,t){return!!(e&t)}function D(e,t,n){return n?e|=t:e&=~t,e}function ie(e,t){t.includes(e.kind)||n(`The decorator applied to '${String(e.name)}' cannot be used on a ${e.kind} element`)}let O=Symbol(`mobx administration`);var ae=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 E(this.flags_,1)}set isBeingObserved(e){this.flags_=D(this.flags_,1,e)}get isPendingUnobservation(){return E(this.flags_,2)}set isPendingUnobservation(e){this.flags_=D(this.flags_,2,e)}get diffValue(){return+!!E(this.flags_,4)}set diffValue(e){this.flags_=D(this.flags_,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return un(this)}reportChanged(){on(),dn(this),sn()}toString(){return this.name_}};let oe=b(`Atom`,ae);function se(e,t=f,n=f){let r=new ae(e);return t!==f&&(r.onBOL=new Set([t])),n!==f&&(r.onBUOL=new Set([n])),r}function ce(e,t){return e===t}function le(e,t){return Li(e,t)}function ue(e,t){return Li(e,t,1)}let de=Object.is;function fe(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||Sr(e)?e:Array.isArray(e)?dt.array(e,{name:n}):g(e)?dt.object(e,void 0,{name:n}):x(e)?dt.map(e,{name:n}):C(e)?dt.set(e,{name:n}):typeof e==`function`&&!Bn(e)&&!pr(e)?_(e)?lr(e):In(n,e):e}function pe(e,t,r){if(e==null||Ai(e)||mi(e)||N(e)||Si(e))return e;if(Array.isArray(e))return dt.array(e,{name:r,deep:!1});if(g(e))return dt.object(e,void 0,{name:r,deep:!1});if(x(e))return dt.map(e,{name:r,deep:!1});if(C(e))return dt.set(e,{name:r,deep:!1});n(`The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets`)}function me(e){return e}function he(e,t){return Sr(e)&&n(`observable.struct should not be used with observable values`),Li(e,t)?t:e}let ge=`override`,_e={annotationType_:ge,make_:ye,extend_:be};function ve(e){return e.annotationType_===ge}function ye(e,t){return e.isPlainObject_&&n(`Cannot apply '${this.annotationType_}' to '${e.name_}.${t.toString()}':\n'${this.annotationType_}' cannot be used on plain objects.`),T(e.appliedAnnotations_,t)||n(`'${e.name_}.${t.toString()}' is annotated with '${this.annotationType_}', but no such annotated member was found on prototype.`),0}function be(e,t,r,i){n(44,this.annotationType_)}function xe(e,t){return{annotationType_:e,options_:t,make_:Se,extend_:Ce}}function Se(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:Bn(n.value)?1:(a(r,t,Ee(e,this,t,n,!1)),2)}function Ce(e,t,n,r){let i=Ee(e,this,t,n);return e.defineProperty_(t,i,r)}function we(e,t,r){ie(r,[`method`,`field`]);let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>xt(s.options_?.name??a.toString(),e,s.options_?.autoAction??!1);if(i==`field`)return function(e){var t;let n=e;return Bn(n)||(n=c(n)),(t=s.options_)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n};if(i==`method`){var l;return Bn(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 Te(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 Ee(e,t,n,r,i=j.safeDescriptors){var a,o;Te(e,t,n,r);let{value:s}=r;return(a=t.options_)!=null&&a.bound&&(s=s.bind(e.proxy_??e.target_)),{value:xt(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 De(e,t){return{annotationType_:e,options_:t,make_:Oe,extend_:ke}}function Oe(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&&(!T(e.target_,t)||!pr(e.target_[t]))&&this.extend_(e,t,n,!1)===null?0:pr(n.value)?1:(a(r,t,Me(e,this,t,n,!1,!1)),2)}function ke(e,t,n,r){let i=Me(e,this,t,n,this.options_?.bound);return e.defineProperty_(t,i,r)}function Ae(e,t,n){var r;ie(n,[`method`]);let{name:i,addInitializer:a}=n;return pr(t)||(t=lr(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 je(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 Me(e,t,n,r,i,a=j.safeDescriptors){je(e,t,n,r);let{value:o}=r;return pr(o)||(o=lr(o)),i&&(o=o.bind(e.proxy_??e.target_),o.isMobXFlow=!0),{value:o,configurable:a?e.isPlainObject_:!0,enumerable:!1,writable:!a}}function Ne(e,t){return{annotationType_:e,options_:t,make_:Pe,extend_:k}}function Pe(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function k(e,t,n,i){return Ie(e,this,t,n),e.defineComputedProperty_(t,r({},this.options_,{get:n.get,set:n.set}),i)}function Fe(e,t,n){ie(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 At(o)}return o(function(){let e=Di(this)[O],n=this,r=e.values_.get(a);r instanceof At&&r.derivation!==t&&e.values_.delete(a),(e.lazyComputedKeys_??=new Map).set(a,()=>c(n,e))}),function(){let e=this[O],n=e.values_.get(a);if(n instanceof At&&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 Ie(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 Le(e,t){return{annotationType_:e,options_:t,make_:Re,extend_:ze}}function Re(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function ze(e,t,n,r){return Ve(e,this,t,n),e.defineObservableProperty_(t,n.value,this.options_?.enhancer_??fe,r)}function Be(e,t,r){if(r.kind===`field`)throw n(`Please use \`@observable accessor ${String(r.name)}\` instead of \`@observable ${String(r.name)}\``);ie(r,[`accessor`]);let i=e,{kind:a,name:o}=r;if(a!==`accessor`)return;function s(e,t){let n=Di(e)[O];return(n.lazyObservableKeys_??=new Map).set(o,()=>new Ot(t,i.options_?.enhancer_??fe,`${n.name_}.${o.toString()}`,!1)),n}return{get(){return(this[O]??s(this,t.get.call(this))).getObservablePropValue_(o)},set(e){return(this[O]??s(this,e)).setObservablePropValue_(o,e)},init(e){return s(this,e),e}}}function Ve(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 He=Ue();function Ue(e){return{annotationType_:`true`,options_:e,make_:Ke,extend_:qe}}let We=[He];function Ge(e){let t=e.deep!==!1,n=!!e.autoBind,r=!t|(n?2:0);return We[r]??(We[r]=Ue({deep:t,autoBind:n}))}function Ke(e,t,n,r){var i;if(n.get)return gt.make_(e,t,n,r);if(n.set){let i=Bn(n.set)?n.set:xt(t.toString(),n.set);return r===e.target_?e.defineProperty_(t,{configurable:j.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?ur:lr).make_(e,t,n,r)}return((o=this.options_)!=null&&o.autoBind?Rn:In).make_(e,t,n,r)}let c=this.options_?.deep===!1?st:dt;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 qe(e,t,n,r){var i;return n.get?gt.extend_(e,t,n,r):n.set?e.defineProperty_(t,{configurable:j.safeDescriptors?e.isPlainObject_:!0,set:xt(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?st:dt).extend_(e,t,n,r))}function Je(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 Ye={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Ye);function Xe(e){return e||Ye}let Ze=Le(`observable`),Qe=Le(`observable.ref`,{enhancer_:me}),$e=Le(`observable.shallow`,{enhancer_:pe}),et=Le(`observable.struct`,{enhancer_:he});function tt(e){return Je(e,Be)}function nt(e){return e.deep===!0?fe:e.deep===!1?me:it(e.defaultDecorator)}function rt(e){return e?e.defaultDecorator??Ge(e):void 0}function it(e){return e?e.options_?.enhancer_??fe:fe}function at(e,t,n){return t&&typeof t.kind==`string`?Be(Ze,e,t):Sr(e)?e:g(e)?dt.object(e,t,n):Array.isArray(e)?dt.array(e,t):x(e)?dt.map(e,t):C(e)?dt.set(e,t):typeof e==`object`&&e?e:dt.box(e,t)}let ot={box(e,t){let n=Xe(t);return new Ot(e,nt(n),n.name,!0,n.equals)},array(e,t){let n=Xe(t);return si(e,nt(n),n.name)},map(e,t){let n=Xe(t);return new _i(e,nt(n),n.name)},set(e,t){let n=Xe(t);return new xi(e,nt(n),n.name)},object(e,t,n){return P(()=>Zn(Kr({},n),e,t))}},st=tt(Qe),ct=tt($e),lt=tt(Ze),ut=tt(et);var dt=r(at,Ze,ot);let ft=`computed`;function pt(e){return Je(e,Fe)}let mt=Ne(ft),ht=pt(Ne(`computed.struct`,{equals:le})),gt=function(e,t){if(t&&typeof t.kind==`string`)return Fe(mt,e,t);if(g(e))return pt(Ne(ft,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 At(r)};r(gt,mt);let _t=0,vt=1,yt=i(()=>{},`name`)?.configurable??!1,bt={value:`action`,configurable:!0,writable:!1,enumerable:!1};function xt(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 St(e,r,t,i||this,arguments)}return o.isMobxAction=!0,o.toString=()=>t.toString(),yt&&(bt.value=e,a(o,`name`,bt)),o}function St(e,t,n,r,i){let a=Ct(e,t,r,i);try{return n.apply(r,i)}catch(e){throw a.error_=e,e}finally{wt(a)}}function Ct(e,t,n,r){let i=xn()&&!!e,a=0;i&&(a=Date.now(),Cn({type:M,name:e,object:n,arguments:r?Array.from(r):s}));let o=j.trackingDerivation,c=!t||!o;on();let l=j.allowStateChanges;c&&(Ut(),l=Et(!0));let u=j.allowStateReads;A(!0);let d={runAsAction_:c,prevDerivation_:o,prevAllowStateChanges_:l,prevAllowStateReads_:u,notifySpy_:i,startTime_:a,actionId_:vt++,parentActionId_:_t};return _t=d.actionId_,d}function wt(e){_t!==e.actionId_&&n(30),_t=e.parentActionId_,e.error_!==void 0&&(j.suppressReactionErrors=!0),Dt(e.prevAllowStateChanges_),Gt(e.prevAllowStateReads_),sn(),e.runAsAction_&&Wt(e.prevDerivation_),e.notifySpy_&&Tn({time:Date.now()-e.startTime_}),j.suppressReactionErrors=!1}function Tt(e,t){let n=Et(e);try{return t()}finally{Dt(n)}}function Et(e){let t=j.allowStateChanges;return j.allowStateChanges=e,t}function Dt(e){j.allowStateChanges=e}var Ot=class extends ae{constructor(e,t,n=`ObservableValue@`+u(),r=!0,i=de){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&&xn()&&Sn({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!==j.UNCHANGED){let n=xn();n&&Cn({type:ii,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:e,oldValue:t}),this.setNewValue_(e),n&&Tn()}}prepareNewValue_(e){if(It(this),qr(this)){let t=Yr(this,{object:this,type:ii,newValue:e});if(!t)return j.UNCHANGED;e=t.newValue}return e=this.enhancer_(e,this.value_,this.name_),this.equals_(this.value_,e)?j.UNCHANGED:e}setNewValue_(e){let t=this.value_;this.value_=e,this.reportChanged(),Xr(this)&&Qr(this,{type:ii,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 ne(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let kt=b(`ObservableValue`,Ot);var At=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 Mt(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_=xt(this.name_+`-setter`,e.set)),this.equals_=e.equals||de,this.scope_=e.context,this.requiresReaction_=e.requiresReaction,this.keepAlive_=!!e.keepAlive}onBecomeStale_(){pn(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return E(this.flags_,1)}set isComputing(e){this.flags_=D(this.flags_,1,e)}get isRunningSetter(){return E(this.flags_,2)}set isRunningSetter(e){this.flags_=D(this.flags_,2,e)}get isBeingObserved(){return E(this.flags_,4)}set isBeingObserved(e){this.flags_=D(this.flags_,4,e)}get isPendingUnobservation(){return E(this.flags_,8)}set isPendingUnobservation(e){this.flags_=D(this.flags_,8,e)}get diffValue(){return+!!E(this.flags_,16)}set diffValue(e){this.flags_=D(this.flags_,16,e===1)}get(){if(this.isComputing&&n(32,this.name_,this.derivation),j.inBatch===0&&(!this.observers_||this.observers_.size===0)&&!this.keepAlive_)Pt(this)&&(this.warnAboutUntrackedRead_(),on(),this.value_=this.computeValue_(!1),sn());else{let e=this.isBeingObserved;if(un(this),Pt(this)){let e=j.trackingContext;!e&&(this.keepAlive_||this.isBeingObserved)&&(j.trackingContext=this),this.trackAndCompute()&&fn(this),j.trackingContext=e}else !e&&this.isBeingObserved&&this.observing_.forEach(ln)}let e=this.value_;if(Nt(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||Nt(e)||Nt(n)||!this.equals_(e,n);return r&&(this.value_=n,xn()&&Sn({observableKind:`computed`,debugObjectName:this.name_,object:this.scope_,type:`update`,oldValue:e,newValue:n})),r}computeValue_(e){this.isComputing=!0;let t=Et(!1),n;if(e)n=Rt(this,this.derivation,this.scope_);else if(j.disableErrorBoundaries===!0)n=this.derivation.call(this.scope_);else try{n=this.derivation.call(this.scope_)}catch(e){n=new Mt(e)}return Dt(t),this.isComputing=!1,n}suspend_(){this.keepAlive_||(Vt(this),this.value_=void 0)}warnAboutUntrackedRead_(){(typeof this.requiresReaction_==`boolean`?this.requiresReaction_:j.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 ne(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let jt=b(`ComputedValue`,At);var Mt=class{constructor(e){this.cause=void 0,this.cause=e}};function Nt(e){return e instanceof Mt}function Pt(e){switch(e.dependenciesState_){case 0:return!1;case-1:case 2:return!0;case 1:{let t=A(!0),n=Ut(),r=e.observing_,i=r.length;for(let a=0;a<i;a++){let i=r[a];if(jt(i)){if(j.disableErrorBoundaries)i.get();else try{i.get()}catch{return Wt(n),Gt(t),!0}if(e.dependenciesState_===2)return Wt(n),Gt(t),!0}}return Kt(e),Wt(n),Gt(t),!1}}}function Ft(){return j.trackingDerivation!==null}function It(e){let t=!!e.observers_&&e.observers_.size>0;!j.allowStateChanges&&(t||j.enforceActions===`always`)&&console.warn(`[MobX] `+(j.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 Lt(e){!j.allowStateReads&&j.observableRequiresReaction&&console.warn(`[mobx] Observable '${e.name_}' being read outside a reactive context.`)}function Rt(e,t,n){let r=A(!0);Kt(e),e.newObserving_=Array(e.runId_===0?100:e.observing_.length),e.unboundDepsCount_=0,e.runId_=++j.runId;let i=j.trackingDerivation;j.trackingDerivation=e,j.inBatch++;let a;if(j.disableErrorBoundaries===!0)a=t.call(n);else try{a=t.call(n)}catch(e){a=new Mt(e)}return j.inBatch--,j.trackingDerivation=i,Bt(e),zt(e),Gt(r),a}function zt(e){e.observing_.length===0&&(typeof e.requiresObservable_==`boolean`?e.requiresObservable_:j.reactionRequiresObservable)&&console.warn(`[mobx] Derivation '${e.name_}' is created/updated without reading any observable value.`)}function Bt(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&&rn(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,nn(t,e))}r!==0&&(e.dependenciesState_=r,e.onBecomeStale_())}function Vt(e){let t=e.observing_;e.observing_=[];let n=t.length;for(;n--;)rn(t[n],e);e.dependenciesState_=-1}function Ht(e){let t=Ut();try{return e()}finally{Wt(t)}}function Ut(){let e=j.trackingDerivation;return j.trackingDerivation=null,e}function Wt(e){j.trackingDerivation=e}function A(e){let t=j.allowStateReads;return j.allowStateReads=e,t}function Gt(e){j.allowStateReads=e}function Kt(e){if(e.dependenciesState_===0)return;e.dependenciesState_=0;let t=e.observing_,n=t.length;for(;n--;)t[n].lowestObserverState_=0}let qt=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Jt=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 Yt=!0,Xt=!1,j=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Yt=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(Yt=!1),Yt?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Jt):(setTimeout(()=>{Xt||n(35)},1),new Jt)}();function Zt(){if((j.pendingReactions.length||j.inBatch||j.isRunningReactions)&&n(36),Xt=!0,Yt){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),j=new Jt}}function Qt(){return j}function $t(){let e=new Jt;for(let t in e)qt.indexOf(t)===-1&&(j[t]=e[t]);j.allowStateChanges=!j.enforceActions}function en(e){return!!e.observers_&&e.observers_.size>0}function tn(e){return e.observers_??new Set}function nn(e,t){(e.observers_??=new Set).add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function rn(e,t){let n=e.observers_;n&&(n.delete(t),n.size===0&&an(e))}function an(e){e.isPendingUnobservation===!1&&(e.isPendingUnobservation=!0,j.pendingUnobservations.push(e))}function on(){j.inBatch++}function sn(){--j.inBatch===0&&(_n(),!j.isRunningUnobservations&&j.pendingUnobservations.length>0&&cn())}function cn(){j.isRunningUnobservations=!0;try{let e=j.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 At&&n.suspend_())}j.pendingUnobservations=[]}finally{j.isRunningUnobservations=!1}}function ln(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.observing_)==null||t.forEach(ln))}function un(e){Lt(e);let t=j.trackingDerivation;return t===null?((!e.observers_||e.observers_.size===0)&&j.inBatch>0&&an(e),!1):(t.runId_!==e.lastAccessedBy_&&(e.lastAccessedBy_=t.runId_,t.newObserving_[t.unboundDepsCount_++]=e,!e.isBeingObserved&&j.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function dn(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 fn(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 pn(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 mn=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 E(this.flags_,1)}set isDisposed(e){this.flags_=D(this.flags_,1,e)}get isScheduled(){return E(this.flags_,2)}set isScheduled(e){this.flags_=D(this.flags_,2,e)}get isTrackPending(){return E(this.flags_,4)}set isTrackPending(e){this.flags_=D(this.flags_,4,e)}get isRunning(){return E(this.flags_,8)}set isRunning(e){this.flags_=D(this.flags_,8,e)}get diffValue(){return+!!E(this.flags_,16)}set diffValue(e){this.flags_=D(this.flags_,16,e===1)}onBecomeStale_(){this.schedule_()}schedule_(){this.isScheduled||(this.isScheduled=!0,j.pendingReactions.push(this),_n())}runReaction_(){if(!this.isDisposed){on(),this.isScheduled=!1;let e=j.trackingContext;if(j.trackingContext=this,Pt(this)){this.isTrackPending=!0;try{this.onInvalidate_(),this.isTrackPending&&xn()&&Sn({name:this.name_,type:`scheduled-reaction`})}catch(e){this.reportExceptionInDerivation_(e)}}j.trackingContext=e,sn()}}track(e){if(this.isDisposed)return;on();let t=xn(),n;t&&(n=Date.now(),Cn({name:this.name_,type:`reaction`})),this.isRunning=!0;let r=j.trackingContext;j.trackingContext=this;let i=Rt(this,e,void 0);j.trackingContext=r,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Vt(this),Nt(i)&&this.reportExceptionInDerivation_(i.cause),t&&Tn({time:Date.now()-n}),sn()}reportExceptionInDerivation_(e){if(this.errorHandler_){this.errorHandler_(e,this);return}if(j.disableErrorBoundaries)throw e;let t=`[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '${this}'`;j.suppressReactionErrors?console.warn(`[mobx] (error in reaction '${this.name_}' suppressed, fix error of causing action below)`):console.error(t,e),xn()&&Sn({type:`error`,name:this.name_,message:t,error:``+e}),j.globalReactionErrorHandlers.forEach(t=>t(e,this))}dispose(){if(!this.isDisposed){var e;this.isDisposed=!0,(e=this.removeAbortListener_)==null||e.call(this),this.isRunning||(on(),Vt(this),sn())}}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[O]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.name_}]`}};function hn(e){return j.globalReactionErrorHandlers.push(e),()=>{let t=j.globalReactionErrorHandlers.indexOf(e);t>=0&&j.globalReactionErrorHandlers.splice(t,1)}}let gn=e=>e();function _n(){j.inBatch>0||j.isRunningReactions||gn(vn)}function vn(){j.isRunningReactions=!0;let e=j.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_()}j.isRunningReactions=!1}let yn=b(`Reaction`,mn);function bn(e){let t=gn;gn=n=>e(()=>t(n))}function xn(){return!!j.spyListeners.length}function Sn(e){if(!j.spyListeners.length)return;let t=j.spyListeners;for(let n=0,r=t.length;n<r;n++)t[n](e)}function Cn(e){Sn(r({},e,{spyReportStart:!0}))}let wn={type:`report-end`,spyReportEnd:!0};function Tn(e){Sn(e?r({},e,{type:`report-end`,spyReportEnd:!0}):wn)}function En(e){return j.spyListeners.push(e),d(()=>{j.spyListeners=j.spyListeners.filter(t=>t!==e)})}let M=`action`,Dn=`autoAction`,On=`<unnamed action>`,kn=xe(M),An=xe(`action.bound`,{bound:!0}),jn=xe(Dn,{autoAction:!0}),Mn=xe(`autoAction.bound`,{autoAction:!0,bound:!0});function Nn(e){return Je(e,we)}function Pn(e){return function(t,r){if(r&&typeof r.kind==`string`)return we(e?jn:kn,t,r);if(p(t))return xt(t.name||On,t,e);if(p(r))return xt(t,r,e);if(m(t))return Nn(xe(e?Dn:M,{name:t,autoAction:e}));n("Invalid arguments for `action`")}}let Fn=Pn(!1);r(Fn,kn);let In=Pn(!0);r(In,jn);let Ln=Nn(An),Rn=Nn(Mn);function zn(e){return St(e.name||On,!1,e,this,void 0)}function Bn(e){return p(e)&&e.isMobxAction===!0}function Vn(e,t=c){var r;p(e)||n(`Autorun expects a function as first argument`),Bn(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 mn(i,function(){this.track(s)},t.onError,t.requiresObservable);else{let e=Un(t),n=!1;o=new mn(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 Hn=e=>e();function Un(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Hn}function Wn(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=Fn(a,r.onError?Gn(r.onError,t):t),s=!r.scheduler&&!r.delay,l=Un(r),d=!0,f=!1,m,h=r.equals||de,_=new mn(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=Tt(!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 Gn(e,t){return function(){try{return t.apply(this,arguments)}catch(t){e.call(this,t)}}}function Kn(e,t,n){return Jn(`onBO`,e,t,n)}function qn(e,t,n){return Jn(`onBUO`,e,t,n)}function Jn(e,t,n,r){let i=typeof r==`function`?Ni(t,n):Ni(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 Yn=`always`;function Xn(e){e.isolateGlobalState===!0&&Zt();let{enforceActions:t}=e;if(t!==void 0){let e=t===Yn?Yn:t===`observed`;j.enforceActions=e,j.allowStateChanges=!(e===!0||e===Yn)}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(j[t]=!!e[t])}),j.allowStateReads=!j.observableRequiresReaction,j.disableErrorBoundaries===!0&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),e.reactionScheduler&&bn(e.reactionScheduler)}function Zn(e,t,r,i){arguments.length>4&&n(`'extendObservable' expected 2-4 arguments`),typeof e!=`object`&&n(`'extendObservable' expects an object as first argument`),N(e)&&n(`'extendObservable' should not be used on maps, use map.merge instead`),g(t)||n(`'extendObservable' only accepts plain objects as second argument`),(Sr(t)||Sr(r))&&n(`Extending an object with another observable (object) is not supported`);let a=re(t);return P(()=>{let t=Di(e,i)[O];te(a).forEach(e=>{t.extend_(e,a[e],r&&e in r?r[e]:!0)})}),e}function Qn(e,t){return $n(Ni(e,t))}function $n(e){let t={name:e.name_};return e.observing_&&e.observing_.length>0&&(t.dependencies=nr(e.observing_).map($n)),t}function er(e,t){return tr(Ni(e,t))}function tr(e){let t={name:e.name_};return en(e)&&(t.observers=Array.from(tn(e),tr)),t}function nr(e){return Array.from(new Set(e))}let rr=0;var ir=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};function ar(e){return e instanceof ir}function or(e){return Je(e,Ae)}let sr=De(`flow`),cr=De(`flow.bound`,{bound:!0}),lr=r(function(e,t){if(t&&typeof t.kind==`string`)return Ae(sr,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=++rr,a=Fn(`${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=Fn(`${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=Fn(`${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=Fn(`${i} - runid: ${n} - cancel`,function(){try{s&&dr(s);let e=a.return(void 0),t=Promise.resolve(e.value);t.then(f,f),dr(t),o(new ir)}catch(e){o(e)}}),c};return a.isMobXFlow=!0,a},sr),ur=or(cr);function dr(e){p(e.cancel)&&e.cancel()}function fr(e){return e}function pr(e){return e?.isMobXFlow===!0}function mr(e,t,r){let i;if(N(e)||mi(e)||kt(e))i=Pi(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=Pi(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 hr(e,t,n){return p(n)?_r(e,t,n):gr(e,t)}function gr(e,t){return Jr(Pi(e),t)}function _r(e,t,n){return Jr(Pi(e,t),n)}function vr(e,t){var n;if(t===void 0)return jt(e);if(Ai(e)===!1)return!1;let r=e[O];return(n=r.lazyComputedKeys_)!=null&&n.has(t)?!0:r.values_.has(t)?jt(Ni(e,t)):!1}function yr(e){return arguments.length>1?n(`isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property`):vr(e)}function br(e,t){return m(t)?vr(e,t):n(`isComputed expected a property name as second argument`)}function xr(e,t){if(!e)return!1;if(t!==void 0){if(N(e)||mi(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[O];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[O]||oe(e)||yn(e)||jt(e)}function Sr(e){return arguments.length!==1&&n(`isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property`),xr(e)}function Cr(e,t){return m(t)?xr(e,t):n(`expected a property name as second argument`)}function wr(e){if(Ai(e))return e[O].keys_();if(N(e)||Si(e))return Array.from(e.keys());if(mi(e))return e.map((e,t)=>t);n(5)}function Tr(e){if(Ai(e))return wr(e).map(t=>e[t]);if(N(e))return wr(e).map(t=>e.get(t));if(Si(e))return Array.from(e.values());if(mi(e))return e.slice();n(6)}function Er(e){if(Ai(e))return wr(e).map(t=>[t,e[t]]);if(N(e))return wr(e).map(t=>[t,e.get(t)]);if(Si(e))return Array.from(e.entries());if(mi(e))return e.map((e,t)=>[t,e]);n(7)}function Dr(e,t,r){if(arguments.length===2&&!Si(e)){on();let n=t;try{for(let t in n)Dr(e,t,n[t])}finally{sn()}return}Ai(e)?e[O].set_(t,r):N(e)?e.set(t,r):Si(e)?e.add(t):mi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),t<0&&n(42,t),on(),t>=e.length&&(e.length=t+1),e[t]=r,sn()):n(8)}function Or(e,t){Ai(e)?e[O].delete_(t):N(e)||Si(e)?e.delete(t):mi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),e.splice(t,1)):n(9)}function kr(e,t){if(Ai(e))return e[O].has_(t);if(N(e)||Si(e))return e.has(t);if(mi(e))return t>=0&&t<e.length;n(10)}function Ar(e,t){if(kr(e,t)){if(Ai(e))return e[O].get_(t);if(N(e))return e.get(t);if(mi(e))return e[t];n(11)}}function jr(e,t,r){if(Ai(e))return e[O].defineProperty_(t,r);n(39)}function Mr(e){if(Ai(e))return e[O].ownKeys_();n(38)}function Nr(e,t,n,r){return p(n)?Fr(e,t,n,r):Pr(e,t,n)}function Pr(e,t,r){let i=Pi(e);if(mi(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(N(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 Ir(i,t,r);return Zr(i,t)}function Fr(e,t,n,r){return Ir(Pi(e,t),n,r)}function Ir(e,t,n){if(jt(e)){let r=!0,i;return Vn(()=>{let a=e.get();if(!r||n){let n=Ut();t({observableKind:`computed`,debugObjectName:e.name_,type:ii,object:e,newValue:a,oldValue:i}),Wt(n)}r=!1,i=a})}return n&&t({observableKind:`value`,debugObjectName:e.name_,object:e,type:ii,newValue:e.value_,oldValue:void 0}),Zr(e,t)}function Lr(e,t,n){return e.set(t,n),n}function Rr(e,t){if(typeof e!=`object`||!e||e instanceof Date||!Sr(e))return e;if(kt(e)||jt(e))return Rr(e.get(),t);if(t.has(e))return t.get(e);if(mi(e)){let n=Lr(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=Rr(e,t)}),n}if(Si(e)){let n=Lr(t,e,new Set);return e.forEach(e=>{n.add(Rr(e,t))}),n}if(N(e)){let n=Lr(t,e,new Map);return e.forEach((e,r)=>{n.set(r,Rr(e,t))}),n}else{let n=Lr(t,e,{});return Mr(e).forEach(r=>{o.propertyIsEnumerable.call(e,r)&&(n[r]=Rr(e[r],t))}),n}}function zr(e,t){return t&&n(`toJS no longer supports options`),Rr(e,new Map)}function Br(e,t=void 0){on();try{return e.apply(t)}finally{sn()}}function Vr(e,t,n){return arguments.length===1||t&&typeof t==`object`?Ur(e,t):Hr(e,t,n||{})}function Hr(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[O].isDisposed)if(a(),n.onError)n.onError(e);else throw e},n.timeout)}n.name=n.name||`When@`+u();let i=xt(n.name+`-effect`,t);var a=Vn(t=>{Tt(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function Ur(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=Hr(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 Wr(e){return e[O]}let Gr={has(e,t){return Wr(e).has_(t)},get(e,t){return Wr(e).get_(t)},set(e,t,n){return m(t)?Wr(e).set_(t,n,!0)??!0:!1},deleteProperty(e,t){return m(t)?Wr(e).delete_(t,!0)??!0:!1},defineProperty(e,t,n){return Wr(e).defineProperty_(t,n)??!0},ownKeys(e){return Wr(e).ownKeys_()},preventExtensions(e){n(13)}};function Kr(e,t){var n;return e=Di(e,t),(n=e[O]).proxy_??(n.proxy_=new Proxy(e,Gr))}function qr(e){return e.interceptors_!==void 0&&e.interceptors_.length>0}function Jr(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 Yr(e,t){let r=Ut();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{Wt(r)}}function Xr(e){return e.changeListeners_!==void 0&&e.changeListeners_.length>0}function Zr(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 Qr(e,t){let n=Ut(),r=e.changeListeners_;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Wt(n)}}function $r(e,t,n){return P(()=>{let r=Di(e,n)[O];te(t).forEach(e=>ni(r,e,t[e]))}),e}let ei=Symbol(`mobx-keys`);function ti(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)?Zn(e,e,t,r):(P(()=>{let n=Di(e,r)[O];if(!e[ei]){let t=Object.getPrototypeOf(e),n=new Set([...te(e),...te(t)]);n.delete(`constructor`),n.delete(O),v(t,ei,n)}e[ei].forEach(e=>ni(n,e,t&&e in t?t[e]:!0))}),e)}function ni(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 ri=`splice`,ii=`update`,ai={get(e,t){let n=e[O];return t===O?n:t===`length`?n.getArrayLength_():typeof t==`string`&&!isNaN(t)?n.get_(parseInt(t)):T(ci,t)?ci[t]:e[t]},set(e,t,n){let r=e[O];return t===`length`?r.setArrayLength_(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.set_(parseInt(t),n),!0},preventExtensions(){n(15)}};var oi=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 ae(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){It(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),qr(this)){let r=Yr(this,{object:this.proxy_,type:ri,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_&&xn(),i=Xr(this),a=i||r?{observableKind:`array`,object:this.proxy_,type:ii,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&Cn(a),this.atom_.reportChanged(),i&&Qr(this,a),r&&Tn()}notifyArraySplice_(e,t,n){let r=!this.owned_&&xn(),i=Xr(this),a=i||r?{observableKind:`array`,object:this.proxy_,debugObjectName:this.atom_.name_,type:ri,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&Cn(a),this.atom_.reportChanged(),i&&Qr(this,a),r&&Tn()}get_(e){return this.atom_.reportObserved(),this.dehanceValue_(this.values_[e])}set_(e,t){let n=this.values_;if(e<n.length){It(this.atom_);let r=n[e];if(qr(this)){let n=Yr(this,{type:ii,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 si(e,t,n=`ObservableArray@`+u(),r=!1){return P(()=>{let i=new oi(n,t,r);y(i.values_,O,i);let a=new Proxy(i.values_,ai);return i.proxy_=a,e&&e.length&&i.spliceWithArray_(0,0,e),a})}var ci={clear(){return this.splice(0)},replace(e){let t=this[O];return t.spliceWithArray_(0,t.values_.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[O];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[O].spliceWithArray_(e,t,n)},push(...e){let t=this[O];return t.spliceWithArray_(t.values_.length,0,e),t.values_.length},pop(){return this.splice(Math.max(this[O].values_.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[O];return t.spliceWithArray_(0,0,e),t.values_.length},reverse(){return j.trackingDerivation&&n(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){j.trackingDerivation&&n(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[O],n=t.dehanceValues_(t.values_).indexOf(e);return n>-1?(this.splice(n,1),!0):!1}};li(`at`,ui),li(`concat`,ui),li(`flat`,ui),li(`includes`,ui),li(`indexOf`,ui),li(`join`,ui),li(`lastIndexOf`,ui),li(`slice`,ui),li(`toString`,ui),li(`toLocaleString`,ui),li(`toSorted`,ui),li(`toSpliced`,ui),li(`with`,ui),li(`every`,di),li(`filter`,di),li(`find`,di),li(`findIndex`,di),li(`findLast`,di),li(`findLastIndex`,di),li(`flatMap`,di),li(`forEach`,di),li(`map`,di),li(`some`,di),li(`toReversed`,di),li(`reduce`,fi),li(`reduceRight`,fi);function li(e,t){typeof Array.prototype[e]==`function`&&(ci[e]=t(e))}function ui(e){return function(){let t=this[O];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_);return n[e].apply(n,arguments)}}function di(e){return function(t,n){let r=this[O];return r.atom_.reportObserved(),r.dehanceValues_(r.values_)[e]((e,r)=>t.call(n,e,r,this))}}function fi(e){return function(){let t=this[O];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 pi=b(`ObservableArrayAdministration`,oi);function mi(e){return h(e)&&pi(e[O])}let hi={},gi=`delete`;var _i=class{constructor(e,t=fe,n=`ObservableMap@`+u()){this.enhancer_=void 0,this.name_=void 0,this[O]=hi,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,P(()=>{this.keysAtom_=se(`${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(!j.trackingDerivation)return this.has_(e);let t=this.hasMap_.get(e);if(!t){let n=t=new Ot(this.has_(e),me,`${this.name_}.${w(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(qr(this)){let r=Yr(this,{type:n?ii:`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(It(this.keysAtom_),qr(this)&&!Yr(this,{type:gi,object:this,name:e}))return!1;if(this.has_(e)){let t=xn(),n=Xr(this),r=n||t?{observableKind:`map`,debugObjectName:this.name_,type:gi,object:this,oldValue:this.data_.get(e).value_,name:e}:null;return t&&Cn(r),Br(()=>{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&&Qr(this,r),t&&Tn(),!0}return!1}updateValue_(e,t){let n=this.data_.get(e);if(t=n.prepareNewValue_(t),t!==j.UNCHANGED){let r=xn(),i=Xr(this),a=i||r?{observableKind:`map`,debugObjectName:this.name_,type:ii,object:this,oldValue:n.value_,name:e,newValue:t}:null;r&&Cn(a),n.setNewValue_(t),i&&Qr(this,a),r&&Tn()}}addValue_(e,t){It(this.keysAtom_),Br(()=>{var n;let r=new Ot(t,this.enhancer_,`${this.name_}.${w(e)}`,!1);this.data_.set(e,r),t=r.value_,(n=this.hasMap_.get(e))==null||n.setNewValue_(!0),this.keysAtom_.reportChanged()});let n=xn(),r=Xr(this),i=r||n?{observableKind:`map`,debugObjectName:this.name_,type:`add`,object:this,name:e,newValue:t}:null;n&&Cn(i),r&&Qr(this,i),n&&Tn()}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 N(e)&&(e=new Map(e)),Br(()=>{g(e)?ee(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(){Br(()=>{Ht(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return Br(()=>{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`}},N=b(`ObservableMap`,_i);function vi(e){return e[Symbol.toStringTag]=`MapIterator`,Vi(e)}function yi(e){if(x(e)||N(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=fe,n=`ObservableSet@`+u()){this.name_=void 0,this[O]=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),P(()=>{this.atom_=se(this.name_),e&&this.replace(e)})}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){Br(()=>{Ht(()=>{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(It(this.atom_),qr(this)){let t=Yr(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){Br(()=>{e=this.enhancer_(e,void 0),this.data_.add(e),this.atom_.reportChanged()});let t=xn(),n=Xr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:`add`,object:this,newValue:e}:null;t&&Cn(r),n&&Qr(this,r),t&&Tn()}return this}delete(e){if(qr(this)&&!Yr(this,{type:gi,object:this,oldValue:e}))return!1;if(this.has(e)){let t=xn(),n=Xr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:gi,object:this,oldValue:e}:null;return t&&Cn(r),Br(()=>{this.atom_.reportChanged(),this.data_.delete(e)}),n&&Qr(this,r),t&&Tn(),!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)?Br(()=>{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=He){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 ae(`${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 At)return n.set(t),!0;if(qr(this)){let n=Yr(this,{type:ii,object:this.proxy_||this.target_,name:e,newValue:t});if(!n)return null;t=n.newValue}if(t=n.prepareNewValue_(t),t!==j.UNCHANGED){let r=Xr(this),i=xn(),a=r||i?{type:ii,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,oldValue:n.value_,name:e,newValue:t}:null;i&&Cn(a),n.setNewValue_(t),r&&Qr(this,a),i&&Tn()}return!0}get_(e){return j.trackingDerivation&&!T(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return T(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(!j.trackingDerivation)return e in this.target_;this.pendingKeys_||=new Map;let t=this.pendingKeys_.get(e);return t||(t=new Ot(e in this.target_,me,`${this.name_}.${w(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){It(this.keysAtom_);try{on();let i=this.delete_(e);if(!i)return i;if(qr(this)){let n=Yr(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{sn()}return!0}defineObservableProperty_(e,t,n,r=!1){It(this.keysAtom_);try{on();let i=this.delete_(e);if(!i)return i;if(qr(this)){let n=Yr(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:j.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 Ot(t,n,`${this.name_}.${e.toString()}`,!1);this.values_.set(e,c),this.notifyPropertyAddition_(e,c.value_)}finally{sn()}return!0}defineComputedProperty_(e,t,n=!1){It(this.keysAtom_);try{on();let r=this.delete_(e);if(!r)return r;if(qr(this)&&!Yr(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:j.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 At(t)),this.notifyPropertyAddition_(e,void 0)}finally{sn()}return!0}delete_(e,t=!1){if(It(this.keysAtom_),!T(this.target_,e))return!0;if(qr(this)&&!Yr(this,{object:this.proxy_||this.target_,name:e,type:Ti}))return null;try{var n;on();let r=Xr(this),a=xn(),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 Ot&&(s=o.value_),dn(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&&Cn(t),r&&Qr(this,t),a&&Tn()}}finally{sn()}return!0}notifyPropertyAddition_(e,t){var n;let r=Xr(this),i=xn();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&&Cn(n),r&&Qr(this,n),i&&Tn()}(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(!0),this.keysAtom_.reportChanged()}ownKeys_(){return this.keysAtom_.reportObserved(),te(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.`),T(e,O))return Pi(e)instanceof Ei||n(`Cannot convert '${Fi(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,O,new Ei(e,new Map,String(r),rt(t))),e}let Oi=b(`ObservableObjectAdministration`,Ei);function ki(e){return wi[e]||(wi[e]={get(){return this[O].getObservablePropValue_(e)},set(t){return this[O].setObservablePropValue_(e,t)}})}function Ai(e){return h(e)?Oi(e[O]):!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.`),!ve(t)&&T(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 Ni(e,t){if(typeof e==`object`&&e){if(mi(e))return t!==void 0&&n(23),e[O].atom_;if(Si(e))return e.atom_;if(N(e)){if(t===void 0)return e.keysAtom_;let r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,Fi(e)),r}if(Ai(e)){if(!t)return n(26);let r=e[O],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,Fi(e)),i}if(oe(e)||jt(e)||yn(e))return e}else if(p(e)&&yn(e[O]))return e[O];n(28)}function Pi(e,t){if(e||n(29),t!==void 0)return Pi(Ni(e,t));if(oe(e)||jt(e)||yn(e)||N(e)||Si(e))return e;if(e[O])return e[O];n(24,e)}function Fi(e,t){let n;if(t!==void 0)n=Ni(e,t);else if(Bn(e))return e.name;else n=Ai(e)||N(e)||Si(e)?Pi(e):Ni(e);return n.name_}function P(e){let t=Ut(),n=Et(!0);on();try{return e()}finally{sn(),Dt(n),Wt(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(!(T(t,o)&&Ri(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function zi(e){return mi(e)?e.slice():x(e)||N(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:En,extras:{getDebugName:Fi},$mobx:O}),e.$mobx=O,e.FlowCancellationError=ir,e.ObservableMap=_i,e.ObservableSet=xi,e.Reaction=mn,e._allowStateChanges=Tt,e._allowStateChangesInsideComputed=zn,e._allowStateReadsEnd=Gt,e._allowStateReadsStart=A,e._autoAction=In,e._autoActionBound=Rn,e._endAction=wt,e._getAdministration=Pi,e._getGlobalState=Qt,e._interceptReads=mr,e._isComputingDerivation=Ft,e._resetGlobalState=$t,e._startAction=Ct,e.action=Fn,e.actionBound=Ln,e.autorun=Vn,e.compareDefault=de,e.compareIdentity=ce,e.compareShallow=ue,e.compareStructural=le,e.computed=gt,e.computedStruct=ht,e.configure=Xn,e.createAtom=se,e.defineProperty=jr,e.entries=Er,e.extendObservable=Zn,e.flow=lr,e.flowBound=ur,e.flowResult=fr,e.get=Ar,e.getAtom=Ni,e.getDebugName=Fi,e.getDependencyTree=Qn,e.getObserverTree=er,e.has=kr,e.intercept=hr,e.isAction=Bn,e.isBoxedObservable=kt,e.isComputed=yr,e.isComputedProp=br,e.isFlow=pr,e.isFlowCancellationError=ar,e.isObservable=Sr,e.isObservableArray=mi,e.isObservableMap=N,e.isObservableObject=Ai,e.isObservableProp=Cr,e.isObservableSet=Si,e.keys=wr,e.makeAutoObservable=ti,e.makeObservable=$r,e.observable=dt,e.observableDeep=lt,e.observableRef=st,e.observableShallow=ct,e.observableStruct=ut,e.observe=Nr,e.onBecomeObserved=Kn,e.onBecomeUnobserved=qn,e.onReactionError=hn,e.override=_e,e.ownKeys=Mr,e.reaction=Wn,e.remove=Or,e.runInAction=zn,e.set=Dr,e.spy=En,e.toJS=zr,e.transaction=Br,e.untracked=Ht,e.values=Tr,e.when=Vr})),X=Ae(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=kT():t.exports=AT()}))();function jT(e){if(Array.isArray(e))return Object.freeze(e.map(jT));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]=jT(r);return Object.freeze(t)}return e}function MT(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 NT(e){return typeof e==`string`?e:String(e)}function PT(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 FT(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 IT=class extends Error{constructor(e,t){super(t),this.variable=e}};function LT(e){return e instanceof IT?e:e instanceof Error&&e.cause!==void 0?LT(e.cause):void 0}const RT=e=>e===ko;var zT=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,RT(n)||YT(e,t,n,`initial value`),this.cell=X.observable.box(n,{deep:!1}),this.lastChangedAt=RT(n)?null:Date.now()}read(){let e=this.cell.get();if(RT(e))throw new IT(this.name,`variable "${this.name}" has no value yet: nothing has written it`);return e}set(e){RT(e)||YT(this.name,this.type,e,`set value`),!Object.is(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}stored(){return this.cell.get()}},BT=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_()}},VT=class{constructor(e){this.deriver=e}read(){return this.deriver()}},HT=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new BT(`Variable "${e}"`,()=>{let e=n();return YT(this.name,this.type,e,`computed result`),e})}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}},UT=class{kind=`projection`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new VT(()=>{let e=n();return YT(this.name,this.type,e,`projection result`),e})}read(){return this.cell.read()}lastUpdatedMs(){return null}},WT=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=X.observable.box(JT(t),{deep:!1}),this.lastChangedAt=t.kind===`pending`?null:Date.now()}read(){return this.cell.get()}set(e){let t=JT(e);qT(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}},GT=class{kind=`document`;cell;constructor(e,t){this.name=e,this.cell=new BT(`Variable "${e}"`,()=>JT(t()),qT)}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}};function KT(e){return JSON.stringify(e)}function qT(e,t){return KT(e)===KT(t)}function JT(e){return e.kind===`ok`?{kind:`ok`,value:jT(e.value)}:e}function YT(e,t,n,r){let i=MT(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var XT=class{constructor(e=null){this.parent=e}nodes=X.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new zT(e,t,n))}defineDocument(e,t){this.declare(e,new WT(e,t))}defineDerivedDocument(e,t){this.declare(e,new GT(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`?HT:UT;this.declare(e,new a(e,t,()=>r(i)))}derive(e,t,n){if(this.refuseDisposed(`Derived value "${e}"`),t===`projection`)return new VT(n);let r=new BT(`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 WT))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`?ko:F(KT(e))}try{return F(String(t.read()))}catch(e){return LT(e)===void 0?F(` failed:${e instanceof Error?e.message:String(e)}`):ko}}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 HT||t instanceof GT)&&(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))}},ZT=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?oE(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}},QT=class extends ZT{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},$T=class extends ZT{name=`EvalError`;kind=`EvalError`},eE=class extends $T{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=sE(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}},tE=class extends $T{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}},nE=class extends $T{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}},rE=class extends nE{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)}`}},iE=class extends $T{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},aE=class extends $T{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function oE(e,t){let n=e.split(`
|
|
62
62
|
`),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(`
|
|
63
63
|
`)}function sE(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:cE(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 cE(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 lE(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const uE=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`]]),dE={left:`{{`,right:`}}`};var fE=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=dE){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 QT(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&&pE(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);pE(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);pE(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(;pE(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`;pE(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&&(hE(e)||mE(e)&&hE(this.src[this.offset+1]??``)||e===`.`&&hE(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&bE(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===`
|
|
64
64
|
`)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===`
|
|
@@ -70,7 +70,7 @@ import{createRequire as e}from"node:module";import t from"node:process";import{U
|
|
|
70
70
|
`).map(e=>n+e).join(`
|
|
71
71
|
`)}function mj(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 hj(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw nA(`join`,2,`list of strings/primitives`,`list element of type ${gj(e)}`);n.push(String(e))}return n.join(e)}function gj(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function _j(e){return oj(e,`-`)}function vj(e){return e.toLowerCase()}function yj(e,t){return`\n${pj(e,t)}`}function bj(e){return e.replace(/\s+/g,``)}function xj(e,t,n){return n===1?e:t}function Sj(...e){return e.map(e=>`"${e}"`).join(` `)}function Cj(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function wj(e,t){return t.repeat(Math.max(0,e))}function Tj(e,t,n){return WA(e,n).join(t)}function Ej(e){return oj(e,`_`)}function Dj(e,t){let n=WA(e,t),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function Oj(e,t){return WA(e,t)}function kj(e,t,n){let r=Aj(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function Aj(e,t,n){if(n===0)return[];let r=WA(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 jj(...e){return e.map(e=>`'${e}'`).join(` `)}function Mj(e,t,n){let r=UA(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 Nj(e){let t=``;for(let n of e)Pj(n)?t+=n.toLowerCase():Fj(n)?t+=n.toUpperCase():t+=n;return t}function Pj(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function Fj(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function Ij(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function Lj(e){return e.trim()}function Rj(e,t){if(e.length===0)return t;let n=new Set(UA(e)),r=UA(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 zj(e,t){return t.startsWith(e)?t.slice(e.length):t}function Bj(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function Vj(e,t){let n=UA(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 Hj(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function Uj(e){return e.toUpperCase()}function Wj(e,t){return Gj(e,`
|
|
72
72
|
`,t)}function Gj(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
|
|
73
|
-
`)){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 Kj(e,t,n){return Gj(e,t,n)}function qj(){return{abbrev:{fn:(e,t)=>GA(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>KA(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>cj(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>lj(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>uj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>dj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>fj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>pj(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>mj(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>hj(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>_j(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>vj(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>yj(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>bj(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>xj(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>Sj(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>Cj(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>wj(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>Tj(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>Ej(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>Dj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>Oj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>kj(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>jj(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>Mj(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>Nj(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>Ij(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>Lj(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>Rj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>zj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>Bj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>Vj(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>Hj(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>Uj(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>Wj(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>Kj(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function Jj(e,t){let n=Yj(e),r=n.copy();return r.style=Wf(n.style,t),r}function Yj(e){if(!(e instanceof K))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function Xj(e){return{fn:(t=>Jj(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function Zj(e){return{fn:((t,n)=>Jj(n,new U({[e]:H.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function Qj(e,t){return new U({[e]:t})}function $j(){let e={};for(let t of If)e[t]=Xj(Qj(t,!0)),e[`not_${t}`]=Xj(Qj(t,!1));for(let[t,n]of Object.entries(Rf))e[t]=Xj(Qj(n,!0));return e}const eM={fn:((e,t)=>Jj(t,U.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},tM={fn:((e,t)=>Jj(t,new U({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function nM(){return{fg:Zj(`color`),bg:Zj(`bgcolor`),...$j(),link:tM,style:eM}}function rM(e,t){let n;try{n=vu(e.trim())}catch(n){throw n instanceof eu?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 iM(n,t,JSON.stringify(e))}function iM(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 aM(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function oM(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 sM=aM([`string`,`int`],((e,t)=>nd(rM(e,`darken`),t).hex)),cM=aM([`string`,`int`],((e,t)=>nd(rM(e,`lighten`),-t).hex)),lM={min:0,max:100,note:`0 = from, 100 = toward`},uM=aM([`string`,`string`,`float`],((e,t,n)=>yu(rM(e,`mix`),rM(t,`mix`),oM(n,`mix`,`percentage`,lM)/100).hex)),dM={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},fM=aM([`string`],(e=>sd(rM(e,`contrastOn`)).hex)),pM={depth:V.TRUECOLOR},mM=e=>aM([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return cd(rM(t,`readableOn`),rM(n,`readableOn`),oM(r,`readableOn`,`ratio`,dM),i,void 0,a).hex})),hM={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function gM(){let e={};for(let[t,n]of Object.entries(hM)){let r=t;e[n]=aM([`string`,`float`],((e,t)=>{let i={...Pu,[r]:oM(t,n,`amount`)};return Ku.fromRgba(rM(e,n)).applyKey(i).toRgba().hex}))}return e}function _M(e=()=>pM){return{darken:sM,lighten:cM,mix:uM,contrastOn:fM,readableOn:mM(e),...gM()}}function vM(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:iM(Xu(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function yM(e){return{color:{fn:(t=>Xu(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new Lp(bf(n),vM(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}const bM=Wp.play(0);function xM(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 SM={...A_.loops,typewriter:e=>A_.transitions.typewriter(e).effect,scramble:e=>A_.transitions.scramble(e).effect,backspace:e=>A_.transitions.backspace(e).effect,scrambleOut:e=>A_.transitions.scrambleOut(e).effect};function CM(e){if(!Object.hasOwn(SM,e))throw RangeError(`unknown glyph effect ${JSON.stringify(e)}; expected one of ${Object.keys(SM).map(e=>JSON.stringify(e)).join(`, `)}`);return SM[e]}function wM(e,t={}){let n=t.timeline??(()=>bM),r=(e,t,r)=>[Wp.run(n(),t),wf(e,r.time)],i=(t,n)=>{let i=e(),[a,o]=r(t,n,i),s=Ep(a,o,i);return i.onHold?.(Dp(s,o)),s.value},a=(e,t)=>Wp.run(Wp.play(e),t);return{frames:{fn:((...t)=>{let n=xM(`frame`,t,Yj).map(({seconds:e,value:t})=>({seconds:e,text:t})),i=e();return M_(...r(`frames`,new j_(n),i),i)}),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...e)=>{let t=xM(`color`,e,e=>rM(e,`stepped`));return t[i(`stepped`,jf(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,Ip(r,o,{seconds:e,ease:bf(t)})))),argTypes:[`float`,`string`,`float`,`float`,`float`],arity:{kind:`exact`},returnType:`float`},loop:{fn:((e,t)=>i(`loop`,a(t,G.continuous(Mf.loop(e))))),argTypes:[`float`,`float`],arity:{kind:`exact`},returnType:`float`},glyphs:{fn:((t,n,i)=>{let o=CM(t),s=Yj(i),c=s.plain,l=e();return M_(...r(`glyphs`,a(n,c_(s,o({z:jh(c,0,0)}),{key:c,asciiOnly:l.asciiOnly===!0})),l),l)}),argTypes:[`string`,`float`,`liftable`],arity:{kind:`exact`},returnType:`T`}}}function TM(e){return{...nM(),..._M(e)}}new U({color:`red`,dim:!0});const EM=/^(?:(?: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,DM=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function OM(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(EM);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(DM);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 kM(e){let t=e.match(DM);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 AM(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 jM(e){return e.toLocaleString()}function MM(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 NM(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 PM=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],FM=PM.length;function IM(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*(FM-1));o+=PM[t]}return o}function LM(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 RM(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 zM=my(),BM=[...Iy];function VM(){return{basename:{fn:e=>s(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>c(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>AM(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(PT(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>NT(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>FT(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>zM,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>BM,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(RM(`sparkline`,[`width`],n),IM(LM(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>NM(e,MM(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function HM(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 UM=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)=>HM(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function WM(){return{formatInteger:{fn:e=>jM(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>OM(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>kM(e),argTypes:[`string`],arity:{kind:`exact`}}}}const GM=e=>e.getTime()/1e3,KM=e=>new Date(e*1e3);let qM=null;function JM(e,t){if(qM!==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 qM=n,{heard:()=>n.soonest,[Symbol.dispose]:()=>{qM=null}}}function YM(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(qM===null)throw Error(`the clock was read outside a draw (${e})`);return qM}const XM={now:()=>KM(YM(`now`).at),frame:()=>YM(`frame`).frame,timeline:()=>YM(`timeline`).timeline};function ZM(e,t){let{frames:n,stepped:r}=wM(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 QM=new Set([`now`,`ago`]);function $M(e,t){return Object.fromEntries(Object.entries(wk(e)).filter(([e])=>QM.has(e)===t))}const eN=$M(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),tN=[e=>$M(e.now,!0),e=>ZM(e.frame,e.timeline),e=>Object.fromEntries(Object.entries(ZM(e.frame)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),UM];function nN(e){return Object.assign({},...e.map(e=>e(XM)))}const rN=new Set(Object.keys(nN(tN)));function iN(e){return new Set([...rN,...Object.keys(nN(e))])}const aN={readableOn:mM},oN=new Set(Object.keys(aN));function sN(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return UD({fromString:e=>new K(e),toString:e=>e.plain,isT:e=>e instanceof K,missingKey:`error`,funcs:{...Mk(),...qj(),...bA(),...HA(),...mO(),...Jk(),...Kk(),...eN,...TM(r),...Object.fromEntries(Object.entries(aN).map(([e,t])=>[e,t(r)])),...nN([...tN,...e.clockFuncs??[]]),...VM(),...WM(),...n??{}}})}function cN(e){return lN(e,new Set(e.names()),``)}function lN(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!dN(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:fN(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return lN(e,t,a)}})}function uN(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 dN(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function fN(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new IT(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}const pN=/\r\n|\r|\n/g,mN=e=>F(e.replace(pN,` `).trim());function hN(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?L(`regex no-match`):F(n.replace(pN,` `))}}const gN=e=>{try{return F(JSON.parse(e))}catch(e){return L(`JSON parse failed: ${e.message}`)}};var _N=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 vN=[`first`,`period`,`change`,`request`,`supersede`];var yN=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,lastMs:null};for(let t of e.refresh)n.refreshes[t]??=0;return this.tallies.set(t,n),new xN(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(vN.map(e=>[e,0]));for(let t of this.tallies.values())for(let n of vN)e[n]+=t.refreshes[n]??0;return e}};const bN={first:!0,period:!0,change:!0,request:!1,supersede:!0};var xN=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&&!bN[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`)}};function SN(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(k(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function CN(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 wN=`session.id`;function TN(e,t,n,r){return{where:`output of "${t}" in ${n}`,read:async()=>{let i=await e.launch({bin:`/bin/sh`,args:[`-c`,t],cwd:n,category:`user-shell`,signal:r});if(!i.ok&&i.reason===`aborted`&&r.aborted)throw r.reason;return i.ok?F(i.stdout):L(`shell "${t}" ${i.exitCode===null?[i.reason,i.error].filter(e=>e!==void 0).join(`: `):`exited with code ${i.exitCode}`} in ${n}`)}}}function EN(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await _e(e,{encoding:`utf8`,signal:n});return F(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return L(`file unreadable: ${e}`)}}}}function DN(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?L(`${r.reason} in ${n}`):r}function ON(e){switch(e.kind){case`never`:return[`first`];case`ttl`:return[`first`,`period`];case`watch_file`:case`key`:case`depends_on`:return[`first`,`change`]}}function kN(e){let t=!1;return()=>{e(`new-key`,t?`change`:`first`),t=!0}}var AN=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=jN(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=jN(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 ST(`watch_file ${e}`,t.bound,il(this.fileEvents.delivery()))}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 jN=e=>xT({named:[e],whole:[e]});var MN=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:me(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(fe(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())fe(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};const NN={read:()=>ko,drawnAt:()=>{throw new IT(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}};function PN(e,t){let n=e;for(let e of t.split(`.`)){if(n===ko)return ko;if(typeof n!=`object`||!n)return;n=n[e]}return n}function FN(e,t){if(t===ko)return ko;if(t===void 0)return L(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the preset reads`);switch(typeof t==`object`&&t?t.kind:void 0){case`ok`:case`absent`:case`failed`:return t;default:return L(`variable "${e}": the view's payload holds no source reading at "${e}"`)}}function IN(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`?NT(e):t===`number`?PT(e):FT(e)}function LN(e){return e===`number`?0:e===`boolean`?!1:``}var RN=class e{lastErrors=new Map;policyFaults=X.observable.map(void 0,{deep:!1});watchMgr;ttlMgr=new MN;cleanups=[];runs=new Map;newKeys=X.observable.set();reads=new _N;askedBy=new Map;abort=new AbortController;inputs=X.observable.box(NN,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=sN({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,a=new yN,o=$c,s=new OT){this.launcher=e,this.store=t,this.defaultEmptyValue=n,this.parent=i,this.ledger=a,this.fileEvents=o,this.watchers=s,this.sessionState=r,this.watchMgr=new AN(s,o)}view(){return new e(this.launcher,new XT(this.store),this.defaultEmptyValue,this.sessionState,this,this.ledger,this.fileEvents,this.watchers)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,MT(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,L(t))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>FN(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===ko)throw this.lastErrors.delete(e),new IT(e,`variable "${e}" has no value yet: its source has not answered`);if(i===void 0)return this.fallbackOf(e,n,r,`input path "${t}" not found in payload`);try{let t=IN(i,n);return this.lastErrors.delete(e),t}catch(t){return this.fallbackOf(e,n,r,t instanceof Error?t.message:String(t))}}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,TN(this.launcher,t,n.cwd,this.abort.signal),SN(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,EN(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where);(0,X.runInAction)(()=>this.sourceNames.push(e));let a=this.ledger.declare({name:`var.${e}`,scope:this.parent===null?`directory`:`view`,refresh:ON(n)});this.registerCachePolicy(e,n,(n,r)=>this.runSource(e,t,i,n,r,a))}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,mN,t.default,n);case`regex`:return this.scalarPublisher(e,hN(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=DN(n,t,r);return this.noteOutcome(e,a),this.store.setBox(e,Oo(a,i)),a}}documentPublisher(e,t,n){let r=t===void 0?ko:F(t);this.store.defineDocument(e,r);let i,a=!1;return this.cleanups.push(()=>clearTimeout(i)),o=>{clearTimeout(i);let s=o.kind===`ok`&&o.value.trim()===``?I:o,c=DN(s,gN,n);this.noteOutcome(e,c);let l=c.kind===`ok`||s.kind===`ok`||t===void 0?c:r,u=a&&s.kind===`ok`&&c.kind!==`ok`,d=()=>{a=c.kind===`ok`,this.store.setDocument(e,l)};return u?i=setTimeout(d,250):d(),c}}runSource(e,t,n,r,i,a){this.askedBy.set(e,i);let o=this.reads.run(e,()=>{let r=this.askedBy.get(e)??i,o=Date.now();return t.read().then(e=>a.recorded(`where=${R(t.where)}`,r,n(e),Date.now()-o),e=>{if(e!==this.abort.signal.reason)throw e})});this.track(e,o,r)}track(e,t,n){if((0,X.runInAction)(()=>{t.kind===`started`&&(this.runs.set(e,t.done),this.newKeys.delete(e)),n===`new-key`&&this.newKeys.add(e)}),t.kind===`queued`)return;let r=t.done;r.finally(()=>(0,X.runInAction)(()=>{this.runs.get(e)===r&&(this.runs.delete(e),this.newKeys.delete(e))}))}async inFlight(e){try{await(0,X.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}return this.awaited()}awaited(){return[...this.newKeys,...this.parent?.awaited()??[]]}settled(e){return this.inFlight(AbortSignal.timeout(e))}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(cN(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=IN(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=LT(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(wN);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(wN):``;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(){this.abort.abort();for(let e of this.cleanups)e();return this.cleanups.length=0,this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:n(`new-key`,`first`);break;case`ttl`:{n(`new-key`,`first`);let e=this.ttlMgr.subscribe(t.durationMs,()=>n(`re-read`,`period`));this.cleanups.push(e);break}case`watch_file`:{n(`new-key`,`first`);let r=this.watchMgr.subscribe(t.path,()=>n(`re-read`,`change`),t=>this.notePolicy(e,t===null?F(void 0):L(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template);this.onReads(e,()=>{try{return F(r.evaluate(cN(this.store)).map(e=>e.plain).join(``))}catch(e){return LT(e)===void 0?L(`cache key: ${e instanceof Error?e.message:String(e)}`):ko}},kN(n));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(`,`)):ko},kN(n));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())},{fireImmediately:!0});this.cleanups.push(i)}fallbackOf(e,t,n,r){if(this.recordError(e,r),n!==void 0)return n;try{return IN(this.defaultEmptyValue,t)}catch{return LN(t)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}notePolicy(e,t){(0,X.runInAction)(()=>{t.kind===`failed`?this.policyFaults.get(e)?.message!==t.reason&&this.policyFaults.set(e,{timestamp:Date.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 zN(e,t){let n=Lx[e],r=Gx(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 BN=Object.fromEntries([...$x].map(([e,t])=>[t,zN(e,t)])),VN={subscribers:`number`,fps:`number`,shown:`boolean`},HN=Object.keys(VN),UN={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[wN]:{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:``},...BN,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(ox.flatMap(e=>HN.map(t=>[dx(e,t),{kind:`input`,path:dx(e,t),type:VN[t],default:ux[t]}]))),[lx(`by`)]:{kind:`input`,path:lx(`by`),default:cx.by},[lx(`fps`)]:{kind:`input`,path:lx(`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:``}},WN={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 GN(e){let t=e.split(`.`,1)[0];return Object.hasOwn(WN,t)?t:void 0}const KN=Object.fromEntries(yy.map(e=>[e,$x.get(e)]));function qN(e){return yy.find(t=>KN[t]===e)}function JN(e,t,n){let r=new Set,i=(e,t=n)=>{for(let n of cT(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 nb(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(wN);for(let t of Object.values(e.actions)){r.add(wN);for(let[,e]of Hw(t))i(e);let e=`set`in t?eS.get(t.set):void 0,n=`persist`in t?$x.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function YN(e,t,n){let r=vT({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of JN(e,t,n.helpers)){if(_T(a,r))continue;let e=UN[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 XN(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function ZN(e){return e}function QN(e,t,n){return n===void 0?Ni+XN(e)+`.`+XN(t):$N(n)}function $N(e){return Ni+XN(e)}function eP(e,t){return e+`.`+t}function tP(e){return Pi+e}const nP=[`closeOnPick`,`paged`,`key`,`distribution`],rP=e=>nP.includes(e),iP=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${Sv.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function aP(e){for(let t of Object.keys(e))if(!rP(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${iP}`);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&&!Cv(r))throw Error(`{{ menu }} option "distribution" must be one of: ${Sv.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Tv(r)}}const oP=e=>`from`in e?e.from:e.themes;function sP(e,t,n){return e===`bool`?Jy(t)!==null:`min`in e?Yy(t,e)!==null:Lw(oP(e),n).members.includes(t)}function cP(e,t){if(e===`bool`)return Ky.join(` or `);if(!(`min`in e)){let n=oP(e),{members:r}=Lw(n,t),i=r.map(e=>JSON.stringify(e));if(r.length<=8)return`one of ${i.join(`, `)}`;let a=typeof n==`string`?` "${n}"`:``;return`one of the ${r.length}${a} names, such as ${i.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function lP(e){return{label:e.label,domain:uP(e.domain)}}function uP(e){return e===`theme`?{themes:Pw}:e===`bool`||`min`in e?e:{from:e}}function dP(e,t,n,r,i){let a=Si(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...Ky]}},variables:{}};if(`from`in o)return fP(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 fP(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 fP(e,t,n,r,i){let a={variable:n,key:n,member:t},o=eP(n,t),s=`${t}.open`,c=tP(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]:Ai(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:ki(n,N),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const pP=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],mP=Object.fromEntries(pP.map(e=>[e.member,e.label])),hP={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},gP=Object.keys(hP),_P=tS(e=>Jx[e].place),vP=e=>Object.hasOwn(hP,e),yP=(e,t)=>e===t||vP(e)&&yP(_P[hP[e].beside],t),bP=e=>vP(e)?`${bP(_P[hP[e].beside])} › ${hP[e].trigger}`:e===`door`?`first line`:mP[e],xP=e=>bP(_P[e]),SP=()=>[`door`,...pP.map(e=>e.member)].flatMap(e=>[e,...gP.filter(t=>yP(t,e))]).map(e=>({path:bP(e),names:Yx.filter(t=>_P[t]===e)})).filter(({names:e})=>e.length>0),CP=e=>{let{setting:t,on:n,inTmux:r}=ax[e].switch;return`${ax[e].label} is off — turn it on in the settings menu's ${xP(t)}, or set globals.${t}: ${JSON.stringify(n)}${r?`; it runs only for a session inside a tmux pane`:``}`},wP=Object.fromEntries(Object.entries(Lx).map(([e,t])=>[e,t.spec]));function TP(e){return EP(Lx[e])}function EP(e){return`optionDomain`in e&&e.optionDomain!==void 0?{from:e.optionDomain.name}:e.domain}function DP(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:q(e.source,[...n.split(`.`),r])})}}}function OP(e){return DP(`${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 kP(e){return DP(`${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 AP(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&by(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:q(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const jP={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 ${xP(`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."},MP={noun:`globals key`,fields:wP,removed:jP},NP={preset:OP(`a preset`),menuGlyph:kP(`a preset`)},PP={noun:`preset globals key`,fields:{...wP,...NP},removed:jP};function FP(e){return GP(e)&&!(e in NP)}const IP=`is decided later than any rule could be settled`,LP={noun:`editGlobals key`,removed:jP,fields:{...wP,preset:OP(`the editGlobals fragment`),menuGlyph:kP(`the editGlobals fragment`),palette:AP(wP.palette,`the editGlobals fragment`,IP),style:AP(wP.style,`the editGlobals fragment`,IP),effect:AP(wP.effect,`the editGlobals fragment`,IP)}},RP={noun:`theme default key`,fields:{...Object.fromEntries(Vx.map(e=>[e,wP[e]])),style:AP(wP.style,`a theme's default`,`is the look that theme wears by name`)}};function zP(e,t){if(!Ab(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${jb(t)}`,line:q(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${dy(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:q(e.source,[`themeDefaults`,r])});continue}let a=Mb(e,RP,t,i);a!==null&&(n[r]=a)}return n}function BP(e,t,n){return n===void 0?{}:Mb(e,MP,t,n)??{}}function VP(e,t,n){return Mb(e,PP,t,n)??{}}function HP(){return $b(PP)}function UP(e,t,n){return Mb(e,LP,t,n)??{}}const WP=new Set(Object.keys(wP));function GP(e){return WP.has(e)}function ote(e){return Object.hasOwn(jP,e)?jP[e]:void 0}function ste(){return[...WP]}const cte=new Map(Object.entries(Lx).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function lte(e){let t=new Map;for(let[n,r]of cte){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const ute=/^segments\.([^.]+)\.palette$/,dte=/^presets\.(.+)\.root$/,fte=/^presets\.(.+)\.globals\.([^.]+)$/,pte=/^themeDefaults\.(.+)\.([^.]+)$/;function KP(e){return`presets.${e}.root`}function mte(e,t){return`themeDefaults.${e}.${t}`}const qP=e=>Vx.includes(e);function JP(e,t){return`presets.${e}.globals.${t}`}function YP(e){if(GP(e))return{scope:`globals`,field:e};let t=ute.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=fte.exec(e);if(n&&FP(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=pte.exec(e);if(r&&qP(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=dte.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function XP(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 ZP=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],hte=[...ZP,`other`],gte={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},QP=UD({fromString:e=>e});function _te(e){let t=XN(e);return Ii.find(e=>t.startsWith(XN(e)))}function $P(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:q(e.source,[`root`])})}function vte(e,t,n){for(let r of[`variables`,`actions`,`helpers`,`segments`])for(let i of Object.keys(t[r]??{})){let t=Yw(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:q(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=Yw(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:q(e.source,[`segments`,r,`vars`,t])})}}const eF=`edit.mode`,tF=`edit.configure`,nF=`edit.toggle`,rF=`arrange`,iF=`${Fi}draft.`;function aF(e,t){return`${e}:${t}`}const oF={variable:eF,key:eF,member:rF},sF=wi(oF);function yte(e){try{return QP.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function bte(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`&&yte(t))return!0}return!1}function xte(e,t){if($P(e,t,Fi,`edit mode`),!bte(t))return;let{variables:n,actions:r}=cF();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function cF(){return{variables:{[eF]:{...ki(eF,N),within:[Bi]},[tF]:{...ki(tF,N),within:[oF]}},actions:{[nF]:Ai(eF,rF),"edit.unconfigure":{set:tF,to:N}}}}function lF(e,t,n,r){let i={variable:e,key:e,member:vi};return r.variables[e]={...ki(e,N),...n.length>0&&{within:n}},r.actions[e]=Ai(e,vi),r.segments[e]={template:Ei(e,`(?)`,`✕`),...Ste(n)},Ci(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 Ste(e){let[t,...n]=e;return t===void 0?{}:{when:wi(t,...n)}}const uF=`none`;function dF(e){return Xu(e,`background`)}var Cte=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function wte(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=fF(n,i),l=c!==uF,u=l?c===void 0?o:pF(a,c,`bg`):dF(a);e.bg=u;let d=fF(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:Vv(a,e,t))(u):void 0:pF(a,d,`fg`);return new U({...l&&{bgcolor:H.fromRgba(u)},...f!==void 0&&{color:H.fromRgba(f)}})}function fF(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function pF(e,t,n){try{return Xu(e,t)}catch(e){throw e instanceof Yu?new Cte(t,n,e.message):e}}const mF=`🔧`,hF={help:[`-h`,`--help`],version:[`-V`,`--version`]},gF=[...new Set(Object.values(ax).map(e=>xP(e.switch.setting)))].join(` or `),Tte=Math.max(...Object.values(Jx).map(e=>e.configKey.length))+2,_F=[`✚ inserts`,`✖ removes`,`${mF} configures`,`↺ resets layout`],vF={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`]},Ete=`
|
|
73
|
+
`)){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 Kj(e,t,n){return Gj(e,t,n)}function qj(){return{abbrev:{fn:(e,t)=>GA(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>KA(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>cj(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>lj(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>uj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>dj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>fj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>pj(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>mj(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>hj(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>_j(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>vj(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>yj(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>bj(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>xj(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>Sj(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>Cj(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>wj(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>Tj(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>Ej(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>Dj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>Oj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>kj(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>jj(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>Mj(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>Nj(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>Ij(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>Lj(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>Rj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>zj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>Bj(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>Vj(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>Hj(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>Uj(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>Wj(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>Kj(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function Jj(e,t){let n=Yj(e),r=n.copy();return r.style=Wf(n.style,t),r}function Yj(e){if(!(e instanceof K))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function Xj(e){return{fn:(t=>Jj(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function Zj(e){return{fn:((t,n)=>Jj(n,new U({[e]:H.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function Qj(e,t){return new U({[e]:t})}function $j(){let e={};for(let t of If)e[t]=Xj(Qj(t,!0)),e[`not_${t}`]=Xj(Qj(t,!1));for(let[t,n]of Object.entries(Rf))e[t]=Xj(Qj(n,!0));return e}const eM={fn:((e,t)=>Jj(t,U.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},tM={fn:((e,t)=>Jj(t,new U({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function nM(){return{fg:Zj(`color`),bg:Zj(`bgcolor`),...$j(),link:tM,style:eM}}function rM(e,t){let n;try{n=vu(e.trim())}catch(n){throw n instanceof eu?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 iM(n,t,JSON.stringify(e))}function iM(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 aM(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function oM(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 sM=aM([`string`,`int`],((e,t)=>nd(rM(e,`darken`),t).hex)),cM=aM([`string`,`int`],((e,t)=>nd(rM(e,`lighten`),-t).hex)),lM={min:0,max:100,note:`0 = from, 100 = toward`},uM=aM([`string`,`string`,`float`],((e,t,n)=>yu(rM(e,`mix`),rM(t,`mix`),oM(n,`mix`,`percentage`,lM)/100).hex)),dM={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},fM=aM([`string`],(e=>sd(rM(e,`contrastOn`)).hex)),pM={depth:V.TRUECOLOR},mM=e=>aM([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return cd(rM(t,`readableOn`),rM(n,`readableOn`),oM(r,`readableOn`,`ratio`,dM),i,void 0,a).hex})),hM={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function gM(){let e={};for(let[t,n]of Object.entries(hM)){let r=t;e[n]=aM([`string`,`float`],((e,t)=>{let i={...Pu,[r]:oM(t,n,`amount`)};return Ku.fromRgba(rM(e,n)).applyKey(i).toRgba().hex}))}return e}function _M(e=()=>pM){return{darken:sM,lighten:cM,mix:uM,contrastOn:fM,readableOn:mM(e),...gM()}}function vM(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:iM(Xu(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function yM(e){return{color:{fn:(t=>Xu(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new Lp(bf(n),vM(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}const bM=Wp.play(0);function xM(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 SM={...A_.loops,typewriter:e=>A_.transitions.typewriter(e).effect,scramble:e=>A_.transitions.scramble(e).effect,backspace:e=>A_.transitions.backspace(e).effect,scrambleOut:e=>A_.transitions.scrambleOut(e).effect};function CM(e){if(!Object.hasOwn(SM,e))throw RangeError(`unknown glyph effect ${JSON.stringify(e)}; expected one of ${Object.keys(SM).map(e=>JSON.stringify(e)).join(`, `)}`);return SM[e]}function wM(e,t={}){let n=t.timeline??(()=>bM),r=(e,t,r)=>[Wp.run(n(),t),wf(e,r.time)],i=(t,n)=>{let i=e(),[a,o]=r(t,n,i),s=Ep(a,o,i);return i.onHold?.(Dp(s,o)),s.value},a=(e,t)=>Wp.run(Wp.play(e),t);return{frames:{fn:((...t)=>{let n=xM(`frame`,t,Yj).map(({seconds:e,value:t})=>({seconds:e,text:t})),i=e();return M_(...r(`frames`,new j_(n),i),i)}),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...e)=>{let t=xM(`color`,e,e=>rM(e,`stepped`));return t[i(`stepped`,jf(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,Ip(r,o,{seconds:e,ease:bf(t)})))),argTypes:[`float`,`string`,`float`,`float`,`float`],arity:{kind:`exact`},returnType:`float`},loop:{fn:((e,t)=>i(`loop`,a(t,G.continuous(Mf.loop(e))))),argTypes:[`float`,`float`],arity:{kind:`exact`},returnType:`float`},glyphs:{fn:((t,n,i)=>{let o=CM(t),s=Yj(i),c=s.plain,l=e();return M_(...r(`glyphs`,a(n,c_(s,o({z:jh(c,0,0)}),{key:c,asciiOnly:l.asciiOnly===!0})),l),l)}),argTypes:[`string`,`float`,`liftable`],arity:{kind:`exact`},returnType:`T`}}}function TM(e){return{...nM(),..._M(e)}}new U({color:`red`,dim:!0});const EM=/^(?:(?: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,DM=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function OM(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(EM);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(DM);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 kM(e){let t=e.match(DM);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 AM(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 jM(e){return e.toLocaleString()}function MM(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 NM(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 PM=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],FM=PM.length;function IM(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*(FM-1));o+=PM[t]}return o}function LM(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 RM(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 zM=my(),BM=[...Iy];function VM(){return{basename:{fn:e=>s(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>c(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>AM(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(PT(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>NT(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>FT(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>zM,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>BM,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(RM(`sparkline`,[`width`],n),IM(LM(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>NM(e,MM(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function HM(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 UM=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)=>HM(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function WM(){return{formatInteger:{fn:e=>jM(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>OM(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>kM(e),argTypes:[`string`],arity:{kind:`exact`}}}}const GM=e=>e.getTime()/1e3,KM=e=>new Date(e*1e3);let qM=null;function JM(e,t){if(qM!==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 qM=n,{heard:()=>n.soonest,[Symbol.dispose]:()=>{qM=null}}}function YM(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(qM===null)throw Error(`the clock was read outside a draw (${e})`);return qM}const XM={now:()=>KM(YM(`now`).at),frame:()=>YM(`frame`).frame,timeline:()=>YM(`timeline`).timeline};function ZM(e,t){let{frames:n,stepped:r}=wM(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 QM=new Set([`now`,`ago`]);function $M(e,t){return Object.fromEntries(Object.entries(wk(e)).filter(([e])=>QM.has(e)===t))}const eN=$M(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),tN=[e=>$M(e.now,!0),e=>ZM(e.frame,e.timeline),e=>Object.fromEntries(Object.entries(ZM(e.frame)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),UM];function nN(e){return Object.assign({},...e.map(e=>e(XM)))}const rN=new Set(Object.keys(nN(tN)));function iN(e){return new Set([...rN,...Object.keys(nN(e))])}const aN={readableOn:mM},oN=new Set(Object.keys(aN));function sN(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return UD({fromString:e=>new K(e),toString:e=>e.plain,isT:e=>e instanceof K,missingKey:`error`,funcs:{...Mk(),...qj(),...bA(),...HA(),...mO(),...Jk(),...Kk(),...eN,...TM(r),...Object.fromEntries(Object.entries(aN).map(([e,t])=>[e,t(r)])),...nN([...tN,...e.clockFuncs??[]]),...VM(),...WM(),...n??{}}})}function cN(e){return lN(e,new Set(e.names()),``)}function lN(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!dN(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:fN(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return lN(e,t,a)}})}function uN(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 dN(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function fN(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new IT(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}const pN=/\r\n|\r|\n/g,mN=e=>F(e.replace(pN,` `).trim());function hN(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?L(`regex no-match`):F(n.replace(pN,` `))}}const gN=e=>{try{return F(JSON.parse(e))}catch(e){return L(`JSON parse failed: ${e.message}`)}};var _N=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 vN=[`first`,`period`,`change`,`request`,`supersede`];var yN=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,lastMs:null};for(let t of e.refresh)n.refreshes[t]??=0;return this.tallies.set(t,n),new xN(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(vN.map(e=>[e,0]));for(let t of this.tallies.values())for(let n of vN)e[n]+=t.refreshes[n]??0;return e}};const bN={first:!0,period:!0,change:!0,request:!1,supersede:!0};var xN=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&&!bN[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`)}};function SN(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(k(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function CN(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 wN=`session.id`;function TN(e,t,n,r){return{where:`output of "${t}" in ${n}`,read:async()=>{let i=await e.launch({bin:`/bin/sh`,args:[`-c`,t],cwd:n,category:`user-shell`,signal:r});if(!i.ok&&i.reason===`aborted`&&r.aborted)throw r.reason;return i.ok?F(i.stdout):L(`shell "${t}" ${i.exitCode===null?[i.reason,i.error].filter(e=>e!==void 0).join(`: `):`exited with code ${i.exitCode}`} in ${n}`)}}}function EN(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await _e(e,{encoding:`utf8`,signal:n});return F(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return L(`file unreadable: ${e}`)}}}}function DN(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?L(`${r.reason} in ${n}`):r}function ON(e){switch(e.kind){case`never`:return[`first`];case`ttl`:return[`first`,`period`];case`watch_file`:case`key`:case`depends_on`:return[`first`,`change`]}}function kN(e){let t=!1;return()=>{e(`new-key`,t?`change`:`first`),t=!0}}var AN=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=jN(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=jN(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 ST(`watch_file ${e}`,t.bound,il(this.fileEvents.delivery()))}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 jN=e=>xT({named:[e],whole:[e]});var MN=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:me(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(fe(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())fe(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};const NN={read:()=>ko,drawnAt:()=>{throw new IT(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}};function PN(e,t){let n=e;for(let e of t.split(`.`)){if(n===ko)return ko;if(typeof n!=`object`||!n)return;n=n[e]}return n}function FN(e,t){if(t===ko)return ko;if(t===void 0)return L(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the preset reads`);switch(typeof t==`object`&&t?t.kind:void 0){case`ok`:case`absent`:case`failed`:return t;default:return L(`variable "${e}": the view's payload holds no source reading at "${e}"`)}}function IN(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`?NT(e):t===`number`?PT(e):FT(e)}function LN(e){return e===`number`?0:e===`boolean`?!1:``}var RN=class e{lastErrors=new Map;policyFaults=X.observable.map(void 0,{deep:!1});watchMgr;ttlMgr=new MN;cleanups=[];runs=new Map;newKeys=X.observable.set();reads=new _N;askedBy=new Map;abort=new AbortController;inputs=X.observable.box(NN,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=sN({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,a=new yN,o=$c,s=new OT){this.launcher=e,this.store=t,this.defaultEmptyValue=n,this.parent=i,this.ledger=a,this.fileEvents=o,this.watchers=s,this.sessionState=r,this.watchMgr=new AN(s,o)}view(){return new e(this.launcher,new XT(this.store),this.defaultEmptyValue,this.sessionState,this,this.ledger,this.fileEvents,this.watchers)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,MT(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,L(t))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>FN(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===ko)throw this.lastErrors.delete(e),new IT(e,`variable "${e}" has no value yet: its source has not answered`);if(i===void 0)return this.fallbackOf(e,n,r,`input path "${t}" not found in payload`);try{let t=IN(i,n);return this.lastErrors.delete(e),t}catch(t){return this.fallbackOf(e,n,r,t instanceof Error?t.message:String(t))}}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,TN(this.launcher,t,n.cwd,this.abort.signal),SN(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,EN(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where);(0,X.runInAction)(()=>this.sourceNames.push(e));let a=this.ledger.declare({name:`var.${e}`,scope:this.parent===null?`directory`:`view`,refresh:ON(n)});this.registerCachePolicy(e,n,(n,r)=>this.runSource(e,t,i,n,r,a))}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,mN,t.default,n);case`regex`:return this.scalarPublisher(e,hN(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=DN(n,t,r);return this.noteOutcome(e,a),this.store.setBox(e,Oo(a,i)),a}}documentPublisher(e,t,n){let r=t===void 0?ko:F(t);this.store.defineDocument(e,r);let i,a=!1;return this.cleanups.push(()=>clearTimeout(i)),o=>{clearTimeout(i);let s=o.kind===`ok`&&o.value.trim()===``?I:o,c=DN(s,gN,n);this.noteOutcome(e,c);let l=c.kind===`ok`||s.kind===`ok`||t===void 0?c:r,u=a&&s.kind===`ok`&&c.kind!==`ok`,d=()=>{a=c.kind===`ok`,this.store.setDocument(e,l)};return u?i=setTimeout(d,250):d(),c}}runSource(e,t,n,r,i,a){this.askedBy.set(e,i);let o=this.reads.run(e,()=>{let r=this.askedBy.get(e)??i,o=Date.now();return t.read().then(e=>a.recorded(`where=${R(t.where)}`,r,n(e),Date.now()-o),e=>{if(e!==this.abort.signal.reason)throw e})});this.track(e,o,r)}track(e,t,n){if((0,X.runInAction)(()=>{t.kind===`started`&&(this.runs.set(e,t.done),this.newKeys.delete(e)),n===`new-key`&&this.newKeys.add(e)}),t.kind===`queued`)return;let r=t.done;r.finally(()=>(0,X.runInAction)(()=>{this.runs.get(e)===r&&(this.runs.delete(e),this.newKeys.delete(e))}))}async inFlight(e){try{await(0,X.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}return this.awaited()}awaited(){return[...this.newKeys,...this.parent?.awaited()??[]]}settled(e){return this.inFlight(AbortSignal.timeout(e))}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(cN(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=IN(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=LT(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(wN);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(wN):``;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(){this.abort.abort();for(let e of this.cleanups)e();return this.cleanups.length=0,this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:n(`new-key`,`first`);break;case`ttl`:{n(`new-key`,`first`);let e=this.ttlMgr.subscribe(t.durationMs,()=>n(`re-read`,`period`));this.cleanups.push(e);break}case`watch_file`:{n(`new-key`,`first`);let r=this.watchMgr.subscribe(t.path,()=>n(`re-read`,`change`),t=>this.notePolicy(e,t===null?F(void 0):L(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template);this.onReads(e,()=>{try{return F(r.evaluate(cN(this.store)).map(e=>e.plain).join(``))}catch(e){return LT(e)===void 0?L(`cache key: ${e instanceof Error?e.message:String(e)}`):ko}},kN(n));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(`,`)):ko},kN(n));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())},{fireImmediately:!0});this.cleanups.push(i)}fallbackOf(e,t,n,r){if(this.recordError(e,r),n!==void 0)return n;try{return IN(this.defaultEmptyValue,t)}catch{return LN(t)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}notePolicy(e,t){(0,X.runInAction)(()=>{t.kind===`failed`?this.policyFaults.get(e)?.message!==t.reason&&this.policyFaults.set(e,{timestamp:Date.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 zN(e,t){let n=Lx[e],r=Gx(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 BN=Object.fromEntries([...Qx].map(([e,t])=>[t,zN(e,t)])),VN={subscribers:`number`,fps:`number`,shown:`boolean`},HN=Object.keys(VN),UN={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[wN]:{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:``},...BN,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(ox.flatMap(e=>HN.map(t=>[dx(e,t),{kind:`input`,path:dx(e,t),type:VN[t],default:ux[t]}]))),[lx(`by`)]:{kind:`input`,path:lx(`by`),default:cx.by},[lx(`fps`)]:{kind:`input`,path:lx(`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:``}},WN={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 GN(e){let t=e.split(`.`,1)[0];return Object.hasOwn(WN,t)?t:void 0}const KN=Object.fromEntries(yy.map(e=>[e,Qx.get(e)]));function qN(e){return yy.find(t=>KN[t]===e)}function JN(e,t,n){let r=new Set,i=(e,t=n)=>{for(let n of cT(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 nb(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(wN);for(let t of Object.values(e.actions)){r.add(wN);for(let[,e]of Hw(t))i(e);let e=`set`in t?$x.get(t.set):void 0,n=`persist`in t?Qx.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function YN(e,t,n){let r=vT({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of JN(e,t,n.helpers)){if(_T(a,r))continue;let e=UN[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 XN(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function ZN(e){return e}function QN(e,t,n){return n===void 0?Ni+XN(e)+`.`+XN(t):$N(n)}function $N(e){return Ni+XN(e)}function eP(e,t){return e+`.`+t}function tP(e){return Pi+e}const nP=[`closeOnPick`,`paged`,`key`,`distribution`],rP=e=>nP.includes(e),iP=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${Sv.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function aP(e){for(let t of Object.keys(e))if(!rP(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${iP}`);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&&!Cv(r))throw Error(`{{ menu }} option "distribution" must be one of: ${Sv.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Tv(r)}}const oP=e=>`from`in e?e.from:e.themes;function sP(e,t,n){return e===`bool`?Jy(t)!==null:`min`in e?Yy(t,e)!==null:Lw(oP(e),n).members.includes(t)}function cP(e,t){if(e===`bool`)return Ky.join(` or `);if(!(`min`in e)){let n=oP(e),{members:r}=Lw(n,t),i=r.map(e=>JSON.stringify(e));if(r.length<=8)return`one of ${i.join(`, `)}`;let a=typeof n==`string`?` "${n}"`:``;return`one of the ${r.length}${a} names, such as ${i.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function lP(e){return{label:e.label,domain:uP(e.domain)}}function uP(e){return e===`theme`?{themes:Pw}:e===`bool`||`min`in e?e:{from:e}}function dP(e,t,n,r,i){let a=Si(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...Ky]}},variables:{}};if(`from`in o)return fP(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 fP(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 fP(e,t,n,r,i){let a={variable:n,key:n,member:t},o=eP(n,t),s=`${t}.open`,c=tP(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]:Ai(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:ki(n,N),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const pP=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],mP=Object.fromEntries(pP.map(e=>[e.member,e.label])),hP={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},gP=Object.keys(hP),_P=eS(e=>Jx[e].place),vP=e=>Object.hasOwn(hP,e),yP=(e,t)=>e===t||vP(e)&&yP(_P[hP[e].beside],t),bP=e=>vP(e)?`${bP(_P[hP[e].beside])} › ${hP[e].trigger}`:e===`door`?`first line`:mP[e],xP=e=>bP(_P[e]),SP=()=>[`door`,...pP.map(e=>e.member)].flatMap(e=>[e,...gP.filter(t=>yP(t,e))]).map(e=>({path:bP(e),names:Yx.filter(t=>_P[t]===e)})).filter(({names:e})=>e.length>0),CP=e=>{let{setting:t,on:n,inTmux:r}=ax[e].switch;return`${ax[e].label} is off — turn it on in the settings menu's ${xP(t)}, or set globals.${t}: ${JSON.stringify(n)}${r?`; it runs only for a session inside a tmux pane`:``}`},wP=Object.fromEntries(Object.entries(Lx).map(([e,t])=>[e,t.spec]));function TP(e){return EP(Lx[e])}function EP(e){return`optionDomain`in e&&e.optionDomain!==void 0?{from:e.optionDomain.name}:e.domain}function DP(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:q(e.source,[...n.split(`.`),r])})}}}function OP(e){return DP(`${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 kP(e){return DP(`${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 AP(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&by(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:q(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const jP={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 ${xP(`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."},MP={noun:`globals key`,fields:wP,removed:jP},NP={preset:OP(`a preset`),menuGlyph:kP(`a preset`)},PP={noun:`preset globals key`,fields:{...wP,...NP},removed:jP};function FP(e){return GP(e)&&!(e in NP)}const IP=`is decided later than any rule could be settled`,LP={noun:`editGlobals key`,removed:jP,fields:{...wP,preset:OP(`the editGlobals fragment`),menuGlyph:kP(`the editGlobals fragment`),palette:AP(wP.palette,`the editGlobals fragment`,IP),style:AP(wP.style,`the editGlobals fragment`,IP),effect:AP(wP.effect,`the editGlobals fragment`,IP)}},RP={noun:`theme default key`,fields:{...Object.fromEntries(Vx.map(e=>[e,wP[e]])),style:AP(wP.style,`a theme's default`,`is the look that theme wears by name`)}};function zP(e,t){if(!Ab(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${jb(t)}`,line:q(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${dy(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:q(e.source,[`themeDefaults`,r])});continue}let a=Mb(e,RP,t,i);a!==null&&(n[r]=a)}return n}function BP(e,t,n){return n===void 0?{}:Mb(e,MP,t,n)??{}}function VP(e,t,n){return Mb(e,PP,t,n)??{}}function HP(){return $b(PP)}function UP(e,t,n){return Mb(e,LP,t,n)??{}}const WP=new Set(Object.keys(wP));function GP(e){return WP.has(e)}function ote(e){return Object.hasOwn(jP,e)?jP[e]:void 0}function ste(){return[...WP]}const cte=new Map(Object.entries(Lx).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function lte(e){let t=new Map;for(let[n,r]of cte){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const ute=/^segments\.([^.]+)\.palette$/,dte=/^presets\.(.+)\.root$/,fte=/^presets\.(.+)\.globals\.([^.]+)$/,pte=/^themeDefaults\.(.+)\.([^.]+)$/;function KP(e){return`presets.${e}.root`}function mte(e,t){return`themeDefaults.${e}.${t}`}const qP=e=>Vx.includes(e);function JP(e,t){return`presets.${e}.globals.${t}`}function YP(e){if(GP(e))return{scope:`globals`,field:e};let t=ute.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=fte.exec(e);if(n&&FP(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=pte.exec(e);if(r&&qP(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=dte.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function XP(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 ZP=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],hte=[...ZP,`other`],gte={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},QP=UD({fromString:e=>e});function _te(e){let t=XN(e);return Ii.find(e=>t.startsWith(XN(e)))}function $P(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:q(e.source,[`root`])})}function vte(e,t,n){for(let r of[`variables`,`actions`,`helpers`,`segments`])for(let i of Object.keys(t[r]??{})){let t=Yw(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:q(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=Yw(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:q(e.source,[`segments`,r,`vars`,t])})}}const eF=`edit.mode`,tF=`edit.configure`,nF=`edit.toggle`,rF=`arrange`,iF=`${Fi}draft.`;function aF(e,t){return`${e}:${t}`}const oF={variable:eF,key:eF,member:rF},sF=wi(oF);function yte(e){try{return QP.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function bte(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`&&yte(t))return!0}return!1}function xte(e,t){if($P(e,t,Fi,`edit mode`),!bte(t))return;let{variables:n,actions:r}=cF();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function cF(){return{variables:{[eF]:{...ki(eF,N),within:[Bi]},[tF]:{...ki(tF,N),within:[oF]}},actions:{[nF]:Ai(eF,rF),"edit.unconfigure":{set:tF,to:N}}}}function lF(e,t,n,r){let i={variable:e,key:e,member:vi};return r.variables[e]={...ki(e,N),...n.length>0&&{within:n}},r.actions[e]=Ai(e,vi),r.segments[e]={template:Ei(e,`(?)`,`✕`),...Ste(n)},Ci(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 Ste(e){let[t,...n]=e;return t===void 0?{}:{when:wi(t,...n)}}const uF=`none`;function dF(e){return Xu(e,`background`)}var Cte=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function wte(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=fF(n,i),l=c!==uF,u=l?c===void 0?o:pF(a,c,`bg`):dF(a);e.bg=u;let d=fF(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:Vv(a,e,t))(u):void 0:pF(a,d,`fg`);return new U({...l&&{bgcolor:H.fromRgba(u)},...f!==void 0&&{color:H.fromRgba(f)}})}function fF(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function pF(e,t,n){try{return Xu(e,t)}catch(e){throw e instanceof Yu?new Cte(t,n,e.message):e}}const mF=`🔧`,hF={help:[`-h`,`--help`],version:[`-V`,`--version`]},gF=[...new Set(Object.values(ax).map(e=>xP(e.switch.setting)))].join(` or `),Tte=Math.max(...Object.values(Jx).map(e=>e.configKey.length))+2,_F=[`✚ inserts`,`✖ removes`,`${mF} configures`,`↺ resets layout`],vF={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`]},Ete=`
|
|
74
74
|
cc-candybar - Beautiful powerline statusline for Claude Code
|
|
75
75
|
|
|
76
76
|
Usage: cc-candybar [options]
|
|
@@ -178,11 +178,11 @@ Config tooling:
|
|
|
178
178
|
`,yF=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`;function Dte(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?D.homedir()+e.slice(1):e}function bF(e,t){return o.resolve(e,Dte(t))}function xF(e,t){return typeof t==`string`&&t!==``?bF(e,t):void 0}const SF=`CC_CANDYBAR_CONFIG`;function CF(e,t){return xF(t,e[SF])}function wF(e,t){return e===void 0?t===void 0?{source:`search`}:{source:`environment`,path:t}:{source:`argument`,path:e}}function TF(e,t,n){return wF(xF(n,e),CF(t,n))}function EF(e,t=`bundled default (no config file loaded)`){return e.join(` < `)||t}const Ote=[`moves`,`can-move`,`still`];function DF(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const kte=[`carried`,`missing`,`unanswered`];function Ate(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:DF(e)===`no`?`unanswered`:`missing`}function jte(e){return{path:e.transcript_path,answered:DF(e)===`yes`}}const OF=[...Ote,`failed`,`drawing`],Mte=[`statusline`,`frames`],kF=e=>e?.kind===`frames`?`frames`:`statusline`;var Nte=class{seen=new Map;see(e,t,n,r){let i=kF(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 AF={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`}}},jF=e=>AF[e];function Pte(e){return jF(e).glyphs.kind===`bundled`}function Fte(e){return jF(e).glyphs.kind===`configured`}const MF=e=>jF(e).label,NF=[{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 PF(e,t){let n=t.codePointAt(0);return NF.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&LF(e,t)===!0)}const FF=Object.keys(AF);function IF(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function LF(e,t){let n=IF(e),r=IF(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 RF(e){for(let t of FF){let n=jF(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 zF(e){let t=FF.find(t=>jF(t).term===e);return t===void 0?null:{name:t,version:null}}function BF(e){let t=RF(e.termtype)??zF(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 VF(e){let t=e.TERM_PROGRAM,n=FF.find(e=>jF(e).program===t),r=n===void 0?zF(e.TERM):{name:n,version:jF(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 HF(e){switch(e.kind){case`known`:return MF(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function UF(e){switch(e.kind){case`known`:return MF(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function WF({name:e,version:t}){let n=jF(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=LF(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const GF=FF.filter(e=>jF(e).links!==null).map(MF).join(`, `);function KF(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(!ss(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||!ss(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function qF(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 JF=[`managed`,`project`],YF=e=>!JF.includes(e.scope),XF={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:is(t.projectDir)}),user:e=>({scope:`user`,path:e})},ZF=[`drawn`,`boxes`],QF=1024*1024,$F=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function eI(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 tI(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const nI=Uc.truecolor;function rI(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 iI={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>rI(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=qF(t.sources,nI);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:`${nI} 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`,nI],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=XF[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 ${nI} to "1" there`}:o(s)})},aI={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>rI(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"})},oI={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:`${$F(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 ${$F(e.value.of)} measured`}},sI={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},cI={argument:`command argument`,environment:`$${SF}`,pick:`load-config pick`,unknown:`source unknown`};function lI({target:e,layers:t}){return e.source===`search`?t.length===0?EF(t):`${EF(t)} (searched)`:`${e.path} (${cI[e.source]})`}function uI(e){switch(e.kind){case`failed`:{let t=[...e.error.split(`
|
|
179
179
|
`).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return t.length===0?[`the config failed to load`]:t}case`loaded`:return[...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${sI[e]}`)]}}const dI={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{let t=lI(e),n=tI(uI(e));return n.ok?{ok:!0,note:t}:{...n,reason:`${t}: ${n.reason}`}}},fI="re-run `cc-candybar install`";function pI(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:// — ${fI}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${fI}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${fI}`)}const mI={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${fI}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${fI}`};case`lost`:return tI([...pI(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}};function hI({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 gI(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${ox.join(`|`)}>\``:e.checkout===null?fI:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function _I(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 — ${gI(e,`native`)}`];let{bundle:i,source:a}=hI(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} — ${gI(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 — ${gI(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 vI=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)`},yI={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`:`${vI(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:tI([...new Set(i.flatMap(e=>_I(n,r,e)))])}};function bI({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||Br(e.identity,t.value.through)):[]}function xI(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const SI={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`?xI(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return tI([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=bI(e.value,n),u=tI([...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 ${Lr(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 ${Lr(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&Ur(o.charge.bytes,s)?[`the daemon holds ${qr(o.charge)} of its ${Lr(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}}}},CI=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function wI(e,t){let n=HF(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?WF(e.terminal):{kind:`unknown`}}function TI({identified:e,tmuxClient:t},n){let r=UF(e),i=wI(e,n),a=HF(e)===null?CI:`${CI}, 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: ${GF}`];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 EI={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 tI(TI(t,n))}}},DI=e=>e.filter(e=>e.role===`statusline`),OI={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})=>jI(e,kI(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:AI(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:vI(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}}},kI=e=>{let t=DI(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`}},AI=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function jI(e,t){let n=KF(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 AI(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 YF(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 MI=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function NI(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return UF(e);case`bundling`:case`unread`:case`configured`:return[MF(e.name),e.version].filter(e=>e!==null).join(` `)}}function PI(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return HF(e);case`bundling`:case`unread`:return MF(e.name);case`configured`:{let t=MF(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 FI(e){let t=PI(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${MI(e.glyphs)}`}}const II={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=FI(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=NI(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 ${MI(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=AF[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:LF(i.version,e);if(t===!0)return{ok:!0};let n=MF(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 ${MI(n)} — set a Nerd Font as its font`)}}}};function LI(e){return e.join(`, `)}function RI(e){return`or set missingData: "ignore" on ${LI(e)}`}function zI(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${LI(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`?[`${LI(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${RI(t)}`]:[`${LI(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${RI(t)}`]}function BI(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${LI(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${LI(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`:`${LI(n)}: ${vI(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`)?[`${LI(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${LI(n)}`]:[]}const VI={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>tI([...zI(e.pullRequests),...BI(e.rateLimits,t)])};function HI({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 ${QF/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const UI=[dI,yI,SI,mI,EI,iI,aI,oI,OI,II,VI,{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`:`${vI(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:tI(e.value.flatMap(HI))}],WI=UI.filter(e=>e.takesMark);function GI(e){return UI.map(t=>({check:t,verdict:t.probe(e)}))}function KI(e){return UI.find(t=>t.name===e)}const qI=`${P}doctor.`;function JI(e){let t=`${qI}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function YI({target:e}){return`configTarget=${e.source}`}function XI(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?HF(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 ZI(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 QI(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}=hI(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const $I=e=>`${e>=0?`+`:``}${Lr(e)}`;function eL({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${xI(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`:`${bI(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Jr(i.charge)}${i.charge.kind===`stand-in`?`(${$I(-i.charge.gap)})`:``}:${Lr(i.charge.bytes)}`}/${Lr(a)} postMortems=${s}`}function tL(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 nL(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>rL(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${R(i)}`;let a=DI(r.flatMap(e=>e.bars));return`frames=${OF.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${R(i)}`}function rL(e){let t=KF(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 iL(e){let t=qF(e,nI);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${R(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function aL(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 oL(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=FI(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 sL(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function cL(e){return e.flatMap(({check:e,verdict:t})=>{let n=JI(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:Gy},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:sL(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?Gy:Wy},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const lL={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function uL(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(lL).map(([t,n])=>[`${e}${t}`,n]))}}const dL=`armed`,fL=`disarmed`,pL=`.armed`,mL=e=>e.endsWith(pL);function hL(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 gL(e,t,n){let r=`${e}${pL}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${dL}")`,s=hL(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:dL},[a]:{set:r,to:fL},...s.actions},armed:o,variables:{[e]:{kind:`state`,key:r,default:fL}},disarm:a}}const _L=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function vL(e){return typeof e==`string`&&_L.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 yL(e){let t=vL(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const bL=[`/compact`,`/model`],xL=`/clear`;function SL(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=gL(`${e}clear`,{arm:xL,confirm:`${xL} ✓ confirm`},[{action:n,when:`true`}]);return{template:bL.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${ix} }}`,actions:{...Object.fromEntries(bL.map(e=>[t(e),{slash:yL(e)}])),...r.actions,[n]:{slash:yL(xL)}},variables:r.variables,disarm:r.disarm}}const CL=Array.from({length:10},(e,t)=>(t+1)*1e5),wL=CL[0],TL=CL[CL.length-1];function EL(e){let t;try{t=ts(e)}catch(e){return L(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?F(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=wL&&n<=TL?F(n):L(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${wL}–${TL} tokens)`)}function DL(e,t){let n=Math.min(t??TL,TL),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:CL.filter(e=>e<r).at(-1)??0,higher:CL.find(e=>e>r&&e<=n)??0}}function OL(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${ix} }}{{ 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:yL(`/autocompact auto`)},...Object.fromEntries(CL.map(t=>[`${e}${t}`,{slash:yL(`/autocompact ${t}`)}]))}}}const kL=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 }}`,AL=`${P}edit`,jL=`${P}toolbar`,ML=uL(P),NL=`${P}commands`,PL=SL(`${NL}.`),FL=`${P}autocompact`,IL=OL(`${FL}.`,kL),LL=e=>({kind:`segment`,name:e}),RL=`${P}tab`,zL=e=>`${RL}.${e}`,BL=e=>`${zL(e)}.toggle`,VL=e=>({variable:RL,key:RL,member:e}),HL=`${P}save`,UL=`${P}preset.save`,WL=`${P}preset.delete`,GL=e=>`${P}${e}`,KL=e=>`${P}apply.${e}`,qL=e=>`${P}reset.${e}`,JL=`${P}themeDefault.save`,YL=`${P}themeDefault.differs`,XL=`${P}themeDefault.theme`,ZL={when:`{{ .${YL} }}`,template:`{{ action "${JL}" (printf "⤓ default for %s" .${XL}) }} {{ swatch "${KL(`theme`)}" .${XL} }}`},QL=`${P}resetAll`,$L=`${Ri}.toggle`,eR=`${P}undo`,tR=`${P}back`,nR=`${tR}.step`,rR=`${P}navigation.back`,iR=tR,aR={template:`{{ if gt .${rR} 0 }}{{ action "${tR}" "◁" }}{{ else }}{{ fg (${yF}) "◁" }}{{ end }}`},oR=`${P}redo`,sR=`${P}doctor`,cR=`${sR}.run`,lR=e=>`${sR}.fix.${e}`,uR=(e,t)=>`${sR}.mark.${e}.${t}`,dR=e=>`${sR}.${e}`,fR={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},pR=$N(`${P}pickers`),mR=e=>`${P}${e}`,hR=e=>`${mR(e)}.toggle`,gR=e=>vP(e)?$N(`${P}${e}Pickers`):pR,_R=e=>{let t=gR(_P[hP[e].beside]);return{variable:t,key:t,member:e}},vR={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${WL}" (printf "🚮 delete %s" .${Jx.preset.effectiveVar}) }}`}},yR=(e,t)=>`${P}list.${e}.${t}`,bR=e=>`${P}resettable.${e}`,xR=e=>e.length===0?`false`:`(or ${e.map(e=>`(and (${e.shown}) .${bR(e.name)})`).join(` `)})`,SR=ox.map(e=>[ax[e].switch.setting,e]),CR={variables:{},actions:{},segments:{}},wR=Object.fromEntries(SR.map(([e,t])=>[e,lF(`${P}help.${e}`,vF[t],[],CR)])),TR=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],ER=e=>{let t=t=>`.${dx(e,t)}`,n=TR.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if eq .${Jx[ax[e].switch.setting].effectiveVar} ${JSON.stringify(ax[e].switch.on)} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},DR=`{{ if .diagnostics.label }} {{ bg .diagnostics.bg (fg .diagnostics.fg (action "${Vi}" .diagnostics.label .diagnostics.open)) }}{{ end }}`,OR=`${P}fps`,kR=`{{ if eq .${lx(`by`)} "feed" }}{{ printf "%3s" (printf "≤%d" (int .${lx(`fps`)})) }} fps{{ else }}${`polled`.padStart(7)}{{ end }}`,AR=Object.fromEntries(SR.map(([e,t])=>[e,ER(t)])),jR=e=>gP.filter(t=>hP[t].beside===e),MR=Object.keys(Jx).map(e=>{let t=Jx[e],n=_P[e];return{...t,name:e,place:n,control:dP({label:t.label,domain:TP(t.configKey)},t.sessionKey,t.effectiveVar,KL(e),gR(n)),beneath:t.previews.map(e=>vR[e]),help:[wR[e]].filter(e=>e!==void 0),submenus:jR(e)}}),NR=e=>MR.filter(t=>t.place===e),PR=e=>MR.filter(t=>yP(t.place,e)),FR=e=>t=>`(print ${Oi(t)} (ternary ${Oi(` •`)} "" ${xR(PR(e))}))`,IR=e=>NR(e).flatMap(e=>[JR(e),...e.help,...e.submenus.map(e=>Ci(mR(e),_R(e),tz(e),`drop`))].map(t=>({...t,when:`{{ ${e.shown} }}`})));new Set(MR.flatMap(e=>[e.sessionKey,e.configKey]));const LR=gL(QL,{arm:`⟲`,confirm:`⟲ reset all?`},MR.map(e=>({action:qL(e.name),when:e.shown}))),RR=[`unsaved`,`history.undo`,`history.redo`],zR=e=>`${P}${e}`,BR=zR(`unsaved`),VR=(e,t)=>({body:t,shown:`(gt .${zR(e)} 0)`}),HR=[VR(`unsaved`,`{{ action "${HL}" (printf "💾 save %d" .${BR}) }}`),VR(`history.undo`,`{{ action "${eR}" "↶" }}`),VR(`history.redo`,`{{ action "${oR}" "↷" }}`),{body:LR.template,shown:`(or ${xR(MR)} ${LR.armed})`}],UR={when:`{{ or ${HR.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+HR.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},WR=[{step:LR,place:`door`},{step:PL,place:`session`}],GR=e=>e.map(e=>e.step.disarm),KR=GR(WR),qR=GR(WR.filter(e=>e.place!==`door`));function JR(e){let t=GL(e.name);return e.control.kind===`inline`?LL(t):Ci(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>LL(yR(e.name,n)))},`drop`)}function YR(e){return e===Ri}function XR(e){let t=LL(Ri);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[XR(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 ZR(e){return QR(e)>0?e:XR(e)}function QR(e){let t=0;for(let n of nb(e))n.kind===`segment`&&YR(n.name)&&(t+=1);return t}function $R(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&YR(e.name)||e.opens!==void 0&&$R(e.opens.body,!0):e.children.some(e=>$R(e,n))}const ez={door:{direction:`horizontal`,content:[LL(iR)],after:[LL(AL),LL(HL)]},session:{direction:`vertical`,content:[LL(jL),{kind:`container`,direction:`horizontal`,children:[LL(NL),LL(FL)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[LL(UL)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[LL(sR),...UI.map(e=>LL(dR(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[LL(JL)]},toggles:{direction:`horizontal`,content:[],after:[]}};function tz(e){let{direction:t,content:n,after:r}=ez[e];return{kind:`container`,direction:t,children:[...n,...IR(e),...r]}}function nz(e){return e.kind===`segment`?YR(e.name)?{kind:`container`,direction:`horizontal`,children:[Ci(e.name,Bi,iz,`above`),LL(OR)]}:e:az(e)}function rz(){return{kind:`container`,direction:`vertical`,children:[tz(`door`),{kind:`container`,direction:`horizontal`,children:pP.map(({member:e})=>Ci(zL(e),VL(e),tz(e),`drop`))}]}}const iz=rz();function az(e){return{...e,children:e.children.map(e=>nz(e))}}function oz(e){let t={variables:{[Ri]:ki(Ri,N),[Vi]:{kind:`state`,key:Vi,default:`0`}},actions:{[$L]:Ai(Ri,zi),[Vi]:{set:Vi,int:!0},[Ri]:{do:[$L,...KR]},[cR]:{doctor:`run`},...ML.actions,...PL.actions,...IL.actions,[HL]:{save:!0},[eR]:{undo:!0},[nR]:{back:!0},[tR]:{do:[nR,...KR]},[oR]:{redo:!0},[UL]:{preset:`save`},[JL]:{themeDefault:`save`},[WL]:{preset:`delete`,name:`{{ .${Jx.preset.effectiveVar} }}`}},segments:{[Ri]:{template:`{{ $door := ${Di(Ri,Oi(e),Oi(`✖`))} }}{{ if ${Ti(Bi)} }}{{ fg (keptOn (roleTextOn "error" (bgOf)) (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+DR},[OR]:{template:kR},[jL]:{template:ML.template},[NL]:{template:PL.template,when:PL.when},[FL]:{template:IL.template,bg:IL.bg,when:IL.when},[iR]:aR,[HL]:UR,[JL]:ZL,[UL]:{template:`{{ action "${UL}" "+ preset" }}`},[sR]:{template:`{{ action "${cR}" "🩺 doctor" }}`},[AL]:{template:`{{ action "${nF}" "✎ arrange" "✎ done" }}`}}};t.variables[YL]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[XL]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[rR]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of RR)t.variables[zR(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[RL]=ki(RL,N);for(let{member:e,label:n}of pP){t.actions[BL(e)]=Ai(RL,e),t.actions[zL(e)]={do:[BL(e),...qR]};let r=FR(e);t.segments[zL(e)]={template:`{{ ${Di(zL(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,PL.variables,LR.variables),cz(t),sz(t),t}function sz(e){for(let t of UI){let n=JI(t.name),r=lR(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?ZF:[];for(let n of i)e.actions[uR(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${uR(t.name,e)}" "${fR[e]}" }}`).join(``);e.segments[dR(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} "${Wy}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function cz(e){for(let t of MR){Object.assign(e.actions,t.control.actions);let n=qL(t.name);e.actions[n]={reset:t.configKey},e.variables[bR(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${bR(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[GL(t.name)]={template:`${t.control.template}${AR[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[yR(t.name,r)]=n})}Object.assign(e.actions,LR.actions),Object.assign(e.variables,CR.variables),Object.assign(e.actions,CR.actions),Object.assign(e.segments,CR.segments);for(let t of gP){let n=_R(t);e.actions[hR(t)]=Ai(n.key,n.member),e.segments[mR(t)]={template:`{{ action "${hR(t)}" ${FR(t)(hP[t].trigger)} }}`}}}function lz(e){let{variables:t,actions:n}=cF();Object.assign(e.variables,t),Object.assign(e.actions,n)}function uz(e){let t=oz(e.globals.menuGlyph??`🍫`);lz(t);let n={...e.presets},r=[];for(let t of Tw(e.presets)){let{node:i}=Ow(e,t),a=nz(ZR(i));r.push(a),n[t]={...Dw(e.presets,t),root:a}}let i=YN(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const dz=`${Fi}live`,fz=[`☐ live`,`☑ live`],pz=`${Fi}done`,mz=`${Fi}cancel`,hz=`${Fi}rewind`,gz=`${Fi}changes`,_z=`(gt .${gz} 0)`,vz=`(or ${_z} (gt .${BR} 0))`,yz={variable:dz,key:dz,member:vi};function bz(e){return`${Fi}configuring.p${e}`}function xz(e){return`and ${Ti(oF)} (not ${Ti(yz)}) (ne .${bz(e)} "true")`}function Sz(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${tF} "${Si(e)}")`).join(` `)} false }}`}}function Cz(e,t,n){return`{{ if ${xz(e)} }}${t}{{ else }}${n}{{ end }}`}const wz=`{{ and ${Ti(oF)} .preset.customized }}`,Tz=Li;function Ez(e){return new Map([...Fw(e),...Oz(e)])}const Dz=`${Fi}addable`;function Oz(e){return new Map([[Dz,{members:Object.keys(e.segments).filter(e=>!Tz(e)),library:{groups:hte.map(e=>({id:e,label:gte[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function kz(e,t,n){return n.segments[e]={template:t,when:sF,bg:uF},{kind:`segment`,name:e}}function Az(e,t,n){let r=`${Fi}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Bv}`}) (action "${r}" "✖") }}`}function jz(e){return`{{ if ${Ti(oF)} }}${e}{{ end }}`}function Mz(e,t){return e.reduce((e,t)=>`{{ if and ${Ti(oF)} ${Ti(t)} }}true{{ else }}${e}{{ end }}`,t)}function Nz(e){return e.flatMap(e=>[...nb(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function Pz(e,t,n){return`${iF}${e}.${t}.${n}`}function Fz(e,t,n,r){let i=Qy(n),a=`${Fi}${e.presetIdent}`,o=aF(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=$N(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:N},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:tF,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=Pz(e.presetIdent,i,r),l=`${iF}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:bb(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=dP(lP(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 Ci(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${mF}" }}`,ref:{variable:tF,key:tF,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const Iz=`${Fi}label:`;function Lz(e){if(e.startsWith(Iz)){let t=e.slice(Iz.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function Rz(e,t,n,r){let i=Qy(e),a=zz(n,i,e,t,i),o=Object.fromEntries(hb.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...Ci(a,r.ref,r.body,`drop`,Mz([r.ref],`{{ ${xz(n.presetIdent)} }}`)),...Object.keys(o).length>0&&{settings:o},drafts:Object.fromEntries(hb.map(e=>[e,r.drafts[e]]))}}function zz(e,t,n,r,i){let a=`${Iz}${t}:${n.name}`;return e.artifacts.segments[a]={template:`{{ "${Si(i)}" }}`,...r.palette!==void 0&&{palette:r.palette}},a}function Bz(e,t,n,r){let i=Qy(e),a=n?[Uz(r,String(r.posCounter.n++),i,`before`)]:[],o=String(r.posCounter.n++),s=Uz(r,o,i,`after`),c=Az(r,o,i),l=r.segments[e.name],u=Fz(r,o,e,gb(l)),d=jz(c),f=jz(u.term);return[...a.map(e=>kz(e.host,e.template,r.artifacts)),{...Rz(e,l,r,u),lead:d,trail:f},{...t,when:Cz(r.presetIdent,`false`,e.when??`true`),lead:d,trail:f,drafts:u.drafts},kz(s.host,s.template,r.artifacts)]}function Vz(e){return o.join(o.basename(o.dirname(e)),o.basename(e))}function Hz(e,t,n,r){let i=r.segments[e.name],a=Qy(e);return[{kind:`segment`,name:zz(r,`${a}/${r.presetIdent}`,e,i,`${a} · ${Vz(t.file)} ${t.entry}`),when:`{{ ${xz(r.presetIdent)} }}`},{...n,when:Cz(r.presetIdent,`false`,e.when??`true`)}]}function Uz(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${Fi}${i}.insert.${t}`,s=`${Fi}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:Dz,anchor:n,relation:r};let c=ZN(o),l=QN(s,o,void 0),u=tP(l),d=eP(l,c);return a.variables[l]={...ki(l,N),within:[oF]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=Ai(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${Ti({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Bv}`}) $m }}{{ end }}`}}function Wz(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!Tz(e.name)&&e.insertedBy===void 0),i=e=>Wz(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=tb(o,i);if(Tz(o.name)){n.push(s);continue}let c={kind:`container`,direction:`horizontal`,children:o.insertedBy===void 0?Bz(o,s,a===r,t):Hz(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:Mz(Nz(n),Cz(t.presetIdent,`true`,e.when))}}}function Gz(e,t,n,r,i,a,o){let s=`${Fi}${t}.resetLayout`,c=`${Fi}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:wz},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},Kz(e,o)]}}function Kz(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),Kz(n,t)]}:{...e,children:[...e.children,t]}}function qz(e,t,n,r,i,a){let{node:o}=Ow(e,t),s={presetIdent:XN(t),rootKey:KP(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=Wz(o,s);return n.variables[bz(s.presetIdent)]=Sz(s.configured),Gz(c,s.presetIdent,s.rootKey,n,r,i,a)}function Jz(e){let t={variables:{},actions:{},segments:{}},n=lF(`${Fi}help`,_F,[oF],t);t.variables[dz]=ki(dz,N),t.actions[dz]=Ai(dz,yz.member),t.segments[dz]={template:Ei(dz,...fz),when:sF};let r={kind:`segment`,name:dz},i=n;t.variables[gz]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[pz]={do:[HL,nF]},t.segments[pz]={template:`{{ if ${vz} }}{{ action "${pz}" "✓ save" }}{{ else }}{{ action "${pz}" "✓ done" }}{{ end }}`,when:sF},t.actions[hz]={rewind:!0},t.actions[mz]={do:[hz,nF]},t.segments[mz]={template:`{{ action "${mz}" "↩ cancel" }}`,when:`{{ and ${Ti(oF)} ${_z} }}`};let a=[{kind:`segment`,name:pz},{kind:`segment`,name:mz}],o={...e.presets},s=[];for(let n of Tw(e.presets)){let c=qz(e,n,t,a,r,i);s.push(c),o[n]={...Dw(e.presets,n),root:c}}let c=YN(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function Yz(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function Xz(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 Zz(e,t,n){let r=eb(e,new Set(n.map($y).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const Qz=/^-?\d+$/;function $z(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 eB(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!Qz.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 tB(e,t,n){return r=>r?Qz.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 nB(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=>!Qz.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 rB(e){return e===`config`?`set-config`:`set-state`}function iB(e,t,n){return t.kind===`int`?eB(`menu page "${e}"`):t.kind===`range`?tB(t.min,t.max,`${n} stepper "${e}"`):$z(t.allowed,`${n} "${e}"`,rB(n))}function aB(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:nB(e,n,t)}))}function oB(e,t,n,r){let i=new Map(Object.entries(e)),a=new Map,o=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of n)if(o.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let s=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...n];for(let{key:t,spec:n}of aB(s,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,iB(t,n,r)),n.kind===`range`&&a.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>a.get(e)??null}}function sB(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};oB(e,[o],[],t),r.push(o),i++;let s=!0;return()=>{s&&(s=!1,r.splice(r.indexOf(o),1),i++)}},gateFor(o){let s=a.get(o);if(s?.epoch===i)return s.gate;let c=oB(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const cB=sB({},`config`,hB);function lB(e,t){return cB.register(e,t)}function uB(e){return cB.gateFor(e)}function dB(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:Lw(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:[Yz({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Yz({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Lw(e.insertSegmentFrom,t).members.map(t=>Yz({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function fB(e,t){let n=lte(e).get(t);return n===void 0?null:String(n)}function pB(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?YP(n.persist):null;e?.scope===`preset-root`&&t.add(KP(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function mB(e){let t=Ez(e);return[...pB(e),...Object.values(e.actions).flatMap(e=>dB(e,t))]}function hB(e){return aB(mB(e),`config`)}function gB(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:yB(t.segments,_B(t.segments,e.segments??{})),root:gw(e.root??lw,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:yB(t.presets,vB(t.presets,e.presets??{})),themeDefaults:yB(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function _B(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 vB(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 yB(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function bB(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: ${cb.join(`, `)})`,line:q(e.source,t.split(`.`))}),null):CB(e,`${t}.cache`,n.cache)}function xB(e){return{required:!0,json:wB(),parse:(t,n,r,i)=>bB(t,n,i,e)??void 0}}const SB={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&EB(n)?{ttl:n}:Lb(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${J(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return Lb(e,t,`cache.watch_file must be a path string, got ${J(n)}`);let r=Yb(`cache.watch_file`,n);return r===null?{watch_file:n}:Lb(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}:Lb(e,t,`cache.depends_on must be an array of variable-name strings, got ${J(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:Lb(e,t,`cache.key must be a non-empty template string, got ${J(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:Lb(e,t,`cache.never must be the literal boolean true, got ${J(n)}`)}}};function CB(e,t,n){return Rb(e,SB,t,n)}function wB(){return nx(SB)}const TB=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function EB(e){return TB.test(e)}const DB=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 OB(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 kB(e){let t=DB.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${OB(t)}`}function AB(e){let t=DB.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${OB(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const jB=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`]]),MB=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 NB(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 PB(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`?MB.get(e.field):void 0;if(n===void 0){let e=[...MB.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 ${NB(n.declare)} under a name of your own`}function FB(e,t,n){if(n===void 0)return{};if(!Ab(n))return e.issues.push({path:t,message:`${t} must be an object, got ${jb(n)}`,line:q(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=zb(e,aV,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function IB(){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 ${jb(i)}`,line:q(e.source,t.split(`.`))});return}return i}}}function LB(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Lee(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const RB={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:Lb(e,t,`parse.text must be the literal boolean true, got ${J(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?zB(e,t,n):Lb(e,t,`parse.regex must be a pattern string, got ${J(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:Lb(e,t,`parse.json must be the literal boolean true, got ${J(n)}`)}}};function zB(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return Lb(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:Lb(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function BB(){return{required:!1,json:nx(RB),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:q(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:Rb(e,RB,`${t}.parse`,r.parse)??void 0)}}function VB(){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)=>Ab(r.parse)&&`json`in r.parse?HB(e,t,r.default):Db(e,t,r,`default`)}}function HB(e,t,n){if(n!==void 0)return UB(n)?n:Lb(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${J(n)}`)??void 0}function UB(e){return e!==null&&WB(e)}function WB(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(WB);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(WB)}default:return!1}}const GB={value:IB(),default:Ub()};function KB(){let e=Jb();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:jB.get(a);return o===void 0?a:Lb(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const qB={path:KB(),type:Zb([`string`,`number`,`boolean`]),default:LB()},JB={name:Jb(),default:Ub()},YB={path:Xb(),readMode:Zb([`whole`,`first-line`]),parse:BB(),cache:xB(`file`),default:VB()},XB={command:Jb(),parse:BB(),cache:xB(`shell`),default:VB()};function ZB(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const QB={template:Jb(),type:Zb([`string`,`number`,`boolean`]),default:LB()},$B=ZB(`a template variable recomputes whenever a variable it reads changes`),eV={layout:Jb(),default:Ub()},tV=ZB(`a time variable reads the instant its render is drawn at`),nV={key:Jb(),default:Ub()},rV=`kind`;function iV(e,t,n={}){return{...Bb(rV,e,t),parse:(r,i,a)=>{Nb(r,n,i,a);let o=Pb(r,t,i,a);return o===null?null:{kind:e,...o}}}}const aV={tag:rV,noun:`source kind`,memberNoun:`variable`,arms:{literal:iV(`literal`,GB),input:iV(`input`,qB),env:iV(`env`,JB),file:iV(`file`,YB),shell:iV(`shell`,XB),template:iV(`template`,QB,$B),time:iV(`time`,eV,tV),state:iV(`state`,nV)},retired:{git:PB}};function oV(){return tx(aV)}function sV(){return{type:`object`,additionalProperties:oV()}}const cV=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 lV(e){let t=cV.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})`}}const uV=/^[A-Za-z_][A-Za-z0-9_]*$/,dV={pattern:uV.source},fV={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},pV={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`,...dV}}}]},default:fV}},mV=[`label`,`domain`,`default`],hV=[`min`,`max`,`step`,`atLeast`];function gV(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,t.split(`.`))})}function _V(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 gV(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 gV(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?gV(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(Ab(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!hV.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}}:gV(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 gV(e,t,`domain must be "bool", a list of words, or { min, max }, got ${J(n)}`)}function vV(e,t,n){if(!Ab(n))return gV(e,t,`${t} must be { label, domain, default }, got ${jb(n)}`);for(let r of Object.keys(n))mV.includes(r)||gV(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${mV.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||gV(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${J(r)}`);let a=_V(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!yV(n.default)||!yb(o,n.default)?gV(e,`${t}.default`,`default must be ${Sb(o)}, got ${J(n.default)}`):o}function yV(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const bV={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${pb}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function xV(e){return hb.includes(e)}function SV(){return{required:!1,json:{type:`object`,propertyNames:{...dV,not:{enum:[...hb]}},additionalProperties:pV},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Ab(i))return gV(e,a,`${a} must be an object of name → { label, domain, default }, got ${jb(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!uV.test(t)){gV(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(xV(t)){gV(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${bV[t]}`);continue}let r=vV(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const CV=Ii.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function wV(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${CV})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!Li(i)?i:gV(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${Ii.map(e=>`"${e}"`).join(`, `)} namespaces, got ${J(i)}`)}}}function TV(){return{required:!1,json:{type:`object`,propertyNames:dV,additionalProperties:fV},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Ab(i))return gV(e,a,`a placement's "settings" must be an object of setting name → value, got ${jb(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))yV(n)?o[t]=n:gV(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${jb(n)}`);return o}}}function EV(e){return new Set(Object.keys(e.segments).filter(e=>!Li(e)))}function DV(e,t,n){if(t===void 0)return{};if(!Ab(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${jb(t)}`,line:q(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=Mb(e,n.has(i)?LV:IV,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function OV(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 ${jb(s)}`,line:q(e.source,[...t.split(`.`),n])})}return r?a.join(``):void 0}e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be a string or an array of strings, got ${jb(i)}`,line:q(e.source,[...t.split(`.`),n])})}const kV={anyOf:[{type:`string`},{type:`array`,items:{type:`string`}}]};function AV(){return{required:!0,json:kV,parse:(e,t,n,r)=>r[n]===void 0?Lb(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${lV(t.slice(9))}`)??void 0:OV(e,t,n,r)}}function jV(){return{required:!1,json:kV,parse:(e,t,n,r)=>r[n]===void 0?void 0:OV(e,t,n,r)}}function MV(){return{required:!1,json:{type:`object`,additionalProperties:kV},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;if(!Ab(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be an object, got ${jb(i)}`,line:q(e.source,[...t.split(`.`),n])});return}let a=Object.create(null);for(let r of Object.keys(i)){let o=OV(e,`${t}.${n}`,r,i);o!==void 0&&(a[r]=o)}return a}}}function NV(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${J(i)}`,line:q(e.source,[...t.split(`.`),n])})}}}}function PV(){return{required:!1,json:sV(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return FB(e,`${t}.${n}`,i)}}}const FV={template:AV(),description:Ub(),group:Zb(ZP),width:NV(),justify:Zb(Dee),truncate:Zb(Oee),bg:Ub(),fg:Ub(),when:Ub(),palette:qb(),vars:PV(),settings:SV(),missingData:Zb(wee),partials:MV()},IV={noun:`segment key`,fields:FV},LV={noun:`segment key`,fields:{...FV,template:jV()}},RV=`#/definitions/LayoutNode`,zV={kind:`container`,direction:`vertical`,children:[]};function BV(e){return{required:!0,json:{const:e},parse:()=>e}}function VV(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${J(i)}`,line:q(e.source,[`root`])}),``)}}}function HV(){return{required:!0,json:{enum:[...Xy]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Xy.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${Xy.join(`, `)} (got ${JSON.stringify(i)})`,line:q(e.source,[`root`])}),`vertical`)}}}function UV(e){return{required:!0,json:{type:`array`,items:{$ref:RV}},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 ${jb(a)}`,line:q(t.source,[`root`])}),[])}}}const WV={noun:`layout-node key`,fields:{kind:BV(`segment`),name:VV(),when:Ub(),id:wV(),settings:TV()}},GV=()=>Zb(Sv),KV={noun:`layout-node key`,fields:{kind:BV(`container`),direction:HV(),children:UV(Vb(()=>ZV)),when:Ub(),distribution:GV()}};function qV(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${J(i)}`,line:q(e.source,[...t.split(`.`),n])}),``)}}}const JV={noun:`layout-node key`,fields:{seg:qV(),when:Ub(),id:wV(),settings:TV()}},YV={noun:`layout-node key`,fields:{h:UV(Vb(()=>ZV)),when:Ub(),distribution:GV()}},XV={noun:`layout-node key`,fields:{v:UV(Vb(()=>ZV)),when:Ub(),distribution:GV()}},ZV=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:q(e.source,[`root`])}),zV):{kind:`segment`,name:n};if(!Ab(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 ${jb(n)}`,line:q(e.source,[`root`])}),zV;if(n.kind===`container`)return Mb(e,KV,t,n)??zV;if(n.kind===`segment`)return Mb(e,WV,t,n)??zV;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
180
180
|
Old: { kind: "cells", segments: ["seg1", "seg2"] }
|
|
181
|
-
New: { h: ["seg1", "seg2"] }`,line:q(e.source,[`root`])}),zV;if(n.kind===`group`){let r=Mb(e,oH,t,n);return r===null?zV:(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}),cH(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:q(e.source,[`root`])}),zV}if(a){let r=Mb(e,JV,t,n);return r===null?zV:{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=Mb(e,YV,t,n);return r===null?zV:{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=Mb(e,XV,t,n);return r===null?zV:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:q(e.source,[`root`])}),zV};function QV(){return{required:!0,json:{type:`object`,propertyNames:{pattern:sw.source},additionalProperties:{$ref:RV}},parse:(e,t,n,r)=>{let i=r[n];if(!Ab(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${jb(i)}`,line:q(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!sw.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:q(e.source,[...t.split(`.`),n,r])});continue}a[r]=ZV(e,`${t}.${n}.${r}`,o)}return a}}}const $V={noun:`root key`,fields:{rows:QV(),when:Ub(),distribution:GV()}};function eH(e,t,n){return Ab(n)&&`rows`in n?Mb(e,$V,t,n)??{rows:{}}:ZV(e,t,n)}const tH={noun:`insert key`,fields:{seg:qV(),id:wV(),before:Ub(),after:Ub()}};function nH(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=Mb(e,tH,i,t);if(a===null)return[];let o=[`before`,`after`].filter(e=>a[e]!==void 0);if(o.length!==1)return e.issues.push({path:i,message:`an insert cell names exactly one of "before" or "after" (the placement id it sits beside), got ${o.length===0?`neither`:`both`}`,line:q(e.source,i.split(`.`))}),[];if(Li(a.seg))return e.issues.push({path:`${i}.seg`,message:`an insert cell places a segment, and "${a.seg}" is the bar's own chrome — name a segment instead`,line:q(e.source,[...i.split(`.`),`seg`])}),[];let s=o[0],c=a[s];return Li(c)?(e.issues.push({path:`${i}.${s}`,message:`an insert cell sits beside a placement, and "${c}" is the bar's own chrome — anchor on a placement id instead`,line:q(e.source,[...i.split(`.`),s])}),[]):[{seg:a.seg,...a.id!==void 0&&{id:a.id},anchor:c,relation:s,by:{file:n,entry:i}}]}):(e.issues.push({path:`insert`,message:`"insert" must be a list of cells like { seg: "name", after: "placement" }, got ${jb(t)}`,line:q(e.source,[`insert`])}),[])}function rH(){return{required:!0,json:{type:`string`,pattern:sw.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!sw.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 "${N}", got ${J(i)}`,line:q(e.source,[`root`])});return}return i}}}function iH(){return{required:!1,json:{type:`string`,minLength:1},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`string`||i===``||i.includes(`/`)){e.issues.push({path:`${t}.${n}`,message:`a group "key" must be a non-empty, slash-free SessionState key, got ${J(i)}`,line:q(e.source,[`root`])});return}return i}}}}function aH(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Eb(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:q(e.source,[...t.split(`.`),n])});return}return i}}}}const oH={noun:`layout-node key`,fields:{kind:BV(`group`),name:rH(),label:aH(),open:Wb(),direction:Zb(Xy),key:iH(),bg:Ub(),fg:Ub(),when:Ub(),distribution:GV(),children:UV(Vb(()=>ZV))}};function sH(e){return e.key??`groups.`+e.name}function cH(e){let t=Mi+e.name;return Ci(t,{variable:t,key:sH(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function lH(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,[`root`])})}function uH(e,t){$P(e,t,Mi,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&lH(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}.`)&&sH(t)===sH(r)&&lH(e,t.path,`group "${t.name}" shares key "${sH(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=sH(t);if(i.has(n)||i.set(n,N),t.open===!0){let r=i.get(n);r!==`closed`&&lH(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=Mi+e.name,r=sH(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=ki(r,i.get(r)),o[t]=Ai(r,e.name),s[t]={template:Ei(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 dH=`menu`,fH=`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`,pH=e=>e.kind===`call`&&e.name===`dict`,mH=e=>e.kind===`literal`&&typeof e.value!=`object`,hH=e=>bi(``,e,2)===void 0;function gH(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&&pH(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(pH))return t(`whose options (dict …) is not its last argument — ${fH}`);if(i!==void 0&&a===void 0&&!mH(i)&&hH(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=bi(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${fH}`);let c=a===void 0?{}:Pk(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=aP(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=_te(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 "${$N(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 _H(e){let t=UD({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===dH).map(gH)}catch{return`parse-failed`}}function vH(e,t){let n=_H(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:QN(t,e.apply,e.options.key),member:ZN(e.apply)}]:[])}function yH(e){let t=UD({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(dH)}catch{return!1}}function bH(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,[`root`])})}function xH(e,t){$P(e,t,Ni,`{{ menu }} helpers`),$P(e,t,Pi,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))yH(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:q(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n)){for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&yH(i)&&bH(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??{}))yH(i)&&e.issues.push({path:`segments.${t}.partials.${n}`,message:`segments.${t}.partials.${n} uses {{ menu }}, but a menu must live directly in a segment's "template" string — the synthesis pass that wires its state never follows a {{ template }} call into a partial. Inline the {{ menu }} call into the template itself.`,line:q(e.source,[`segments`,t,`partials`,n])})}if(t.root!==void 0)for(let n of nb(mw(t.root)))typeof n.when==`string`&&yH(n.when)&&bH(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||!yH(r))continue;let n=_H(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:SH(r.apply);n!==void 0&&bH(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function SH(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(ZN(e)===`closed`)return`whose apply action is named "${N}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function CH(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 Tw(e.presets)){let a=new Map,s=new Map;for(let c of nb(Ow(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,_H(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=Qy(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||SH(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=ZN(i),f=QN(u,i,l.key),p=tP(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=eP(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]=Ai(f,d),n[f]=ki(f,N),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 wH(e,t,n){if(t===void 0)return{};if(!Ab(t))return Z(e,`actions`,`actions must be an object, got ${jb(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=TH(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:q(e.source,t.split(`.`))})}function TH(e,t,n,r){if(!Ab(n))return Z(e,t,`${t} must be an action object, got ${jb(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=Bw.filter(e=>e in n);return i.length===1?DH(r)[i[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${Bw.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function EH(e){return e===`<default>`?{dir:D.homedir()}:o.isAbsolute(e)?{dir:o.dirname(e)}:{text:e}}const DH=e=>({set:(e,t,n)=>lU(e,t,n,`set`,aU),persist:(e,t,n)=>lU(e,t,n,`persist`,oU),copy:OH(`copy`),open:OH(`open`),reset:kH,undo:jH(`undo`),redo:jH(`redo`),back:jH(`back`),rewind:jH(`rewind`),save:jH(`save`),preset:MH,themeDefault:NH,doctor:FH,slash:IH,run:zH(e),do:BH});function OH(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=Eb(t,n,r,e);return i===null?null:{[e]:i}}}function kH(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=VH(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 AH={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 jH(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 — ${AH[e]}), got ${J(r[e])}`),null)}}function MH(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 ${J(r)}`),null;if(r===`save`)return{preset:`save`};let a=Eb(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function NH(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 ${J(n.themeDefault)}`),null)}const PH={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function FH(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(PH,r),a=i?PH[r]:[...new Set(Object.values(PH).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(PH).map(e=>`"${e}"`).join(`, `)}, got ${J(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?WI:UI;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 ${J(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return ZF.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${ZF.map(e=>`"${e}"`).join(` or `)}, got ${J(c)}`),null)}function IH(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=vL(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}const LH=[`run`,`env`,`refreshes`],RH=/^[A-Za-z_][A-Za-z0-9_]*$/;function zH(e){return(t,n,r)=>{for(let e of Object.keys(r))LH.includes(e)||Z(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${LH.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 ${J(a)}`);let o=r.env??{};(!Ab(o)||Object.entries(o).some(([e,t])=>!RH.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 ${J(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 ${J(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}}}RH.source;function BH(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 ${J(r)}`),null):{do:r}}function VH(e,t,n,r,i,a){let o=Eb(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 HH={set:`the SessionState key to write`,persist:`the config globals field to write`};function UH(e,t,n,r){let i=HH[r],a=VH(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);return a===null?null:{[r]:a}}function WH(e){return e===`set`?`set-state`:`set-config`}const GH={to:uU(`set`)},KH={to:uU(`persist`)},qH={from:dU(`set`)},JH={from:dU(`persist`)},YH={min:gU(),max:gU(),by:gU()},XH={int:pU()},ZH={cycle:fU(`set`)},QH={cycle:fU(`persist`)},$H={removeSegment:mU(`removeSegment`)},eU={insertSegment:mU(`insertSegment`),anchor:mU(`anchor`),relation:hU()},tU={insertSegmentFrom:dU(`persist`),anchor:mU(`anchor`),relation:hU()},nU={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},rU={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function iU(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>Pb(e,t,n,r),c=Qb(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?Hb(s,...n):s}}const aU=[iU(`set`,GH),iU(`set`,qH),iU(`set`,YH,[nU,rU]),iU(`set`,XH),iU(`set`,ZH)],oU=[iU(`persist`,KH),iU(`persist`,JH),iU(`persist`,YH,[nU,rU]),iU(`persist`,QH),iU(`persist`,$H),iU(`persist`,eU,[],[`insertSegment`]),iU(`persist`,tU,[],[`insertSegmentFrom`])];function sU(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 cU(e){let t=sU(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 lU(e,t,n,r,i){let a=UH(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${cU(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 uU(e){let t=WH(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>VH(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 dU(e){let t=WH(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 ${J(o)}`)}}}function fU(e){let t=WH(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 ${jb(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 pU(){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 ${J(r[n])}`);return}return!0}}}function mU(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Eb(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 hU(){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 ${J(i)}`);return}return i}}}function gU(){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 ${J(i)}`);return}return i}}}function _U(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const vU={noun:`style key`,fields:{hueShift:Kb(),chromaScale:Kb({min:0}),lightnessScale:Kb(),lightnessShift:Kb()}};function yU(e,t){if(!Ab(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${jb(t)}`,line:q(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:q(e.source,[`styles`,r])});continue}if(Ry(r)){e.issues.push({path:`styles.${r}`,message:_U(`styles.${r}`,r,`globals.endcaps`),line:q(e.source,[`styles`,r])});continue}let t=Mb(e,vU,`styles.${r}`,i);t!==null&&(n[r]={...Pu,...t})}return n}const bU={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:eH(e,`${t}.${n}`,r[n])},globals:{required:!1,json:HP(),parse:(e,t,n,r)=>r[n]===void 0?void 0:VP(e,`${t}.${n}`,r[n])}}};function xU(e,t){if(!Ab(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${jb(t)}`,line:q(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:q(e.source,[`presets`,r])});continue}let t=Mb(e,bU,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function SU(e,t){if(t===void 0)return{};if(!Ab(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${jb(t)}`,line:q(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${J(i)}`,line:q(e.source,[`helpers`,r])});continue}n[r]=i}return n}function CU(e,t){let n=[...t].map(([e,t])=>[qw(e),t]);return t=>{if(YR(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=Yw(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function wU(e){return e.kind===`plugin`||e.kind===`missing`}function TU(e,t,n){let r=new Map,i=(e,t)=>{r.set(e,[...r.get(e)??[],t])},a=e=>uw(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 nb(e))t.kind===`segment`&&i(Qy(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 EU(e){let t=0,n=CU(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)?[tb(e,i)]:[],o=e=>a(e)[0]??DU,s=e=>({...e,rows:Object.fromEntries(Object.entries(e.rows).map(([e,t])=>[e,o(t)]))}),c=e=>uw(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 DU={kind:`container`,direction:`horizontal`,children:[]};function OU({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),[...[...Hw(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=aT(e=>{let i=Qee(e,t)?Object.keys(n):dT(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]}),a=aT(n=>i(n).flatMap(n=>[...cT(n,t).keys()].map(t=>({path:t,reaches:gT(t,e)}))));return{ofTemplate:a,calls:aT(e=>new Set(i(e).flatMap(e=>[...ete(e,t)]))),ofVariable:t=>[...db(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...lb(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function kU(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}const AU=new WeakMap;function jU(e){let t=AU.get(e);return t===void 0&&(t=OU({names:new Set([...hT(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),AU.set(e,t)),t}function MU(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 NU=new WeakMap;function PU(e){let t=NU.get(e);return t===void 0&&(t=IU(e),NU.set(e,t)),t}function FU(e){return PU(e).projections}function IU(e){let t=new Map(hT(e)),n=new Map,r={reads:jU(e),projections:n,clock:rN};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=kU(e,r),i=t===void 0?null:GN(t);i&&n.set(e,`reads the draw's "${i}" (${WN[i]})`)}let i=RU(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=MU(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of yy)if(!a.has(t))for(let n of i[t]){let i=MU(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=kU(r,i);if(t===void 0||n.has(r))continue;let o=qN(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 LU(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>yy.flatMap(n=>{let r=t[n];return by(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function RU(e){let t=LU(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function zU(e,t){return MU(e,PU(t))}function BU(e){return t=>MU(t,e)!==null}function VU(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const HU=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),UU=`plugin.json5`,WU=/^[a-z][a-z0-9_]*$/;function GU(e,t){let n=o.basename(o.dirname(e));return WU.test(n)?{path:e,scope:t,name:n}:{path:e,scope:t,name:void 0}}function KU(e){return`${e}.data`}function qU(e){return`${e}.json`}function JU(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:YU(e)}}}function YU(e){return e instanceof Cb?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 XU(e,t,n){return e.map(e=>GU(bF(o.dirname(t),e),n))}function ZU(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=n.path,s=n.name===void 0?void 0:Kw(n),c=(t,r)=>{let i=new Map(e.rendering);return s!==void 0&&r!==e.config&&i.delete(s),{...e,config:r,rendering:i,dropped:[...e.dropped,{...n,reason:t}]}};if(o.basename(a)!==`plugin.json5`){let t=`a plugin is a folder holding its ${UU}, and the folder's name is the plugin's: move this file to <dir>/<name>/${UU} and list that`;return c(t,s===void 0?e.config:$U(QU(e.config,s),s,{...n,reason:t}))}if(n.name===void 0||s===void 0)return c(`its folder "${o.basename(o.dirname(a))}" is not a plugin name (one matching ${WU}: it prefixes every name the plugin declares)`,e.config);let l=i.get(s);if(l!==void 0)return c(`plugin "${n.name}" is already listed, from ${l}`,e.config);i.set(s,a);let u=QU(e.config,s),d=JU(()=>{let i=f.readFileSync(a,`utf-8`),o=gB(aW(a,n,{source:i,json:Ia.default.parse(i)},t),u);return bW(a,s,o),r(o,s,u!==e.config),o});if(d.ok)return{...e,config:d.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[s,n]])};let p={...n,reason:d.reason};return c(d.reason,$U(u,s,p))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function QU(e,t){let n=qw(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 $U(e,t,n){return{...e,variables:{...e.variables,[t]:{kind:`dropped`,reason:VU(n),definition:n.path}}}}function eW(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})=>qw(t)(e))}function tW(e,t){let n=eW(e.config),r=[...e.rendering.keys()].map(qw),i=[...t,...e.dropped].filter(e=>e.name===void 0);return e=>{let t=Yw(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:VU(e)})):[{definition:a.definition,notice:a.notice}]}}function nW(e,t,n){let r=Tw(e.presets).flatMap(t=>[...nb(Ow(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,rW(e,t.map(e=>e.notice),r.filter(t=>t.name===e))])),o=eW(e),s=Object.values(e.variables).some(e=>e.kind===`dropped`),c=s?Object.values(e.segments).flatMap(e=>[...lW.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=>dT(t,e.helpers).map(e=>e.name)),...l],e.actions),f=u(c.flatMap(t=>[...pT(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 rW(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,iW(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function iW(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 aW(e,t,{source:n,json:r},{checkout:i}){let a=Kw(t),s=[],c=()=>{throw new Cb(e,s)};if(!Ab(r))return s.push({path:``,message:`a plugin definition must be an object, got ${jb(r)}`}),c();for(let t of Object.keys(r))HU.has(t)||s.push({path:t,message:t===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${o.basename(o.dirname(e))}") — remove "plugin"`:`a plugin definition may not declare "${t}". Expected only: ${[...HU].join(`, `)}`});let l=r.data===void 0?void 0:CW(r.data,e,i,s),u=r.sources===void 0?{}:yW(r.sources,e,s);if(s.length>0)return c();let d={source:n,issues:s,allowedPalettes:new Set(my()),groups:[],unplaced:[],inherited:[]},p=l===void 0?{}:FB(d,`data`,{[KU(a)]:{kind:`file`,path:l,parse:{json:!0},cache:{watch_file:l},default:{}}}),m=FB(d,`variables`,r.variables);for(let[e,t]of[[`variables`,Object.keys(m)],[`sources`,Object.keys(u)]])t.includes(`data`)&&s.push({path:`${e}.data`,message:`"data" names the plugin's data file (.${KU(a)}), declared by the definition's own "data" key: give this ${e===`sources`?`source`:`variable`} another name`});for(let e of Object.keys(u))Object.hasOwn(m,e)&&s.push({path:`sources.${e}`,message:`source "${e}" and variable "${e}" are one name (.${a}.${e}): give one of them another name`});let h={variables:{...p,...fW(a,u),...fW(a,Object.fromEntries(Object.entries(m).map(([e,t])=>[e,mW(a,t)])))},segments:fW(a,hW(a,DV(d,r.segments,new Set))),helpers:fW(a,SU(d,r.helpers)),actions:fW(a,gW(a,wH(d,r.actions,{dir:f.realpathSync(o.dirname(e))})))};s.push(...uW(h,t));let g=oW(a,h);for(let[e,t]of dW(g))try{QP.parse(t)}catch(t){s.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return s.length>0&&c(),g}function oW(e,t){let n=t=>rte(t,Jw,e),r=t=>qw(`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=>sW(ub(e,n),r)),segments:i(t.segments,e=>({...e,...Object.fromEntries(lW.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=>sW(ub(e,n),r))}})),helpers:i(t.helpers,n),actions:i(t.actions,e=>cW(Uw(e,n),r))}}function sW(e,t){return lb(e)&&`depends_on`in e.cache?{...e,cache:{depends_on:e.cache.depends_on.map(t)}}:e}function cW(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 lW=[`template`,`bg`,`fg`,`when`];function uW(e,t){let n=e.helpers??{},r=Gw.filter(e=>e!==t.scope).map(e=>({scope:e,ns:Kw({scope:e,name:t.name})})),i=new Map,a=(e,n,a)=>{let o=r.find(({ns:e})=>qw(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 ${Kw(t)}: a plugin names itself without its scope — write ${s}${Jw}${n.slice(o.ns.length)}`})},o=[...[...dW(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 cT(t,n))i===null&&a(e,r,!0);for(let{name:r,via:i}of dT(t,n))i===null&&a(e,r,!1);for(let n of pT(t,{}))a(e,n,!1)}for(let[t,n]of Object.entries(e.actions??{}))cW(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(lb(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*dW(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of db(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of lW){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 db(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 Hw(n))yield[`actions.${t}.${e}`,r]}function fW(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,n]))}function pW(e,t){return`${e}.${t}`}function mW(e,t){return t.kind===`state`?{...t,key:pW(e,t.key)}:t}function hW(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,mW(e,n)]))}]))}function gW(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:pW(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>pW(e,t))}:n]))}const _W=WU,vW={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function yW(e,t,n){if(!Ab(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${jb(e)}`}),{};let r=o.join(f.realpathSync(o.dirname(t)),`session`),i=JSON.stringify(vW),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!_W.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${_W}: it is the last segment of .<scope>.<plugin>.${t})`});continue}let s=SW(o,vW,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 bW(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=xW(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=qw(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 Cb(e,a)}function xW(e){return o.join(e.storage,qU(`<session id>`))}function SW(e,t,n){return!Ab(t)||!Ab(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)?SW(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function CW(e,t,n,r){if(typeof e==`string`&&e!==``)return bF(o.dirname(t),e);if(Ab(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(o.isAbsolute(t)||t.startsWith(`~`)||o.normalize(t).split(o.sep)[0]===`..`){r.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){r.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return o.resolve(n.root,t)}if(Ab(e)&&`project`in e){r.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}r.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`})}const wW={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 TW(e,t){let n=new Map;for(let e of Object.keys(t)){let t=XN(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:q(e.source,[`presets`])})}function EW(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 hw(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const DW=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${Kw(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${OW(Kw(r.definition),n)}${kW(t,n)}`:`${e} entry "${t}" does not match any declared segment${kW(t,n)}`;function OW(e,t){let n=Object.keys(t).filter(qw(e)).sort();return n.length===0?`no segments`:n.map(e=>{let n=Object.keys(t[e].settings??{});return`${e} (${n.length===0?`no settings`:`settings: ${n.join(`, `)}`})`}).join(`, `)}function kW(e,t){return lV(e)+Xw(e,e=>Object.hasOwn(t,e))}function AW(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||by(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:Ry(r)?_U(i,r,a):`${i} "${r}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:q(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:q(e.source,[`globals`,`preset`])}),TW(e,t.presets);let a=vT(t);for(let t of a.names)t!==`settings`&&!t.startsWith(NW)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:q(e.source,[`variables`,t])});let o=(t,n,i)=>{QR(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Ri}" ${QR(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:i}),$R(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Ri}" 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:wW[a](n),line:i});let o=new Map;for(let e of nb(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=Qy(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=eb(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`||Zy[e.direction]===`cell`);return Zy[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:Zy[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,rb(t,n)]):e.opens===void 0?[]:[[e.opens.body,ib(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=mw(n),s=uw(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:wW[t](n),line:q(e.source,n.split(`.`))});for(let[o,s]of hw(n,i)){let n=q(e.source,s.split(`.`));if(o.when!==void 0&&(YW(e,`${s}.when`,o.when,a,{line:n}),qW(e,`${s}.when`,o.when,n),JW(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if(YR(o.name)){(o.id!==void 0||o.settings!==void 0)&&e.issues.push({path:s,message:`${i} gives the global settings menu anchor "${Ri}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${Ri}"`,line:n});continue}let c=r(o.name);wU(c)&&(d.add(o.name),e.unplaced.push({path:s,message:DW(i,o.name,t.segments,c),line:n})),VW(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`,pw(t.root)]]);for(let e of Tw(t.presets)){let{node:n,path:r}=Ow(t,e);p.set(r,n)}for(let[t,n]of p)o(n,t,q(e.source,t.split(`.`)));for(let[n,i]of p)for(let[a]of ab(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);wU(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:DW(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:q(e.source,n.split(`.`))}))}rG(e,t,a,()=>!0)}const jW=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function MW(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=q(e.source,[`actions`,n,r]);if(!Tw(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Tw(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(`, `)})${lV(i)}`,line:c})},p=new Set($y(Ow(t,a).node)),m=(r,i)=>{!cV.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${lV(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 NW=`settings.`;function PW(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>NW+e)])}}function FW(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:q(e.source,[`segments`,t,`settings`,n])})},a=RW(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of vb(n,LW(n)))i(e,`the defaults do not stand together: ${t}`)}function IW(e){return RW(e).length>0||vb(e,LW(e)).length>0}function LW(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function RW(e){let t=t=>_b(zW(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||_b(zW(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${BW(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 zW(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function BW(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&_b(n)!==void 0).map(([e])=>e)}function VW(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=gb(a),s=`${r}: placement "${Qy(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(`, `)})`:yb(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?dy(a):``}, but it must be ${Sb(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])=>yb(o[e],t))||IW(o)))for(let{message:t}of vb(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function HW(e,t,n,r,i){for(let[a,o]of db(n))YW(e,`${t}.${a}`,o,r,{segCtx:i})}function UW(e,t,n,r,i){if(!(!lb(n)||!(`depends_on`in n.cache)))for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:q(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const WW=`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 GW(e,t,n,r){if(!lb(n))return;let i=n=>q(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=zU(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${WW}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=FU(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}: ${WW}`,line:i(`depends_on`)})})}}function KW(e,t){let n=new Map(hT(t)),r=jU(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=yy.find(e=>KN[e]===n||KN[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${KN[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=kU(e,a),s=o===void 0?void 0:qN(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 LU(t)){let t=i(r.ofTemplate(a),new Set);if(t===null)continue;let o=n.join(`.`);e.issues.push({path:o,message:`${o} ${t}: a rule decides that name, so it cannot read it — read the data the rule is about instead`,line:q(e.source,[...n])})}}function qW(e,t,n,r){try{QP.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function JW(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 dT(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){ZW(e,u,`Template references unknown action "${c}"${r}`,XW(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function YW(e,t,n,r,i){for(let[a,o]of cT(n,r.helpers)){if(_T(a,r))continue;if(a.startsWith(NW)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??q(e.source,t.split(`.`))});continue}if(o!==null){ZW(e,o,`Template references unknown variable ".${a}"${AB(a)}`,XW(o,i?.segCtx===void 0?void 0:{name:i.segCtx,partials:i.partials}));continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&_T(n,r)?` (segment-local vars are namespaced — write ".${n}")`:AB(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??q(e.source,t.split(`.`))})}}function XW(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function ZW(e,t,n,r=[`helpers`,t]){let i=r.join(`.`);e.issues.some(e=>e.path===i&&e.message===n)||e.issues.push({path:i,message:n,line:q(e.source,r)})}function QW(e,t,n,r,i){let a=n.set,o=TP(Jx[r].configKey),s=`${a} takes ${cP(o,i)}`;if(`min`in n&&(o===`bool`||!(`min`in o))){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:q(e.source,[`actions`,t,`min`])});return}let c=tG(n,i);if(c===eG){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:q(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!sP(o,e.value,i));if(l.length!==0){if(a===Jx.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>Ry(e.value)))){let r=Jx.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:_U(`actions.${t}.to`,n.to,`set: "${r}", to`),line:q(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:q(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=$W?r.join(`, `):`${r.slice(0,$W).join(`, `)} and ${r.length-$W} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:q(e.source,[`actions`,t,n])})}}}const $W=3,eG=Symbol(`any integer`);function tG(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?Lw(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)}]:eG}function nG(e,t){return Object.entries(e).filter(([e])=>t(e))}function rG(e,t,n,r){let i=Ez(t),a=Iw(i);for(let[n,o]of nG(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 ${zw(r,i)}`,line:q(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;Qx.has(o.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${o.set}", which has no session pick — globals.${o.set} is set in the config file only, so a click would change nothing; write it with { persist: "${o.set}", … } instead`,line:q(e.source,[`actions`,n,`set`])});let s=nS.get(o.set);s!==void 0&&QW(e,n,o,s,i)}for(let[n,i]of nG(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&&Ww(o)?`"${r}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${r}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:q(e.source,[`actions`,n,`do`])})});for(let[n,i]of nG(t.actions,r))if(`run`in i)for(let r of i.refreshes){let i=Object.hasOwn(t.variables,r)?t.variables[r]:void 0;i?.kind!==`source`&&e.issues.push({path:`actions.${n}.refreshes`,message:`actions.${n} refreshes "${r}", which ${i===void 0?`is not declared`:`is a ${i.kind} variable`}: a run refreshes only a declared source (by its full name, <scope>.<plugin>.<source> where the scope is plugins or repo; a plugin names its own sources bare)`,line:q(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of nG(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=YP(r);if(o===null){let t=ote(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${ste().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, a "themeDefaults.<theme>.<shade|variation|style>" target, or a "presets.<name>.root" target`:`actions.${n}: the globals field "${r}" was removed: ${t}`,line:q(e.source,[`actions`,n,a])});continue}let s=jW.filter(e=>e in i);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:q(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){MW(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Tw(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: ${Tw(t.presets).join(`, `)})`,line:q(e.source,[`actions`,n,a])});continue}if(o.scope===`theme-default`&&!e.allowedPalettes.has(o.theme)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names theme "${o.theme}" which is not installed${dy(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:q(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${lV(o.segment)}`,line:q(e.source,[`actions`,n,a])});continue}`min`in i&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:q(e.source,[`actions`,n,a])})}}for(let[i,a]of nG(t.variables,r)){HW(e,`variables.${i}`,a,n);let t=kB(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:q(e.source,[`variables`,i])})}for(let[i,a]of nG(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))HW(e,`segments.${i}.vars.${t}`,r,n,i);let r=gb(a);if(FW(e,i,r),a.partials!==void 0)for(let t of Object.keys(a.partials))Object.hasOwn(n.helpers,t)&&e.issues.push({path:`segments.${i}.partials.${t}`,message:`segments.${i}.partials.${t} reuses the name of a global helper (helpers.${t}) — partials and helpers share one define chain, so pick a name no helper already uses`,line:q(e.source,[`segments`,i,`partials`,t])});let o=a.partials===void 0?n.helpers:{...n.helpers,...a.partials},s=PW({...n,helpers:o},r);for(let n of lW){let c=a[n];typeof c==`string`&&(YW(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),JW(e,t,`segments.${i}.${n}`,c,q(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of nG(t.variables,r))UW(e,`variables.${i}`,a,n),GW(e,`variables.${i}`,a,t);KW(e,t);for(let[i,a]of nG(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))UW(e,`segments.${i}.vars.${r}`,o,n,i),GW(e,`segments.${i}.vars.${r}`,o,t)}function iG(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=aG(t),a=new Map,o=[];for(let e of r.keys())a.set(e,0);for(let e of r.keys())if(!(!n(e)||a.get(e)!==0)&&s(e))return;function s(t){a.set(t,1),o.push(t);for(let c of r.get(t)??[]){if(!n(c))continue;let t=a.get(c);if(t===1){let t=o.indexOf(c),n=[...o.slice(t),c],r=n[0],a=i.get(r);return e.issues.push({path:a?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:q(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function aG(e){let t=new Map,n=new Map,r=jU(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 oG(e,t,n){let r=new Map([...mT(t)].map(([e,,t])=>[e,t]));for(let[t,i]of r){let a=t.split(`.`);for(let o=1;o<a.length;o++){let s=a.slice(0,o).join(`.`),c=r.get(s);if(c===void 0||!(n.checked(t)||n.checked(s)))continue;let[l,u,d]=n.authored(t)?[t,s,i]:[s,t,c],f=n.authored(t)===n.authored(s)?`Rename one so neither name starts with the other.`:`"${u}" is declared outside this file (the bundled default, a plugin, or a control the bar builds), so rename "${l}".`;e.issues.push({path:d.join(`.`),message:`variable "${t}" is declared under the variable "${s}" — a read of ".${t}" would name both, "${t}" and a field of "${s}". ${f}`,line:q(e.source,[...d])})}}}function sG(e){let t=[...[...(process.env.XDG_DATA_DIRS||uG()).split(`:`).filter(e=>e!==``)].reverse().map(e=>o.join(e,`cc-candybar`,`plugins`)),cG()];return[...t.filter((e,n)=>t.lastIndexOf(e)===n).map(e=>({dir:e,scope:`plugins`})),...e===null?[]:[{dir:o.join(e,lG),scope:`repo`}]]}function cG(){let e=process.env.XDG_DATA_HOME||o.join(D.homedir(),`.local`,`share`);return o.join(e,`cc-candybar`,`plugins`)}const lG=o.join(`.cc-candybar`,`plugins`);function uG(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${o.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function dG(e){let t=sG(e),n=new Map,r=[],i=[];for(let{dir:e,scope:a}of t){let t=fG(e);if(`error`in t){r.push(t);continue}for(let r of t.folders){let t=GU(o.join(e,r,UU),a),i=`${a}\0${r}`;n.delete(i),n.set(i,t)}for(let n of t.files)i.push({path:o.join(e,n),scope:a,name:void 0,reason:`a plugin is a folder holding its ${UU}: move this file to ${o.join(e,`<name>`,UU)}`})}return{roots:t.map(e=>e.dir),definitions:[...n.values()],unchecked:r,strays:i}}function fG(e){try{let t=f.readdirSync(e,{withFileTypes:!0}).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),n=t=>t.isDirectory()||pG(e,t);return{folders:t.filter(n).map(e=>e.name),files:t.filter(e=>!n(e)).map(e=>e.name)}}catch(t){return t.code===`ENOENT`?{folders:[],files:[]}:{path:e,error:t.message}}}function pG(e,t){if(!t.isSymbolicLink())return!1;try{return f.statSync(o.join(e,t.name)).isDirectory()}catch{return!0}}function mG(e){try{return f.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const hG=[`approved`,`declined`];function gG(e){return e.link.kind===`linked`?e.link.main:e.dir}const _G=(e,t)=>Object.hasOwn(e,t)?e[t]:null;function vG(e,t){let n=gG(t);if(e.kind===`failed`)return{standing:`unread`,under:n};let r=_G(e.value,n),i=_G(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 yG(e,t,n){let r=[...new Map([...t,...n?.ships?[n]:[]].map(e=>[e.dir,e])).values()],i=r.map(t=>({dir:t.dir,...vG(e,t)})),a=e=>i.filter(t=>t.standing===e),o=e=>[...new Set(a(e).map(e=>e.under))];return{plugins:n!==null&&vG(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 bG(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 xG(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(!hG.includes(n))return{kind:`failed`,reason:`answers ${JSON.stringify(t)} ${JSON.stringify(n)}, not ${hG.join(` or `)}`};return{kind:`ok`,value:e}}function SG(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 CG(e){let t=SG(e);return[...t===null?[]:[t],...e.awaiting.map(e=>`awaiting approval: ${e} — its cc-candybar config runs once it is approved in the bar`),...e.declined.map(e=>`declined: ${e} — its cc-candybar config does not run`),...e.unproven.map(e=>`not proven a worktree: ${e.dir} — it answers for itself, because ${e.reason}`)]}const wG=[`json5`,`json`];function TG(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?wG.map(t=>o.join(e,`${EG}.${t}`)):[],...wG.map(e=>o.join(r,`${EG}.${e}`)),...wG.map(e=>`${DG()}.${e}`)])]}const EG=`.cc-candybar`;function DG(){let e=process.env.XDG_CONFIG_HOME??o.join(D.homedir(),`.config`);return o.join(e,`cc-candybar`,`config`)}function OG(e){return{path:e,scope:`plugins`}}function kG(e,t,n,r){let i=[],a=new Map;for(let e of TG(t,n,r)){let t=mG(e);if(t===`absent`)continue;if(t!==`present`){i.push(t);continue}let n=f.realpathSync.native(o.dirname(e)),s=o.join(n,o.basename(e).replace(/\.(json5|json)$/,``));a.has(s)||a.set(s,{file:e,repo:r!==void 0||AG(e)?null:{dir:n,link:Vc(n)}})}let s=[...a.values()],c=yG(e,s.flatMap(e=>e.repo===null?[]:[e.repo]),jG(t)),l=s.filter(e=>e.repo===null||c.approved.includes(e.repo.dir)).reverse().map(e=>({path:e.file,scope:e.repo===null?`plugins`:`repo`}));if(r===void 0)return{kind:`chain`,layers:l,home:MG(l),unchecked:i,repos:c};let[u]=i,d=r;return l.length>0?{kind:`chain`,layers:l,home:d,unchecked:i,repos:c}:u===void 0?{kind:`missing`,path:r,home:d,repos:c}:{kind:`unreadable`,...u,home:d,repos:c}}function AG(e){return wG.some(t=>e===`${DG()}.${t}`)}function jG(e){if(e===void 0||mG(e)!==`present`)return null;let t=fG(o.join(e,lG)),n=f.realpathSync.native(e);return{dir:n,link:Vc(n),path:e,ships:!(`error`in t)&&t.folders.length>0}}function MG(e){return e.find(e=>AG(e.path))?.path??`${DG()}.${wG[0]}`}function NG(e,t,n,r){let i=kG(e,t,n,r),a=i.kind===`chain`?i.layers:[];return{path:i.home,above:a.filter(e=>e.path!==i.home),repo:i.repos.plugins,cwd:n??null}}function PG(e){return FG(e).join(`
|
|
181
|
+
New: { h: ["seg1", "seg2"] }`,line:q(e.source,[`root`])}),zV;if(n.kind===`group`){let r=Mb(e,oH,t,n);return r===null?zV:(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}),cH(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:q(e.source,[`root`])}),zV}if(a){let r=Mb(e,JV,t,n);return r===null?zV:{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=Mb(e,YV,t,n);return r===null?zV:{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=Mb(e,XV,t,n);return r===null?zV:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:q(e.source,[`root`])}),zV};function QV(){return{required:!0,json:{type:`object`,propertyNames:{pattern:sw.source},additionalProperties:{$ref:RV}},parse:(e,t,n,r)=>{let i=r[n];if(!Ab(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${jb(i)}`,line:q(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!sw.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:q(e.source,[...t.split(`.`),n,r])});continue}a[r]=ZV(e,`${t}.${n}.${r}`,o)}return a}}}const $V={noun:`root key`,fields:{rows:QV(),when:Ub(),distribution:GV()}};function eH(e,t,n){return Ab(n)&&`rows`in n?Mb(e,$V,t,n)??{rows:{}}:ZV(e,t,n)}const tH={noun:`insert key`,fields:{seg:qV(),id:wV(),before:Ub(),after:Ub()}};function nH(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=Mb(e,tH,i,t);if(a===null)return[];let o=[`before`,`after`].filter(e=>a[e]!==void 0);if(o.length!==1)return e.issues.push({path:i,message:`an insert cell names exactly one of "before" or "after" (the placement id it sits beside), got ${o.length===0?`neither`:`both`}`,line:q(e.source,i.split(`.`))}),[];if(Li(a.seg))return e.issues.push({path:`${i}.seg`,message:`an insert cell places a segment, and "${a.seg}" is the bar's own chrome — name a segment instead`,line:q(e.source,[...i.split(`.`),`seg`])}),[];let s=o[0],c=a[s];return Li(c)?(e.issues.push({path:`${i}.${s}`,message:`an insert cell sits beside a placement, and "${c}" is the bar's own chrome — anchor on a placement id instead`,line:q(e.source,[...i.split(`.`),s])}),[]):[{seg:a.seg,...a.id!==void 0&&{id:a.id},anchor:c,relation:s,by:{file:n,entry:i}}]}):(e.issues.push({path:`insert`,message:`"insert" must be a list of cells like { seg: "name", after: "placement" }, got ${jb(t)}`,line:q(e.source,[`insert`])}),[])}function rH(){return{required:!0,json:{type:`string`,pattern:sw.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!sw.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 "${N}", got ${J(i)}`,line:q(e.source,[`root`])});return}return i}}}function iH(){return{required:!1,json:{type:`string`,minLength:1},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`string`||i===``||i.includes(`/`)){e.issues.push({path:`${t}.${n}`,message:`a group "key" must be a non-empty, slash-free SessionState key, got ${J(i)}`,line:q(e.source,[`root`])});return}return i}}}}function aH(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Eb(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:q(e.source,[...t.split(`.`),n])});return}return i}}}}const oH={noun:`layout-node key`,fields:{kind:BV(`group`),name:rH(),label:aH(),open:Wb(),direction:Zb(Xy),key:iH(),bg:Ub(),fg:Ub(),when:Ub(),distribution:GV(),children:UV(Vb(()=>ZV))}};function sH(e){return e.key??`groups.`+e.name}function cH(e){let t=Mi+e.name;return Ci(t,{variable:t,key:sH(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function lH(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,[`root`])})}function uH(e,t){$P(e,t,Mi,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&lH(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}.`)&&sH(t)===sH(r)&&lH(e,t.path,`group "${t.name}" shares key "${sH(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=sH(t);if(i.has(n)||i.set(n,N),t.open===!0){let r=i.get(n);r!==`closed`&&lH(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=Mi+e.name,r=sH(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=ki(r,i.get(r)),o[t]=Ai(r,e.name),s[t]={template:Ei(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 dH=`menu`,fH=`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`,pH=e=>e.kind===`call`&&e.name===`dict`,mH=e=>e.kind===`literal`&&typeof e.value!=`object`,hH=e=>bi(``,e,2)===void 0;function gH(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&&pH(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(pH))return t(`whose options (dict …) is not its last argument — ${fH}`);if(i!==void 0&&a===void 0&&!mH(i)&&hH(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=bi(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${fH}`);let c=a===void 0?{}:Pk(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=aP(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=_te(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 "${$N(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 _H(e){let t=UD({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===dH).map(gH)}catch{return`parse-failed`}}function vH(e,t){let n=_H(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:QN(t,e.apply,e.options.key),member:ZN(e.apply)}]:[])}function yH(e){let t=UD({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(dH)}catch{return!1}}function bH(e,t,n){e.issues.push({path:t,message:n,line:q(e.source,[`root`])})}function xH(e,t){$P(e,t,Ni,`{{ menu }} helpers`),$P(e,t,Pi,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))yH(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:q(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n)){for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&yH(i)&&bH(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??{}))yH(i)&&e.issues.push({path:`segments.${t}.partials.${n}`,message:`segments.${t}.partials.${n} uses {{ menu }}, but a menu must live directly in a segment's "template" string — the synthesis pass that wires its state never follows a {{ template }} call into a partial. Inline the {{ menu }} call into the template itself.`,line:q(e.source,[`segments`,t,`partials`,n])})}if(t.root!==void 0)for(let n of nb(mw(t.root)))typeof n.when==`string`&&yH(n.when)&&bH(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||!yH(r))continue;let n=_H(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:SH(r.apply);n!==void 0&&bH(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function SH(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(ZN(e)===`closed`)return`whose apply action is named "${N}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function CH(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 Tw(e.presets)){let a=new Map,s=new Map;for(let c of nb(Ow(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,_H(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=Qy(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||SH(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=ZN(i),f=QN(u,i,l.key),p=tP(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=eP(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]=Ai(f,d),n[f]=ki(f,N),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 wH(e,t,n){if(t===void 0)return{};if(!Ab(t))return Z(e,`actions`,`actions must be an object, got ${jb(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=TH(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:q(e.source,t.split(`.`))})}function TH(e,t,n,r){if(!Ab(n))return Z(e,t,`${t} must be an action object, got ${jb(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=Bw.filter(e=>e in n);return i.length===1?DH(r)[i[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${Bw.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function EH(e){return e===`<default>`?{dir:D.homedir()}:o.isAbsolute(e)?{dir:o.dirname(e)}:{text:e}}const DH=e=>({set:(e,t,n)=>lU(e,t,n,`set`,aU),persist:(e,t,n)=>lU(e,t,n,`persist`,oU),copy:OH(`copy`),open:OH(`open`),reset:kH,undo:jH(`undo`),redo:jH(`redo`),back:jH(`back`),rewind:jH(`rewind`),save:jH(`save`),preset:MH,themeDefault:NH,doctor:FH,slash:IH,run:zH(e),do:BH});function OH(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=Eb(t,n,r,e);return i===null?null:{[e]:i}}}function kH(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=VH(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 AH={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 jH(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 — ${AH[e]}), got ${J(r[e])}`),null)}}function MH(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 ${J(r)}`),null;if(r===`save`)return{preset:`save`};let a=Eb(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function NH(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 ${J(n.themeDefault)}`),null)}const PH={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function FH(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(PH,r),a=i?PH[r]:[...new Set(Object.values(PH).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(PH).map(e=>`"${e}"`).join(`, `)}, got ${J(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?WI:UI;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 ${J(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return ZF.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${ZF.map(e=>`"${e}"`).join(` or `)}, got ${J(c)}`),null)}function IH(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=vL(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}const LH=[`run`,`env`,`refreshes`],RH=/^[A-Za-z_][A-Za-z0-9_]*$/;function zH(e){return(t,n,r)=>{for(let e of Object.keys(r))LH.includes(e)||Z(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${LH.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 ${J(a)}`);let o=r.env??{};(!Ab(o)||Object.entries(o).some(([e,t])=>!RH.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 ${J(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 ${J(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}}}RH.source;function BH(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 ${J(r)}`),null):{do:r}}function VH(e,t,n,r,i,a){let o=Eb(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 HH={set:`the SessionState key to write`,persist:`the config globals field to write`};function UH(e,t,n,r){let i=HH[r],a=VH(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);return a===null?null:{[r]:a}}function WH(e){return e===`set`?`set-state`:`set-config`}const GH={to:uU(`set`)},KH={to:uU(`persist`)},qH={from:dU(`set`)},JH={from:dU(`persist`)},YH={min:gU(),max:gU(),by:gU()},XH={int:pU()},ZH={cycle:fU(`set`)},QH={cycle:fU(`persist`)},$H={removeSegment:mU(`removeSegment`)},eU={insertSegment:mU(`insertSegment`),anchor:mU(`anchor`),relation:hU()},tU={insertSegmentFrom:dU(`persist`),anchor:mU(`anchor`),relation:hU()},nU={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},rU={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function iU(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>Pb(e,t,n,r),c=Qb(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?Hb(s,...n):s}}const aU=[iU(`set`,GH),iU(`set`,qH),iU(`set`,YH,[nU,rU]),iU(`set`,XH),iU(`set`,ZH)],oU=[iU(`persist`,KH),iU(`persist`,JH),iU(`persist`,YH,[nU,rU]),iU(`persist`,QH),iU(`persist`,$H),iU(`persist`,eU,[],[`insertSegment`]),iU(`persist`,tU,[],[`insertSegmentFrom`])];function sU(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 cU(e){let t=sU(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 lU(e,t,n,r,i){let a=UH(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${cU(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 uU(e){let t=WH(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>VH(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 dU(e){let t=WH(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 ${J(o)}`)}}}function fU(e){let t=WH(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 ${jb(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 pU(){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 ${J(r[n])}`);return}return!0}}}function mU(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Eb(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 hU(){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 ${J(i)}`);return}return i}}}function gU(){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 ${J(i)}`);return}return i}}}function _U(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const vU={noun:`style key`,fields:{hueShift:Kb(),chromaScale:Kb({min:0}),lightnessScale:Kb(),lightnessShift:Kb()}};function yU(e,t){if(!Ab(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${jb(t)}`,line:q(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:q(e.source,[`styles`,r])});continue}if(Ry(r)){e.issues.push({path:`styles.${r}`,message:_U(`styles.${r}`,r,`globals.endcaps`),line:q(e.source,[`styles`,r])});continue}let t=Mb(e,vU,`styles.${r}`,i);t!==null&&(n[r]={...Pu,...t})}return n}const bU={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:eH(e,`${t}.${n}`,r[n])},globals:{required:!1,json:HP(),parse:(e,t,n,r)=>r[n]===void 0?void 0:VP(e,`${t}.${n}`,r[n])}}};function xU(e,t){if(!Ab(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${jb(t)}`,line:q(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:q(e.source,[`presets`,r])});continue}let t=Mb(e,bU,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function SU(e,t){if(t===void 0)return{};if(!Ab(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${jb(t)}`,line:q(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${J(i)}`,line:q(e.source,[`helpers`,r])});continue}n[r]=i}return n}function CU(e,t){let n=[...t].map(([e,t])=>[qw(e),t]);return t=>{if(YR(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=Yw(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function wU(e){return e.kind===`plugin`||e.kind===`missing`}function TU(e,t,n){let r=new Map,i=(e,t)=>{r.set(e,[...r.get(e)??[],t])},a=e=>uw(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 nb(e))t.kind===`segment`&&i(Qy(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 EU(e){let t=0,n=CU(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)?[tb(e,i)]:[],o=e=>a(e)[0]??DU,s=e=>({...e,rows:Object.fromEntries(Object.entries(e.rows).map(([e,t])=>[e,o(t)]))}),c=e=>uw(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 DU={kind:`container`,direction:`horizontal`,children:[]};function OU({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),[...[...Hw(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=aT(e=>{let i=Qee(e,t)?Object.keys(n):dT(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]}),a=aT(n=>i(n).flatMap(n=>[...cT(n,t).keys()].map(t=>({path:t,reaches:gT(t,e)}))));return{ofTemplate:a,calls:aT(e=>new Set(i(e).flatMap(e=>[...ete(e,t)]))),ofVariable:t=>[...db(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...lb(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function kU(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}const AU=new WeakMap;function jU(e){let t=AU.get(e);return t===void 0&&(t=OU({names:new Set([...hT(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),AU.set(e,t)),t}function MU(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 NU=new WeakMap;function PU(e){let t=NU.get(e);return t===void 0&&(t=IU(e),NU.set(e,t)),t}function FU(e){return PU(e).projections}function IU(e){let t=new Map(hT(e)),n=new Map,r={reads:jU(e),projections:n,clock:rN};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=kU(e,r),i=t===void 0?null:GN(t);i&&n.set(e,`reads the draw's "${i}" (${WN[i]})`)}let i=RU(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=MU(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of yy)if(!a.has(t))for(let n of i[t]){let i=MU(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=kU(r,i);if(t===void 0||n.has(r))continue;let o=qN(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 LU(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>yy.flatMap(n=>{let r=t[n];return by(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function RU(e){let t=LU(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function zU(e,t){return MU(e,PU(t))}function BU(e){return t=>MU(t,e)!==null}function VU(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const HU=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),UU=`plugin.json5`,WU=/^[a-z][a-z0-9_]*$/;function GU(e,t){let n=o.basename(o.dirname(e));return WU.test(n)?{path:e,scope:t,name:n}:{path:e,scope:t,name:void 0}}function KU(e){return`${e}.data`}function qU(e){return`${e}.json`}function JU(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:YU(e)}}}function YU(e){return e instanceof Cb?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 XU(e,t,n){return e.map(e=>GU(bF(o.dirname(t),e),n))}function ZU(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=n.path,s=n.name===void 0?void 0:Kw(n),c=(t,r)=>{let i=new Map(e.rendering);return s!==void 0&&r!==e.config&&i.delete(s),{...e,config:r,rendering:i,dropped:[...e.dropped,{...n,reason:t}]}};if(o.basename(a)!==`plugin.json5`){let t=`a plugin is a folder holding its ${UU}, and the folder's name is the plugin's: move this file to <dir>/<name>/${UU} and list that`;return c(t,s===void 0?e.config:$U(QU(e.config,s),s,{...n,reason:t}))}if(n.name===void 0||s===void 0)return c(`its folder "${o.basename(o.dirname(a))}" is not a plugin name (one matching ${WU}: it prefixes every name the plugin declares)`,e.config);let l=i.get(s);if(l!==void 0)return c(`plugin "${n.name}" is already listed, from ${l}`,e.config);i.set(s,a);let u=QU(e.config,s),d=JU(()=>{let i=f.readFileSync(a,`utf-8`),o=gB(aW(a,n,{source:i,json:Ia.default.parse(i)},t),u);return bW(a,s,o),r(o,s,u!==e.config),o});if(d.ok)return{...e,config:d.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[s,n]])};let p={...n,reason:d.reason};return c(d.reason,$U(u,s,p))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function QU(e,t){let n=qw(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 $U(e,t,n){return{...e,variables:{...e.variables,[t]:{kind:`dropped`,reason:VU(n),definition:n.path}}}}function eW(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})=>qw(t)(e))}function tW(e,t){let n=eW(e.config),r=[...e.rendering.keys()].map(qw),i=[...t,...e.dropped].filter(e=>e.name===void 0);return e=>{let t=Yw(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:VU(e)})):[{definition:a.definition,notice:a.notice}]}}function nW(e,t,n){let r=Tw(e.presets).flatMap(t=>[...nb(Ow(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,rW(e,t.map(e=>e.notice),r.filter(t=>t.name===e))])),o=eW(e),s=Object.values(e.variables).some(e=>e.kind===`dropped`),c=s?Object.values(e.segments).flatMap(e=>[...lW.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=>dT(t,e.helpers).map(e=>e.name)),...l],e.actions),f=u(c.flatMap(t=>[...pT(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 rW(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,iW(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function iW(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 aW(e,t,{source:n,json:r},{checkout:i}){let a=Kw(t),s=[],c=()=>{throw new Cb(e,s)};if(!Ab(r))return s.push({path:``,message:`a plugin definition must be an object, got ${jb(r)}`}),c();for(let t of Object.keys(r))HU.has(t)||s.push({path:t,message:t===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${o.basename(o.dirname(e))}") — remove "plugin"`:`a plugin definition may not declare "${t}". Expected only: ${[...HU].join(`, `)}`});let l=r.data===void 0?void 0:CW(r.data,e,i,s),u=r.sources===void 0?{}:yW(r.sources,e,s);if(s.length>0)return c();let d={source:n,issues:s,allowedPalettes:new Set(my()),groups:[],unplaced:[],inherited:[]},p=l===void 0?{}:FB(d,`data`,{[KU(a)]:{kind:`file`,path:l,parse:{json:!0},cache:{watch_file:l},default:{}}}),m=FB(d,`variables`,r.variables);for(let[e,t]of[[`variables`,Object.keys(m)],[`sources`,Object.keys(u)]])t.includes(`data`)&&s.push({path:`${e}.data`,message:`"data" names the plugin's data file (.${KU(a)}), declared by the definition's own "data" key: give this ${e===`sources`?`source`:`variable`} another name`});for(let e of Object.keys(u))Object.hasOwn(m,e)&&s.push({path:`sources.${e}`,message:`source "${e}" and variable "${e}" are one name (.${a}.${e}): give one of them another name`});let h={variables:{...p,...fW(a,u),...fW(a,Object.fromEntries(Object.entries(m).map(([e,t])=>[e,mW(a,t)])))},segments:fW(a,hW(a,DV(d,r.segments,new Set))),helpers:fW(a,SU(d,r.helpers)),actions:fW(a,gW(a,wH(d,r.actions,{dir:f.realpathSync(o.dirname(e))})))};s.push(...uW(h,t));let g=oW(a,h);for(let[e,t]of dW(g))try{QP.parse(t)}catch(t){s.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return s.length>0&&c(),g}function oW(e,t){let n=t=>rte(t,Jw,e),r=t=>qw(`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=>sW(ub(e,n),r)),segments:i(t.segments,e=>({...e,...Object.fromEntries(lW.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=>sW(ub(e,n),r))}})),helpers:i(t.helpers,n),actions:i(t.actions,e=>cW(Uw(e,n),r))}}function sW(e,t){return lb(e)&&`depends_on`in e.cache?{...e,cache:{depends_on:e.cache.depends_on.map(t)}}:e}function cW(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 lW=[`template`,`bg`,`fg`,`when`];function uW(e,t){let n=e.helpers??{},r=Gw.filter(e=>e!==t.scope).map(e=>({scope:e,ns:Kw({scope:e,name:t.name})})),i=new Map,a=(e,n,a)=>{let o=r.find(({ns:e})=>qw(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 ${Kw(t)}: a plugin names itself without its scope — write ${s}${Jw}${n.slice(o.ns.length)}`})},o=[...[...dW(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 cT(t,n))i===null&&a(e,r,!0);for(let{name:r,via:i}of dT(t,n))i===null&&a(e,r,!1);for(let n of pT(t,{}))a(e,n,!1)}for(let[t,n]of Object.entries(e.actions??{}))cW(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(lb(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*dW(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of db(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of lW){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 db(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 Hw(n))yield[`actions.${t}.${e}`,r]}function fW(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,n]))}function pW(e,t){return`${e}.${t}`}function mW(e,t){return t.kind===`state`?{...t,key:pW(e,t.key)}:t}function hW(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,mW(e,n)]))}]))}function gW(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:pW(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>pW(e,t))}:n]))}const _W=WU,vW={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function yW(e,t,n){if(!Ab(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${jb(e)}`}),{};let r=o.join(f.realpathSync(o.dirname(t)),`session`),i=JSON.stringify(vW),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!_W.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${_W}: it is the last segment of .<scope>.<plugin>.${t})`});continue}let s=SW(o,vW,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 bW(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=xW(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=qw(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 Cb(e,a)}function xW(e){return o.join(e.storage,qU(`<session id>`))}function SW(e,t,n){return!Ab(t)||!Ab(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)?SW(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function CW(e,t,n,r){if(typeof e==`string`&&e!==``)return bF(o.dirname(t),e);if(Ab(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(o.isAbsolute(t)||t.startsWith(`~`)||o.normalize(t).split(o.sep)[0]===`..`){r.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){r.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return o.resolve(n.root,t)}if(Ab(e)&&`project`in e){r.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}r.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`})}const wW={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 TW(e,t){let n=new Map;for(let e of Object.keys(t)){let t=XN(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:q(e.source,[`presets`])})}function EW(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 hw(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const DW=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${Kw(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${OW(Kw(r.definition),n)}${kW(t,n)}`:`${e} entry "${t}" does not match any declared segment${kW(t,n)}`;function OW(e,t){let n=Object.keys(t).filter(qw(e)).sort();return n.length===0?`no segments`:n.map(e=>{let n=Object.keys(t[e].settings??{});return`${e} (${n.length===0?`no settings`:`settings: ${n.join(`, `)}`})`}).join(`, `)}function kW(e,t){return lV(e)+Xw(e,e=>Object.hasOwn(t,e))}function AW(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||by(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:Ry(r)?_U(i,r,a):`${i} "${r}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:q(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:q(e.source,[`globals`,`preset`])}),TW(e,t.presets);let a=vT(t);for(let t of a.names)t!==`settings`&&!t.startsWith(NW)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:q(e.source,[`variables`,t])});let o=(t,n,i)=>{QR(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Ri}" ${QR(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:i}),$R(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Ri}" 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:wW[a](n),line:i});let o=new Map;for(let e of nb(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=Qy(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=eb(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`||Zy[e.direction]===`cell`);return Zy[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:Zy[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,rb(t,n)]):e.opens===void 0?[]:[[e.opens.body,ib(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=mw(n),s=uw(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:wW[t](n),line:q(e.source,n.split(`.`))});for(let[o,s]of hw(n,i)){let n=q(e.source,s.split(`.`));if(o.when!==void 0&&(YW(e,`${s}.when`,o.when,a,{line:n}),qW(e,`${s}.when`,o.when,n),JW(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if(YR(o.name)){(o.id!==void 0||o.settings!==void 0)&&e.issues.push({path:s,message:`${i} gives the global settings menu anchor "${Ri}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${Ri}"`,line:n});continue}let c=r(o.name);wU(c)&&(d.add(o.name),e.unplaced.push({path:s,message:DW(i,o.name,t.segments,c),line:n})),VW(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`,pw(t.root)]]);for(let e of Tw(t.presets)){let{node:n,path:r}=Ow(t,e);p.set(r,n)}for(let[t,n]of p)o(n,t,q(e.source,t.split(`.`)));for(let[n,i]of p)for(let[a]of ab(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);wU(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:DW(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:q(e.source,n.split(`.`))}))}rG(e,t,a,()=>!0)}const jW=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function MW(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=q(e.source,[`actions`,n,r]);if(!Tw(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Tw(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(`, `)})${lV(i)}`,line:c})},p=new Set($y(Ow(t,a).node)),m=(r,i)=>{!cV.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${lV(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 NW=`settings.`;function PW(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>NW+e)])}}function FW(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:q(e.source,[`segments`,t,`settings`,n])})},a=RW(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of vb(n,LW(n)))i(e,`the defaults do not stand together: ${t}`)}function IW(e){return RW(e).length>0||vb(e,LW(e)).length>0}function LW(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function RW(e){let t=t=>_b(zW(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||_b(zW(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${BW(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 zW(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function BW(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&_b(n)!==void 0).map(([e])=>e)}function VW(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=gb(a),s=`${r}: placement "${Qy(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(`, `)})`:yb(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?dy(a):``}, but it must be ${Sb(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])=>yb(o[e],t))||IW(o)))for(let{message:t}of vb(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function HW(e,t,n,r,i){for(let[a,o]of db(n))YW(e,`${t}.${a}`,o,r,{segCtx:i})}function UW(e,t,n,r,i){if(!(!lb(n)||!(`depends_on`in n.cache)))for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:q(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const WW=`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 GW(e,t,n,r){if(!lb(n))return;let i=n=>q(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=zU(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${WW}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=FU(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}: ${WW}`,line:i(`depends_on`)})})}}function KW(e,t){let n=new Map(hT(t)),r=jU(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=yy.find(e=>KN[e]===n||KN[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${KN[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=kU(e,a),s=o===void 0?void 0:qN(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 LU(t)){let t=i(r.ofTemplate(a),new Set);if(t===null)continue;let o=n.join(`.`);e.issues.push({path:o,message:`${o} ${t}: a rule decides that name, so it cannot read it — read the data the rule is about instead`,line:q(e.source,[...n])})}}function qW(e,t,n,r){try{QP.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function JW(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 dT(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){ZW(e,u,`Template references unknown action "${c}"${r}`,XW(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function YW(e,t,n,r,i){for(let[a,o]of cT(n,r.helpers)){if(_T(a,r))continue;if(a.startsWith(NW)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??q(e.source,t.split(`.`))});continue}if(o!==null){ZW(e,o,`Template references unknown variable ".${a}"${AB(a)}`,XW(o,i?.segCtx===void 0?void 0:{name:i.segCtx,partials:i.partials}));continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&_T(n,r)?` (segment-local vars are namespaced — write ".${n}")`:AB(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??q(e.source,t.split(`.`))})}}function XW(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function ZW(e,t,n,r=[`helpers`,t]){let i=r.join(`.`);e.issues.some(e=>e.path===i&&e.message===n)||e.issues.push({path:i,message:n,line:q(e.source,r)})}function QW(e,t,n,r,i){let a=n.set,o=TP(Jx[r].configKey),s=`${a} takes ${cP(o,i)}`;if(`min`in n&&(o===`bool`||!(`min`in o))){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:q(e.source,[`actions`,t,`min`])});return}let c=tG(n,i);if(c===eG){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:q(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!sP(o,e.value,i));if(l.length!==0){if(a===Jx.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>Ry(e.value)))){let r=Jx.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:_U(`actions.${t}.to`,n.to,`set: "${r}", to`),line:q(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:q(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=$W?r.join(`, `):`${r.slice(0,$W).join(`, `)} and ${r.length-$W} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:q(e.source,[`actions`,t,n])})}}}const $W=3,eG=Symbol(`any integer`);function tG(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?Lw(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)}]:eG}function nG(e,t){return Object.entries(e).filter(([e])=>t(e))}function rG(e,t,n,r){let i=Ez(t),a=Iw(i);for(let[n,o]of nG(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 ${zw(r,i)}`,line:q(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;Vee.has(o.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${o.set}", which has no session pick — globals.${o.set} is set in the config file only, so a click would change nothing; write it with { persist: "${o.set}", … } instead`,line:q(e.source,[`actions`,n,`set`])});let s=tS.get(o.set);s!==void 0&&QW(e,n,o,s,i)}for(let[n,i]of nG(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&&Ww(o)?`"${r}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${r}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:q(e.source,[`actions`,n,`do`])})});for(let[n,i]of nG(t.actions,r))if(`run`in i)for(let r of i.refreshes){let i=Object.hasOwn(t.variables,r)?t.variables[r]:void 0;i?.kind!==`source`&&e.issues.push({path:`actions.${n}.refreshes`,message:`actions.${n} refreshes "${r}", which ${i===void 0?`is not declared`:`is a ${i.kind} variable`}: a run refreshes only a declared source (by its full name, <scope>.<plugin>.<source> where the scope is plugins or repo; a plugin names its own sources bare)`,line:q(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of nG(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=YP(r);if(o===null){let t=ote(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${ste().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, a "themeDefaults.<theme>.<shade|variation|style>" target, or a "presets.<name>.root" target`:`actions.${n}: the globals field "${r}" was removed: ${t}`,line:q(e.source,[`actions`,n,a])});continue}let s=jW.filter(e=>e in i);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:q(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){MW(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Tw(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: ${Tw(t.presets).join(`, `)})`,line:q(e.source,[`actions`,n,a])});continue}if(o.scope===`theme-default`&&!e.allowedPalettes.has(o.theme)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names theme "${o.theme}" which is not installed${dy(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:q(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${lV(o.segment)}`,line:q(e.source,[`actions`,n,a])});continue}`min`in i&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:q(e.source,[`actions`,n,a])})}}for(let[i,a]of nG(t.variables,r)){HW(e,`variables.${i}`,a,n);let t=kB(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:q(e.source,[`variables`,i])})}for(let[i,a]of nG(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))HW(e,`segments.${i}.vars.${t}`,r,n,i);let r=gb(a);if(FW(e,i,r),a.partials!==void 0)for(let t of Object.keys(a.partials))Object.hasOwn(n.helpers,t)&&e.issues.push({path:`segments.${i}.partials.${t}`,message:`segments.${i}.partials.${t} reuses the name of a global helper (helpers.${t}) — partials and helpers share one define chain, so pick a name no helper already uses`,line:q(e.source,[`segments`,i,`partials`,t])});let o=a.partials===void 0?n.helpers:{...n.helpers,...a.partials},s=PW({...n,helpers:o},r);for(let n of lW){let c=a[n];typeof c==`string`&&(YW(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),JW(e,t,`segments.${i}.${n}`,c,q(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of nG(t.variables,r))UW(e,`variables.${i}`,a,n),GW(e,`variables.${i}`,a,t);KW(e,t);for(let[i,a]of nG(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))UW(e,`segments.${i}.vars.${r}`,o,n,i),GW(e,`segments.${i}.vars.${r}`,o,t)}function iG(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=aG(t),a=new Map,o=[];for(let e of r.keys())a.set(e,0);for(let e of r.keys())if(!(!n(e)||a.get(e)!==0)&&s(e))return;function s(t){a.set(t,1),o.push(t);for(let c of r.get(t)??[]){if(!n(c))continue;let t=a.get(c);if(t===1){let t=o.indexOf(c),n=[...o.slice(t),c],r=n[0],a=i.get(r);return e.issues.push({path:a?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:q(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function aG(e){let t=new Map,n=new Map,r=jU(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 oG(e,t,n){let r=new Map([...mT(t)].map(([e,,t])=>[e,t]));for(let[t,i]of r){let a=t.split(`.`);for(let o=1;o<a.length;o++){let s=a.slice(0,o).join(`.`),c=r.get(s);if(c===void 0||!(n.checked(t)||n.checked(s)))continue;let[l,u,d]=n.authored(t)?[t,s,i]:[s,t,c],f=n.authored(t)===n.authored(s)?`Rename one so neither name starts with the other.`:`"${u}" is declared outside this file (the bundled default, a plugin, or a control the bar builds), so rename "${l}".`;e.issues.push({path:d.join(`.`),message:`variable "${t}" is declared under the variable "${s}" — a read of ".${t}" would name both, "${t}" and a field of "${s}". ${f}`,line:q(e.source,[...d])})}}}function sG(e){let t=[...[...(process.env.XDG_DATA_DIRS||uG()).split(`:`).filter(e=>e!==``)].reverse().map(e=>o.join(e,`cc-candybar`,`plugins`)),cG()];return[...t.filter((e,n)=>t.lastIndexOf(e)===n).map(e=>({dir:e,scope:`plugins`})),...e===null?[]:[{dir:o.join(e,lG),scope:`repo`}]]}function cG(){let e=process.env.XDG_DATA_HOME||o.join(D.homedir(),`.local`,`share`);return o.join(e,`cc-candybar`,`plugins`)}const lG=o.join(`.cc-candybar`,`plugins`);function uG(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${o.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function dG(e){let t=sG(e),n=new Map,r=[],i=[];for(let{dir:e,scope:a}of t){let t=fG(e);if(`error`in t){r.push(t);continue}for(let r of t.folders){let t=GU(o.join(e,r,UU),a),i=`${a}\0${r}`;n.delete(i),n.set(i,t)}for(let n of t.files)i.push({path:o.join(e,n),scope:a,name:void 0,reason:`a plugin is a folder holding its ${UU}: move this file to ${o.join(e,`<name>`,UU)}`})}return{roots:t.map(e=>e.dir),definitions:[...n.values()],unchecked:r,strays:i}}function fG(e){try{let t=f.readdirSync(e,{withFileTypes:!0}).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),n=t=>t.isDirectory()||pG(e,t);return{folders:t.filter(n).map(e=>e.name),files:t.filter(e=>!n(e)).map(e=>e.name)}}catch(t){return t.code===`ENOENT`?{folders:[],files:[]}:{path:e,error:t.message}}}function pG(e,t){if(!t.isSymbolicLink())return!1;try{return f.statSync(o.join(e,t.name)).isDirectory()}catch{return!0}}function mG(e){try{return f.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const hG=[`approved`,`declined`];function gG(e){return e.link.kind===`linked`?e.link.main:e.dir}const _G=(e,t)=>Object.hasOwn(e,t)?e[t]:null;function vG(e,t){let n=gG(t);if(e.kind===`failed`)return{standing:`unread`,under:n};let r=_G(e.value,n),i=_G(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 yG(e,t,n){let r=[...new Map([...t,...n?.ships?[n]:[]].map(e=>[e.dir,e])).values()],i=r.map(t=>({dir:t.dir,...vG(e,t)})),a=e=>i.filter(t=>t.standing===e),o=e=>[...new Set(a(e).map(e=>e.under))];return{plugins:n!==null&&vG(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 bG(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 xG(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(!hG.includes(n))return{kind:`failed`,reason:`answers ${JSON.stringify(t)} ${JSON.stringify(n)}, not ${hG.join(` or `)}`};return{kind:`ok`,value:e}}function SG(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 CG(e){let t=SG(e);return[...t===null?[]:[t],...e.awaiting.map(e=>`awaiting approval: ${e} — its cc-candybar config runs once it is approved in the bar`),...e.declined.map(e=>`declined: ${e} — its cc-candybar config does not run`),...e.unproven.map(e=>`not proven a worktree: ${e.dir} — it answers for itself, because ${e.reason}`)]}const wG=[`json5`,`json`];function TG(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?wG.map(t=>o.join(e,`${EG}.${t}`)):[],...wG.map(e=>o.join(r,`${EG}.${e}`)),...wG.map(e=>`${DG()}.${e}`)])]}const EG=`.cc-candybar`;function DG(){let e=process.env.XDG_CONFIG_HOME??o.join(D.homedir(),`.config`);return o.join(e,`cc-candybar`,`config`)}function OG(e){return{path:e,scope:`plugins`}}function kG(e,t,n,r){let i=[],a=new Map;for(let e of TG(t,n,r)){let t=mG(e);if(t===`absent`)continue;if(t!==`present`){i.push(t);continue}let n=f.realpathSync.native(o.dirname(e)),s=o.join(n,o.basename(e).replace(/\.(json5|json)$/,``));a.has(s)||a.set(s,{file:e,repo:r!==void 0||AG(e)?null:{dir:n,link:Vc(n)}})}let s=[...a.values()],c=yG(e,s.flatMap(e=>e.repo===null?[]:[e.repo]),jG(t)),l=s.filter(e=>e.repo===null||c.approved.includes(e.repo.dir)).reverse().map(e=>({path:e.file,scope:e.repo===null?`plugins`:`repo`}));if(r===void 0)return{kind:`chain`,layers:l,home:MG(l),unchecked:i,repos:c};let[u]=i,d=r;return l.length>0?{kind:`chain`,layers:l,home:d,unchecked:i,repos:c}:u===void 0?{kind:`missing`,path:r,home:d,repos:c}:{kind:`unreadable`,...u,home:d,repos:c}}function AG(e){return wG.some(t=>e===`${DG()}.${t}`)}function jG(e){if(e===void 0||mG(e)!==`present`)return null;let t=fG(o.join(e,lG)),n=f.realpathSync.native(e);return{dir:n,link:Vc(n),path:e,ships:!(`error`in t)&&t.folders.length>0}}function MG(e){return e.find(e=>AG(e.path))?.path??`${DG()}.${wG[0]}`}function NG(e,t,n,r){let i=kG(e,t,n,r),a=i.kind===`chain`?i.layers:[];return{path:i.home,above:a.filter(e=>e.path!==i.home),repo:i.repos.plugins,cwd:n??null}}function PG(e){return FG(e).join(`
|
|
182
182
|
`)||null}function FG(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 IG(e,t){let n=TG(e,t).filter(e=>mG(e)===`present`),r=new Map;for(let e of n){let t=o.dirname(e),n=o.basename(e).replace(/\.(json5|json)$/,``),i=o.join(t,n);r.has(i)||r.set(i,[]),r.get(i).push(e)}let i=[...r.values()].filter(e=>e.length>1);return i.length===0?null:`config-extension collision: ${i.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function LG(e,t,n,r){return e===null?{...qG,config:gB(qG.raw,t)}:zG(e,f.readFileSync(e,`utf-8`),t,n,r)}const RG={scope:`plugins`,repo:null,checkout:null,beneath:{dropped:[],rendering:new Map}};function zG(e,t,n,r,i){let a=eK(e,t,i,(t,a)=>{let o=ZU(XU(t,e,r.scope),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>GG(t,n,r,e,i)),s=tW(o,r.beneath.dropped);return{inherited:new Set([...EV(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=nW(gB(a.raw,o.config),s,(a.raw.insert??[]).map(e=>e.seg));return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(VU)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const BG=new WeakMap;function VG(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e.path,e.scope,UG(e.path)])]),a=BG.get(n)??new Map;BG.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=ZU(e,t,{config:n,rendering:new Map},(e,t,n)=>GG(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function HG(e,t,n){return ZU(e,{repo:null,checkout:n},{config:t,rendering:new Map},(e,t,n)=>GG(e,t,n,`<plugin install>`,void 0)).dropped}function UG(e){try{let t=f.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function WG(e,t,n,r,i=e=>f.readFileSync(e,`utf-8`),a){let o={repo:r.repo,checkout:r.cwd===null?null:Nc(r.cwd)},s=dG(o.repo),c=VG(s.definitions,o,t,a),l={...c,dropped:[...c.dropped,...s.strays]};n.warned(s.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let u=l.config,d=[];for(let{path:t,scope:r}of e){let e=d.at(-1)?.plugins,s=zG(t,i(t),d.at(-1)?.config??u,{...o,scope:r,beneath:{dropped:[...l.dropped,...d.flatMap(e=>e.plugins.dropped)],rendering:e?.rendering??l.rendering}},a);n.warned(s.warnings),d.push({...s,path:t})}let p=new Set(d.flatMap(e=>[...e.plugins.reached])),m=e=>p.has(e.path),h=l.dropped.filter(m),g=l.dropped.filter(e=>!m(e));n.warned(h.map(VU));let _=d.at(-1)?.plugins.rendering??l.rendering,v={checkout:o.checkout,roots:s.roots,loaded:l.loaded,dropped:h,unreached:g,reached:p,rendering:_},y=d.at(-1),b=({warnings:e,...t})=>(n.warned(e),t);if(y===void 0)return{layers:d,base:u,installed:v,...b(JG(LG(null,u,RG),_,`<default>`,a))};try{return{layers:d,base:u,installed:v,...b(JG(y,_,y.path,a,d.slice(0,-1).reverse()))}}catch(e){for(let[e,t]of d.slice(0,-1).entries())JG(t,t.plugins.rendering,t.path,a,d.slice(0,e).reverse());throw e}}function GG(e,t,n,r,i){if(n){JG(KG(e),new Map,r,i);return}let a=qw(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[],unplaced:[],inherited:[]};if(rG(s,e,vT(e),a),iG(s,e,a),oG(s,e,{checked:a,authored:a}),o.length>0)throw new Cb(r,o)}function KG(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const qG={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function JG(e,t,n=`<config>`,r=new Set(my()),i=[]){let a=CU(e.config.segments,t),o=XG({...e,path:n},i,a),s=(t,s)=>{let c=kw(e.config,t,o.authored);return YG(e,n,r,i,c.config,a,o.dropped,[...c.notices,...s])};try{return s(o.cells,[])}catch(e){if(!(e instanceof Cb)||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 Cb))throw r;let i=r.issues.filter(e=>!n.has(e.message)).map(e=>e.message).join(`; `);return{...e,refused:[...e.refused,Aw(t,`${t.relation} "${t.anchor}", but the bar refuses it there: ${i}`)]}}},{taken:[],refused:[]});return s(r,i)}}function YG({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 Cb(n,[...l,...u.unplaced,...u.inherited],c)};AW(u,a,e,o),iG(u,a),d();let f=QG(n,a.segments,u,o,i,s),p=CH(EU(a),l);d();let m=Jz(uz(p)),h=new Set([...mT({variables:e.variables??{},segments:e.segments??{}})].map(([e])=>e));return oG(u,m,{checked:()=>!0,authored:e=>h.has(e)}),d(),{config:m,dropped:f,placed:a,warnings:c}}function XG(e,t,n){let r=[...t].reverse().concat(e),i=TU(e.config,r.flatMap(e=>e.raw.insert??[]),n),a=e=>!i(e.anchor),o=e=>n(e.seg).kind===`declared`,s=e=>wU(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=wb(t.source);return(t.raw.insert??[]).filter(s).map(i=>({file:t.path,issue:{path:i.by.entry,message:DW(i.by.entry,i.seg,e.config.segments,n(i.seg)),line:r(i.by.entry.split(`.`))}}))})}}function ZG(e){if(e.length>0)throw new Aee(e)}function QG(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=EW(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:DW(n.layoutKey,a,t,r(a)),line:q(n.layer.source,n.path.split(`.`))})}return[...o].map(([e,t])=>new kee(e,t))}function $G(e,t,n=new Set(my()),r=tK){return eK(e,t,n,()=>({inherited:r,layer:null})).raw}function eK(e,t,n,r){let i=nK(e,t),a=Fee(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(my()),groups:[],unplaced:[],inherited:[]};if(!Ab(i))throw new Cb(e,[{path:``,message:`Config root must be an object, got ${jb(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:aK({...c,issues:[]},i.plugins)??[],Ab(i.segments)?Object.keys(i.segments):[]),d=rK(c,i,l,EH(e),e);if(s.length>0)throw new Cb(e,s,o);return{raw:d,warnings:o,layer:u}}const tK=new Set;function nK(e,t){try{return Ia.default.parse(t)}catch(t){let n=t;throw new Cb(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function rK(e,t,n,r,i){for(let n of Object.keys(t))iK.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...iK].join(`, `)}`,line:q(e.source,[n])});let a={};return t.globals!==void 0&&(a.globals=BP(e,`globals`,t.globals)),t.variables!==void 0&&(a.variables=FB(e,`variables`,t.variables)),t.segments!==void 0&&(a.segments=DV(e,t.segments,n)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
|
|
183
183
|
Replace: layout: [["seg1", "seg2"], ["seg3"]]
|
|
184
184
|
With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
|
|
185
|
-
Single-row example: root: { h: ["seg1", "seg2"] }`,line:q(e.source,[`layout`])}),t.root!==void 0&&(a.root=eH(e,`root`,t.root)),t.insert!==void 0&&(a.insert=nH(e,t.insert,i)),t.actions!==void 0&&(a.actions=wH(e,t.actions,r)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:q(e.source,[`looks`])}),t.styles!==void 0&&(a.styles=yU(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=zP(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=xU(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=UP(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=SU(e,t.helpers)),t.plugins!==void 0&&(a.plugins=aK(e,t.plugins)),uH(e,a),xH(e,a),xte(e,a),$P(e,a,P,`the global settings menu`),vte(e,a,n),a}const iK=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function aK(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 ${jb(t)}`,line:q(e.source,[`plugins`])})}const oK={},sK=SL(`commands.`),cK=OL(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),lK=gL(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),uK=`{{ ${yF} }}`,dK={min:0,max:100,step:5},fK={warnAt:{label:`warning at %`,domain:dK,default:50},errorAt:{label:`error at %`,domain:{...dK,atLeast:`warnAt`},default:80}};function pK(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:dK,default:80}}}const mK={globals:{palette:`tokyo-night`},variables:{...sK.variables,...UN,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:`⊫`},...lK.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:uK},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 ${lK.armed} }}{{ if ne .git.branch "" }} {{ end }}${lK.template}{{ end }}`,fg:uK,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:uL(``).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:sK.template,when:sK.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:pK(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:pK(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) ${Bv} }}`,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:cK.template,bg:cK.bg,when:cK.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:{...uL(``).actions,...sK.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...lK.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...cK.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:oK,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 ${Bv} }}{{ \$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 (${yF}) 2 (readableOn (color "accent") (bgOf) ${Bv})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Bv}) .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:kL(`.`),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 .)) }}`}},hK=new Set([mK.globals.palette,...Object.keys(mK.themeDefaults),...Object.values(mK.segments).map(e=>e.palette)].filter(e=>e!==void 0)),gK=gB($G(`<default>`,JSON.stringify(mK),hK),mK),_K=Tw(gK.presets);function vK(e){return _K.includes(e)}const yK=Object.freeze({});function bK(e,t){return e.kind===`decided`?t[e.name]??yK:yK}function xK(e,t){return{...e,...Object.fromEntries(Vx.map(n=>[n,e[n]??t[n]]))}}const SK=(e,t)=>fx(n=>{let{setting:r,on:i,inTmux:a}=ax[n].switch;return e[r]===i&&(t||!a)});function CK(e,t,n,r){let i=Ux(e);return py(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function wK(e,t){return Ew(t(`preset`),e.globals.preset,e.presets)}function TK(e,t,n){let r=wK(e,t),i=jw(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=aw(a.palette,t(`theme`),i.palette),s=xK(i,bK(o,e.themeDefaults));return{...Object.fromEntries(zx.map(e=>[e,CK(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:Ty(a.style,t(`style`),s.style,e.styles),effect:Fy(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function EK(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?Wy:Gy;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const DK=Object.entries(Jx),OK=new Set(Xx.map(e=>e.sessionKey)),kK=()=>!1;function AK(e,t){return TK(e,e=>OK.has(e)?t(e):null,kK)}const jK=[`preset`,`theme`];function MK(e,t,n){let r=new Set(jK.slice(0,n).map(e=>Jx[e].sessionKey));return TK(e,e=>r.has(e)?t(e):null,kK)}function NK(e,t){let n=Array.from({length:jK.length+1},(n,r)=>MK(e,t,r));return e=>{let t=jK.indexOf(e);return n[t===-1?jK.length:t]}}function PK(e,t,n,r){return e.flatMap(([e,i])=>{let a=EK(t,e);return a===null||a===EK(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function FK(e,t,n){return EK(AK(e,t),n)}function IK(e,t){let n=AK(e,t);return PK(DK,n,NK(e,t),t=>LK(e,n.preset,t.configKey))}function LK(e,t,n){return n in(Dw(e.presets,t).globals??{})?JP(t,n):n}function RK(e,t,n){let r=Ew(t(Jx.preset.sessionKey),e.globals.preset,e.presets),i=YP(n);return{key:i?.scope===`globals`?LK(e,r,i.field):n,globals:jw(e,r)}}function zK(e,t){let{preset:n}=AK(e,t);return HK(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:xb(a,s);return c===void 0||bb(c)===bb(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function BK(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Tw(e.presets).flatMap(n=>{let i=HK(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 vb(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:xb(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const VK=new WeakMap;function HK(e,t){let n=VK.get(e)??new Map;VK.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...nb(Ow(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=gb(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 UK(e,t){let n=AK(e,t);return{from:n.preset,globals:Dw(e.presets,n.preset).globals??{},picks:PK(DK.filter(([e])=>e!==`preset`),n,NK(e,t),e=>e.configKey),placements:zK(e,t)}}function WK(e,t){return TK({...e,globals:{palette:t},presets:{}},()=>null,kK)}function GK(e,t){let n=AK(e,t),r=EK(n,`theme`);if(r===null)return{kind:`rule`};let i=WK(e,r),a=jw(e,n.preset),o=Object.fromEntries(Vx.map(e=>[e,EK(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:Vx.some(e=>o[e]!==EK(i,e))}}function KK(e){return{sessionKeys:Xx.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...FP(e)?_K.map(t=>JP(t,e)):[],...qP(e)?my().map(t=>mte(t,e)):[]]}}function qK(e){return new Set(Xx.map(e=>e.configKey).filter(t=>KK(t).fileKeys.some(t=>XK(e,YK(t)))))}function JK(e,t,n){let r=IK(e,n),i=new Set(r.map(e=>e.configKey)),a=tS(e=>i.has(Jx[e].configKey)||t.has(Jx[e].configKey)),o=GK(e,n);return{unsaved:r.length+zK(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function YK(e){let t=YP(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return XP(t)}function XK(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&XK(e[n],r)}const ZK=my(),QK=new Set(ZK),$K=new Set(Iy),eq=e=>e?QK.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${ZK.join(`, `)})`}:{ok:!1,reason:`theme name is required`},tq=e=>e?$K.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Iy.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},nq=new Set([`1`,`true`]),rq=new Set([`0`,`false`]),iq={endcaps:tq,theme:eq,"toolbar-expanded":e=>nq.has(e)?{ok:!0,value:`1`}:rq.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},aq=sB(iq,`state`,fq);function oq(e,t){return aq.register(e,t)}function sq(e){return aq.gateFor(e)}function cq(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:Lw(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 lq(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(iq,e.key))}function uq(e,t,n){let r=nS.get(n);if(r!==void 0)return FK(e,t,r);for(let[,t]of fb(e))if(t.key===n)return t.default??null;return null}function dq(e){let t=Ez(e);return lq(Object.values(e.actions).flatMap(e=>cq(e,t)))}function fq(e){return aB(dq(e))}const pq=`update.dismissed`,mq=`updateNotice`,hq=Jx.updateNotice.sessionKey;function gq(e){return e.kind===`source`?e.newer.digest:ds(e.newer)}const _q=e=>`${e.version} [${et(e.digest)}]`;function vq(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:_q(e.newer),running:_q(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:ds(e.newer),running:ds(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${ps}@${ds(e.newer)}`,`install`]}}}}function yq(e,t,n){if(e===null)return[];let r=gq(e);if(!n.enabled||n.dismissed===r)return[];let i=vq(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(`
|
|
185
|
+
Single-row example: root: { h: ["seg1", "seg2"] }`,line:q(e.source,[`layout`])}),t.root!==void 0&&(a.root=eH(e,`root`,t.root)),t.insert!==void 0&&(a.insert=nH(e,t.insert,i)),t.actions!==void 0&&(a.actions=wH(e,t.actions,r)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:q(e.source,[`looks`])}),t.styles!==void 0&&(a.styles=yU(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=zP(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=xU(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=UP(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=SU(e,t.helpers)),t.plugins!==void 0&&(a.plugins=aK(e,t.plugins)),uH(e,a),xH(e,a),xte(e,a),$P(e,a,P,`the global settings menu`),vte(e,a,n),a}const iK=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function aK(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 ${jb(t)}`,line:q(e.source,[`plugins`])})}const oK={},sK=SL(`commands.`),cK=OL(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),lK=gL(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),uK=`{{ ${yF} }}`,dK={min:0,max:100,step:5},fK={warnAt:{label:`warning at %`,domain:dK,default:50},errorAt:{label:`error at %`,domain:{...dK,atLeast:`warnAt`},default:80}};function pK(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:dK,default:80}}}const mK={globals:{palette:`tokyo-night`},variables:{...sK.variables,...UN,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:`⊫`},...lK.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:uK},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 ${lK.armed} }}{{ if ne .git.branch "" }} {{ end }}${lK.template}{{ end }}`,fg:uK,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:uL(``).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:sK.template,when:sK.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:pK(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:pK(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) ${Bv} }}`,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:cK.template,bg:cK.bg,when:cK.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:{...uL(``).actions,...sK.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...lK.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...cK.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:oK,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 ${Bv} }}{{ \$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 (${yF}) 2 (readableOn (color "accent") (bgOf) ${Bv})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Bv}) .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:kL(`.`),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 .)) }}`}},hK=new Set([mK.globals.palette,...Object.keys(mK.themeDefaults),...Object.values(mK.segments).map(e=>e.palette)].filter(e=>e!==void 0)),gK=gB($G(`<default>`,JSON.stringify(mK),hK),mK),_K=Tw(gK.presets);function vK(e){return _K.includes(e)}const yK=Object.freeze({});function bK(e,t){return e.kind===`decided`?t[e.name]??yK:yK}function xK(e,t){return{...e,...Object.fromEntries(Vx.map(n=>[n,e[n]??t[n]]))}}const SK=(e,t)=>fx(n=>{let{setting:r,on:i,inTmux:a}=ax[n].switch;return e[r]===i&&(t||!a)});function CK(e,t,n,r){let i=Ux(e);return py(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function wK(e,t){return Ew(t(`preset`),e.globals.preset,e.presets)}function TK(e,t,n){let r=wK(e,t),i=jw(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=aw(a.palette,t(`theme`),i.palette),s=xK(i,bK(o,e.themeDefaults));return{...Object.fromEntries(zx.map(e=>[e,CK(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:Ty(a.style,t(`style`),s.style,e.styles),effect:Fy(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function EK(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?Wy:Gy;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const DK=Object.entries(Jx),OK=new Set(Xx.map(e=>e.sessionKey)),kK=()=>!1;function AK(e,t){return TK(e,e=>OK.has(e)?t(e):null,kK)}const jK=[`preset`,`theme`];function MK(e,t,n){let r=new Set(jK.slice(0,n).map(e=>Jx[e].sessionKey));return TK(e,e=>r.has(e)?t(e):null,kK)}function NK(e,t){let n=Array.from({length:jK.length+1},(n,r)=>MK(e,t,r));return e=>{let t=jK.indexOf(e);return n[t===-1?jK.length:t]}}function PK(e,t,n,r){return e.flatMap(([e,i])=>{let a=EK(t,e);return a===null||a===EK(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function FK(e,t,n){return EK(AK(e,t),n)}function IK(e,t){let n=AK(e,t);return PK(DK,n,NK(e,t),t=>LK(e,n.preset,t.configKey))}function LK(e,t,n){return n in(Dw(e.presets,t).globals??{})?JP(t,n):n}function RK(e,t,n){let r=Ew(t(Jx.preset.sessionKey),e.globals.preset,e.presets),i=YP(n);return{key:i?.scope===`globals`?LK(e,r,i.field):n,globals:jw(e,r)}}function zK(e,t){let{preset:n}=AK(e,t);return HK(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:xb(a,s);return c===void 0||bb(c)===bb(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function BK(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Tw(e.presets).flatMap(n=>{let i=HK(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 vb(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:xb(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const VK=new WeakMap;function HK(e,t){let n=VK.get(e)??new Map;VK.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...nb(Ow(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=gb(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 UK(e,t){let n=AK(e,t);return{from:n.preset,globals:Dw(e.presets,n.preset).globals??{},picks:PK(DK.filter(([e])=>e!==`preset`),n,NK(e,t),e=>e.configKey),placements:zK(e,t)}}function WK(e,t){return TK({...e,globals:{palette:t},presets:{}},()=>null,kK)}function GK(e,t){let n=AK(e,t),r=EK(n,`theme`);if(r===null)return{kind:`rule`};let i=WK(e,r),a=jw(e,n.preset),o=Object.fromEntries(Vx.map(e=>[e,EK(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:Vx.some(e=>o[e]!==EK(i,e))}}function KK(e){return{sessionKeys:Xx.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...FP(e)?_K.map(t=>JP(t,e)):[],...qP(e)?my().map(t=>mte(t,e)):[]]}}function qK(e){return new Set(Xx.map(e=>e.configKey).filter(t=>KK(t).fileKeys.some(t=>XK(e,YK(t)))))}function JK(e,t,n){let r=IK(e,n),i=new Set(r.map(e=>e.configKey)),a=eS(e=>i.has(Jx[e].configKey)||t.has(Jx[e].configKey)),o=GK(e,n);return{unsaved:r.length+zK(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function YK(e){let t=YP(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return XP(t)}function XK(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&XK(e[n],r)}const ZK=my(),QK=new Set(ZK),$K=new Set(Iy),eq=e=>e?QK.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${ZK.join(`, `)})`}:{ok:!1,reason:`theme name is required`},tq=e=>e?$K.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Iy.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},nq=new Set([`1`,`true`]),rq=new Set([`0`,`false`]),iq={endcaps:tq,theme:eq,"toolbar-expanded":e=>nq.has(e)?{ok:!0,value:`1`}:rq.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},aq=sB(iq,`state`,fq);function oq(e,t){return aq.register(e,t)}function sq(e){return aq.gateFor(e)}function cq(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:Lw(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 lq(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(iq,e.key))}function uq(e,t,n){let r=tS.get(n);if(r!==void 0)return FK(e,t,r);for(let[,t]of fb(e))if(t.key===n)return t.default??null;return null}function dq(e){let t=Ez(e);return lq(Object.values(e.actions).flatMap(e=>cq(e,t)))}function fq(e){return aB(dq(e))}const pq=`update.dismissed`,mq=`updateNotice`,hq=Jx.updateNotice.sessionKey;function gq(e){return e.kind===`source`?e.newer.digest:ds(e.newer)}const _q=e=>`${e.version} [${et(e.digest)}]`;function vq(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:_q(e.newer),running:_q(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:ds(e.newer),running:ds(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${ps}@${ds(e.newer)}`,`install`]}}}}function yq(e,t,n){if(e===null)return[];let r=gq(e);if(!n.enabled||n.dismissed===r)return[];let i=vq(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(`
|
|
186
186
|
`),c=t.kind===`running`?lC(`[${i.busy}]`,null):lC(`[${i.act}]`,Ea([{verb:ca,args:[n.sessionId]}])),l=[lC(a,null),c,lC(`[dismiss]`,Ea([{verb:Wi,args:[n.sessionId,pq,r]}])),lC(`[disable]`,Ea([{verb:Xi,args:[n.sessionId,mq,`false`]},{verb:Wi,args:[n.sessionId,hq,`false`]}]))],u=o.map(e=>[lC(e,null)]);return[{severity:oC,about:`update\0${r}`,message:s,copy:s,lines:[l,...u]}]}function bq(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function xq(e){switch(e.kind){case`current`:return[`info`,`build: current ${_q(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${_q(e.source)}, running ${_q(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function Sq(e){switch(e.kind){case`current`:return[`info`,`release: current ${ds(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${ds(e.latest)}, running ${ds(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${ds(e.installed)}, latest ${ds(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function Cq(){let e=[lB(mq,[`false`]),oq(hq,[`false`]),oq(pq,[])];return()=>e.forEach(e=>e())}function wq(e){let{launcher:t,entryUrl:n,digest:r,actsDir:i,intervalMs:a,releaseIntervalMs:o,registryUrl:s,fetchImpl:c,onApplied:l,log:u}=e,d={kind:`unchecked`,reason:`not sampled yet`},f=null,p=async e=>{let n=await $s(e,t.launch);if(x)throw new JC(`apply-update`);return n},m=HC(i,p),h=null,g=null,_=Fe(u),v=Fe(u),y=new qC,b=e=>y.run(`acts`,e),x=!1,S=[],C=(e,t)=>{let n=setInterval(e,t).unref();S.push(()=>clearInterval(n))},ee=()=>x?null:bq(d,f);function te(){let e=ee(),t=e===null?null:gq(e);(g===null?null:g.identity)!==t&&(g?.dispose(),g=t===null?null:{identity:t,dispose:oq(pq,[t])})}function w(){d=ot(n,()=>rt(r)),_(xq(d)),te()}async function ne(){f=hs(tt,await ms(ps,c,s)),v(Sq(f)),te()}let T=null,re=Fe(u);async function E(e){try{let t=await e();return T=null,{ok:!0,value:t}}catch(e){return e instanceof JC?{ok:!1,error:e.message}:(T=`update act files (${i}): ${e.message}`,re([`error`,T]),{ok:!1,error:T})}}function D(e){if(!e?.alive||Date.now()<=e.record.deadline)return;let{stands:t,signalled:n}=KC(i,e),r=t?`timed out`:`outlived its verdict`,a=n?`ending it`:`its group took no signal`;u(`error`,`apply-update: act ${e.act} ${r}; ${a}`)}async function ie(){let e=await E(async()=>{let e=await m.read();return x||D(e),e});if(x||!e.ok)return;let t=MC(e.value);h===null&&t.kind===`running`&&u(`info`,`apply-update: act ${t.act} is running; watching it`),h?.kind===`running`&&t.kind!==`running`&&(t.kind===`succeeded`&&(u(`info`,`apply-update: act ${t.act} succeeded`),w(),l()),t.kind===`failed`&&u(`error`,`apply-update: act ${t.act} failed: ${t.reason}`)),h=t}let O;async function ae(){await b(ie),!x&&(O=setTimeout(()=>void ae(),2e3),O.unref())}return{arm(){S.push(Cq()),w(),C(w,a),S.push(()=>clearTimeout(O)),ae(),d.kind===`not-source-checkout`&&(ne(),C(()=>void ne(),o))},close(){x=!0,te(),S.forEach(e=>e())},notice:e=>yq(ee(),h??jC,e),running:()=>b(async()=>{let e=await E(()=>m.read());return e.ok&&MC(e.value).kind===`running`}),error:()=>T,act:()=>b(async()=>{if(x)throw new JC(`apply-update`);let e=await E(()=>m.read());if(x)throw new JC(`apply-update`);if(!e.ok)throw new Y(`apply-update: ${e.error}`);let n=ee();if(n===null)throw new Y(`apply-update: nothing newer is known to apply`);let r=vq(n),a=e.value;if(MC(a).kind===`running`)throw new Y(`apply-update: already ${r.busy}`);let o=await WC(t,i,a===null?null:a.act,gq(n),{...r.command,category:`update.apply`},6e5,Date.now(),p);if(!o.ok)throw new Y(`apply-update: ${o.reason}`);u(`info`,`apply-update: act ${o.act}: ${r.act} — ${r.command.bin} ${r.command.args?.join(` `)??``}`),h={kind:`running`,act:o.act}})}}function Tq(e,t,n,r){let i=o.join(e,t),a=()=>{let e;try{e=f.readFileSync(i,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${i}: ${e.message}`}}let t;try{t=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${i} is not JSON: ${e.message}`}}let a=r(t);return a.kind===`ok`?a:{kind:`failed`,reason:`${i} ${a.reason}`}};return{read:a,update:e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return n!==t.value&&st(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const Eq=`repo-configs.json`;function Dq(e=mt()){return o.join(e,`repo-configs`)}function Oq(e=mt()){return o.join(Dq(e),Eq)}const kq=(e=mt())=>{let t=Tq(Dq(e),Eq,{},xG),n=Tq(e,Eq,{},xG),r=()=>f.existsSync(Oq(e));return{read:()=>(r()?t:n).read(),update:e=>{if(r())return t.update(e);let i=n.read();return i.kind===`failed`?i:t.update(()=>e(i.value))}}};function Aq(e,t,n){let r={superseded:[],absent:[],unchecked:[]},i=e.update(e=>{let i=Object.keys(e).filter(e=>e!==t).map(e=>({d:e,found:mG(e)}));return r={superseded:i.filter(({d:e,found:n})=>n===`present`&&gG({dir:e,link:Vc(e)})===t).map(({d:e})=>e),absent:i.filter(({found:e})=>e===`absent`).map(({d:e})=>e),unchecked:i.flatMap(({found:e})=>typeof e==`object`?[e]:[])},bG(e,t,n,r.superseded)});return i.kind===`failed`?i:F(r)}function jq(e,t,n){return{sessionId:e,action:ma,declaration:t,evaluated:n}}function Mq(e,t,n){return e.awaiting.map(e=>{let r=`a cc-candybar config for ${e} — run it?`,i=hG.map(r=>lC(`[${r===`approved`?`approve`:`decline`}]`,Ea([{verb:ma,args:[t,e,r,n.sign(jq(t,e,r))]}]))),a=[lC(r,null),...i];return{severity:sC,about:`repo-question\0${e}`,message:r,copy:r,lines:[a]}})}const Nq={inside:()=>[],defaultOf:()=>N,menus:[]},Pq=e=>`${e.key}\0${e.member}`;function Fq(e){let t=new Map,n=n=>{let r=`${n.name}\0${Qy(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:vH(a,Qy(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(Pq(e))??new Map;n.set(Pq(t),t),o.set(Pq(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(Pq(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 Tw(e.presets))d(Ow(e,t).node,[]);for(let t of Object.values(e.actions)){let e=ji(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(Pq(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(Pq(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(Pq(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const Iq=new WeakMap;function Lq(e){let t=Iq.get(e);if(t!==void 0)return t;let n=Fq(e);return Iq.set(e,n),n}function Rq(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 zq(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 Bq(e,t,n){let r=(r,i,a)=>{let o=Rq(t(r),t=>e.get(r,t),i);(0,X.runInAction)(()=>{a();for(let t of o)e.clear(r,t)}),o.length>0&&n(`close-nested: folded=${o.join(`,`)} (session=${r})`)},i=(t,n)=>r(t,n,()=>e.setBatch(t,n));return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(e,t,n)=>i(e,[{key:t,value:n}]),setBatch:i,clear:(n,i)=>r(n,[{key:i,value:t(n).defaultOf(i)}],()=>e.clear(n,i))}}const Vq=new Set([`1`,`true`]),Hq=new Set([`0`,`false`,``]);function Uq(e,t){let n=mJ(e),r=n.scope===`segment-palette`?`string`:Gx(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(Vq.has(t))return`true`;if(Hq.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function Wq(e){try{return f.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function Gq(e,t,n){try{if(t===null){f.rmSync(ct(e),{force:!0});return}st(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function Kq(e){return/^\s*$/.test(e)?null:Ua(e)}function qq(e,t){return e!==null&&Ga(e,t)!==void 0}function Jq(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(Jq),...i}}return e}function Yq(e){if(!uw(e))return Jq(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Jq(t)])),...n}}const Xq=mK,Zq=Xq.segments,Qq=Xq.presets,$q=Xq.root;function eJ(e,t,n,r){if(!qq(e,t)&&n===void 0)throw new Y(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function tJ(e,t){let n=XP(t);return t.scope===`segment-palette`&&eJ(e,[`segments`,t.segment],Zq[t.segment],n.join(`.`)),n}function nJ(e){return Ua($a(e))}function rJ(){return Object.entries($q.rows).map(([e,t])=>{let n=Jq(t);return{path:[`root`],fragment:nJ({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function iJ(e,t){let n=e===null?void 0:Ga(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function aJ(e,t){if(t===void 0)return null;let n=Yq(t);return{path:e,fragment:nJ(n),unit:{path:e,value:n}}}function oJ(e,t){let n=[`presets`,t],r=[...n,`root`],i=Qq[t];eJ(e,n,i,r.join(`.`));let a=iJ(e,r)??aJ(r,i?.root);return a!==null&&xo(a.fragment)?a:null}function sJ(e,t){let n=bo(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 cJ(e,t){return[...rJ(),iJ(e,[`root`]),oJ(e,t)].filter(e=>e!==null).reduce(sJ,new Map)}function lJ(e,t,n){for(let{node:r,...i}of cJ(e,t).values())if(Co(r,n))return i;throw new Y(`${uJ(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 uJ(e,t){return oJ(e,t)?.path??[`root`]}function dJ(e,t){return t.scope===`preset-root`?uJ(e,t.preset):XP(t)}function fJ(e,{unit:t}){return t===null?e:mo(e,t.path,$a(t.value),Za)}function pJ(e){let t=YP(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function mJ(e){let t=pJ(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function hJ(e,t,n,r,i){let a=EJ(t,r),o,s=()=>(o??={chain:bJ(t,n)}).chain;DJ(t,s,a),i(t,s,a),Gq(t.path,r,e.logger),e.record(t.path,n,r)}function gJ(e,t,n){let r=yJ(e,t(),n);if(r.length>0)throw new Y(`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 _J=()=>{};function vJ(e,t){try{return t()}catch(t){throw!(t instanceof Y)||e.above.length===0?t:new Y(`${t.message} — or it is declared by ${e.above.map(e=>e.path).join(`, `)}, which the bar does not edit`)}}function yJ(e,t,n){if(t===null)return[];let r=new Set(wJ(CJ(t),CJ(n)));return wJ(SJ(e,t),SJ(e,n)).filter(e=>!r.has(e))}function bJ(e,t){try{return xJ(e,t)}catch(e){if(e instanceof Cb)return null;throw e}}function xJ(e,t){return WG(t===null?e.above:[OG(e.path),...e.above],gK,{warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:f.readFileSync(n,`utf8`))}function SJ(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function CJ(e){return e.layers.at(-1)?.config??e.base}function wJ(e,t,n=``){return!TJ(e)||!TJ(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>wJ(e[r],t[r],n===``?r:`${n}.${r}`))}function TJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function EJ(e,t){try{return xJ(e,t)}catch(e){throw e instanceof Cb?new Y(`refused: the config file would not load after this click — ${e.message}`):e}}function DJ(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 Y(`refused: this click would leave a placement of a segment nothing declares — ${o.map(({file:e,issue:t})=>new Cb(e,[t]).message).join(`
|
|
187
187
|
`)}`)}function OJ(e,t){let n=mJ(t),r=Kq(Wq(e)??``),i=r===null?void 0:Ga(r,XP(n));return i!==void 0&&`value`in i?i.value:void 0}function kJ(e,t,n){AJ(e,t,n,[])}function AJ(e,t,n,r){let i=Wq(t.path),a=n.reduce((e,[t,n])=>mo(e,tJ(Kq(e),mJ(t)),Uq(t,n),Za),i??``);hJ(e,t,i,vJ(t,()=>jJ(a,t.path,r,e=>e)),gJ)}function jJ(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=lJ(Kq(s),n,i),l=Do(fJ(s,c),c.path,i,a,$a(o));if(l===null)throw new Y(`${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 MJ(e,t,n){let r=Kq(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of cJ(r,t)){if(!Co(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?qa(e,c):$a(s.value);if(a!==`#`)return mo(e,[...i,`rows`,a],l,Za);if(oJ(r,t)!==null)throw new Y(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return mo(e,i,l,Za)}return e}function NJ(e,t){return go(e,t,t[0]===`presets`&&t.length>2&&!vK(t[1])?2:0)}function PJ(e,t,n){let r=n.map(pJ),i=Wq(t.path);if(i===null)return;let a=r.reduce((e,t)=>NJ(e,dJ(Kq(e),t)),i);a!==i&&hJ(e,t,i,a,_J)}function FJ(e){let t=e===null?void 0:Ga(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function IJ(e,t){let n=new Set([..._K,...FJ(e),...t.above.flatMap(e=>Object.keys(Ia.default.parse(f.readFileSync(e.path,`utf8`)).presets??{}))].map(XN));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(XN(e)))}function LJ(e,t,n,r,i,a){let o=Wq(t.path),s=Kq(o??``),c=IJ(s,t),l=[`presets`,c],u=vJ(t,()=>oJ(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?qa(o??``,u.fragment):$a(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],$a(r)]]],f=i.map(([e,t])=>{let n=JP(c,e);return[tJ(s,mJ(n)),Uq(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>mo(e,t,n,Za),mo(o??``,l,`{}`,Za));return hJ(e,t,o,vJ(t,()=>jJ(p,t.path,a.map(e=>({...e,preset:c})),MJ)),gJ),c}function RJ(e,t,n,r){let i=Wq(t.path);hJ(e,t,i,mo(i??``,[`themeDefaults`,n],$a(r),Za),gJ)}function zJ(e,t,n){if(vK(n))throw new Y(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=Wq(t.path),a=Kq(i??``);if(i===null||a===null||Ga(a,r)===void 0)throw new Y(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Ga(a,[`globals`,`preset`]);hJ(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>NJ(e,t),i),_J)}function BJ(e,t,n,r){let i=pJ(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=Wq(t.path),o=r.op===`remove`?r.target:r.anchor,s=vJ(t,()=>lJ(Kq(a??``),i.preset,o)),c=fJ(a??``,s),{after:l,placed:u}=VJ(c,s.path,r,()=>{let e=EJ(t,c).config;return Tw(e.presets).map(t=>Ow(e,t).node)});if(l===null)throw new Y(`${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 hJ(e,t,a,l,gJ),u}function VJ(e,t,n,r){switch(n.op){case`remove`:return{after:To(e,t,n.target),placed:null};case`insert`:{let i=Zz(n.segment,n.anchor,r());return{after:Eo(e,t,i,n.anchor,n.relation),placed:i}}}}function HJ(e,t,n){let r=(r,i,a)=>{let o=i.filter(t).map(t=>({key:t,before:e.get(r,t)}));a();for(let{key:t,before:i}of o)n(r,t,i,e.get(r,t))};return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(t,n,i)=>r(t,[n],()=>e.set(t,n,i)),setBatch:(t,n)=>r(t,n.map(e=>e.key),()=>e.setBatch(t,n)),clear:(t,n)=>r(t,[n],()=>e.clear(t,n))}}const UJ={load:()=>({}),save:()=>{},flush:()=>{}};var WJ=class{sessions;storage;head=0;atom=(0,X.createAtom)(`SessionState`);constructor(e=UJ,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}observers(){return this.atom.observers_?.size??0}latestRevision(){return this.head}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,X.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t.some(({key:e,value:t})=>n.values.get(e)!==t)&&(n.revision=++this.head);for(let{key:e,value:r}of t)n.values.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,X.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.values.delete(t)&&(n.revision=++this.head),n.values.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,X.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}close(){this.flush(),this.storage=UJ}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};const GJ={load:()=>({}),save:()=>{}},KJ=new Set(Xx.map(e=>e.sessionKey)),qJ=e=>KJ.has(e)||e.startsWith(iF),JJ=8*1024*1024,YJ={past:[],future:[]},XJ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var ZJ=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=GJ){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??YJ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??YJ}begin(){let e=new Map,t=!1,n=(n,r)=>{t=!0;let i=e.get(n)??new Map,a=i.get(XJ(r));i.set(XJ(r),a===void 0?r:{...r,before:a.before}),e.set(n,i)},r=new Map;return{sessionState:HJ(this.sessionState,()=>!0,(e,i,a,o)=>{if(t=!0,!(!qJ(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:aY(i,r),o=n.get(e),s=o===void 0?a:lY(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 Y(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,sY(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new Y(`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(XJ)),a=n.net.filter(e=>!i.has(XJ(e))),o=eY(uY(cY(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new Y(`rewind: ${r.map(fY).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 Y(`redo: nothing to redo`);let a=[...n,i],o=eY(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...nY(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(XJ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:uY(n,t),future:uY(i,t),...a!==void 0&&{savepoint:{at:uY([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(XJ(e))),below:uY(a.below,t)}}}),new Y(`${r}: ${o.map(fY).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):Wq(t.file)}write(e,t,n){t.kind===`file`?Gq(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||QJ(n)>JJ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,$J(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${JJ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function QJ(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 $J({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...nY(n,1,[])}:{past:e,future:t.slice(1),...nY(n,0,[])}}function eY(e){return e.slice(-50)}const tY=e=>e===oF.member;function nY(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:rY(e.net,n),below:e.below}}}function rY(e,t){let n=new Map(e.map(e=>[XJ(e),e]));for(let e of t){let t=n.get(XJ(e));n.set(XJ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const iY=e=>e.map(e=>({...e,before:e.after,after:e.before}));function aY(e,t){let n=[...e.past,t],r=eY(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...nY(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...oY(e.future,a),...i.below]},n.length-r.length,t)}}function oY(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function sY(e,t){return{past:e.past.slice(0,-1),future:eY([...e.future,t]),...nY(e.savepoint,0,iY(t))}}function cY(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...oY(r,t.at-i.length),...t.below]}function lY(e,t){if(tY(t.after)&&!tY(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!tY(t.after)&&tY(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function uY(e,t){return e.map(e=>e.filter(e=>!t.has(XJ(e)))).filter(e=>e.length>0)}function dY(e){return e.map(fY).join(`, `)}function fY(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function pY(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function mY(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(pY))}function hY(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(pY)&&mY(t.below)}function gY(e){if(typeof e!=`object`||!e)return!1;let t=e;return mY(t.past)&&mY(t.future)&&(t.savepoint===void 0||hY(t.savepoint))}function _Y(e,t){let n=e=>e.kind===`file`||qJ(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 vY(e,t){return{load:()=>{let n;try{n=f.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(gY)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,_Y(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{f.mkdirSync(o.dirname(e),{recursive:!0}),st(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const yY=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function bY(e,t){let n={...e};for(let e of yY)delete n[e];return{...n,CLAUDE_CODE_SESSION_ID:t.sessionId,CLAUDE_PROJECT_DIR:t.projectDir,...t.claudeConfigDir!==void 0&&{CLAUDE_CONFIG_DIR:t.claudeConfigDir}}}const xY=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function SY(e){let t=e=>({kind:`failed`,reason:e});if(!xY(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!xY(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!ZF.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${ZF.join(` or `)}`)}return{kind:`ok`,value:e}}function CY(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const wY=e=>Tq(e,`doctor-marks.json`,{},SY),TY=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},EY=(e,t)=>e.includes(t)?e:[...e,t],DY=e=>Tq(e,`doctor-clicked-terminals.json`,[],TY);var OY=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const kY=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},AY=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),jY=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=AY(e,t);return r===void 0?n:r.projectDir},MY=(e,t)=>AY(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function NY(e){let t=new Map;for(let n of e.split(`
|
|
188
188
|
`)){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*PY(e,t){let n=new Set;for(let r=e.get(t);r!==void 0&&!n.has(r.pid);)n.add(r.pid),yield r,r=e.get(r.ppid)}function FY(e,t){return e.kind===`absent`?F(`none`):e.kind===`failed`?e:t.kind===`failed`?t:F(t.kind===`ok`?`tracked`:`gone`)}function IY(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?L(`HEAD: ${t.reason}`):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const LY={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},RY={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function zY(e,t,n){return Object.hasOwn(t,n)?F(t[n]):L(`${e}: unknown state ${JSON.stringify(n)}`)}const BY={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,tag:`tag`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function VY(e){return Object.keys(BY).flatMap(t=>{let n=e[t];return n?.kind===`failed`?[`git.${BY[t]}: ${n.reason}`]:[]})}function HY(e,t,n){return t.ok?F(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?I:L(UY(e,t))}function UY(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??WY(t.stderr)].filter(Boolean).join(`, `)}`}function WY(e){return e.trim().split(`
|
|
@@ -472,46 +472,46 @@ function run(argv) {
|
|
|
472
472
|
`)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
|
|
473
473
|
`)){let t=PZ(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function YQ(e){let t=qo(e,QF+1);return t.kind===`ok`?F(JQ(t.value.buf,t.value.fromStart)):t}function XQ(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 ZQ={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};async function QQ(e,t){if(Mc(t)===void 0)return{kind:`ok`,value:null};let n=eX(await e.launch({bin:`git`,args:[...$Y],cwd:t,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(n.kind===`failed`)return n;let r=aX(n.value);if(r===null)return{kind:`ok`,value:null};let i=QY(r);if(i===null)return{kind:`ok`,value:null};let a=qY[i],o=ZQ[i],s=o.loginHost(ZY(r)),c=await e.launch({bin:a,args:[...o.args(s)],cwd:t,timeoutMs:2e3,category:`doctor.forge`});return $Q(a,s,o.nonZero,c)}function $Q(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):JY(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:WY(r.stderr)}):{kind:`failed`,reason:UY(e,r)}}function e$(e,t){let n={layers:e.layers,target:t,warnings:e.warning===null?[]:e.warning.split(`
|
|
474
474
|
`)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const t$=e=>MQ(()=>as(e));function n$(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:Zo(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:t$(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 r$(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:await e.probeTmux(t)}}function i$(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:VF(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:BF(t),tmuxClient:t}}}}async function a$(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(Pte(s))return{kind:`bundling`,name:s,version:c};if(!Fte(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 o$(e){switch(e.via){case`link`:return{kind:`arrived`,handler:e.handler,bar:tt};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 s$(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:await t()}}async function c$(e,t,n,r){return{pullRequests:await s$(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:await s$(t.rateLimits,()=>r)}}function l$(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 u$(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=TK(d.config,r,()=>!1),p=await r$(e,t.tmux),m=i$(p,t.terminalEnv),h=[...new Set([...$S(f),...QS(JSON.stringify(d.config))])].join(``),[g,_,v]=await Promise.all([h===``?{kind:`none`}:a$(e,m,t,h).then(e=>({kind:`glyphs`,glyphs:h,terminal:e})),e.daemons(),c$(e,bZ(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:e$(d,n.target),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:v,transcripts:XQ(e,o),claudeSettings:n$({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Zo(Xo(t.claudeConfigDir))},c.kind===`ok`?c.value:[])}}function d$(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;st(e,mo(es(e),t.path,JSON.stringify(t.value),Qa));let r=e=>({...e,sources:t$(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||Br(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 f$=16384;var p$=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;dirWatchesOpened=0;dirWatchesClosed=0;subprocessTotal=0;subprocessInFlight=0;subprocessRefusals=new Map;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;get subprocessRefused(){return this.subprocessRefusals}launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)},onRefused:e=>{this.subprocessRefusals.set(e,(this.subprocessRefusals.get(e)??0)+1)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<f$){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%f$}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,refused:Object.fromEntries(this.subprocessRefused),p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e().snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},fileEvents:{delivery:{kind:`delivering`,unreported:[],missedSince:null},stalls:0,catchUps:0,probes:0,probeFailures:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0,pending:0},journalTurns:{holder:null,heldMs:0,queued:0,gathers:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,dirWatchesActive:0,handlerProbes:[],clients:[],bundle:`/`,sourceDigest:null,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:tt,sourceDigest:e.sourceDigest,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,fileEvents:e.fileEvents,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,journalTurns:e.journalTurns,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors,dirs:{active:e.dirWatchesActive,opened:this.dirWatchesOpened,closed:this.dirWatchesClosed}},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};const m$={connectMs:200,budgetMs:500};async function h$(e){return g$(await _$(),e.includes(`--json`))}function g$(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`daemon-stats: ${on(e)}\n`,code:1};let n=t?JSON.stringify(e.value,null,2)+`
|
|
475
|
-
`:null,r=v$(e.value);return r===null?{stdout:n??
|
|
475
|
+
`:null,r=v$(e.value);return r===null?{stdout:n??E$(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function _$(){return $t(()=>({kind:`stats`}),m$,e=>`stats`in e?e.stats:void 0)}function v$(e,t=y$){let n=p$.referenceSnapshot(),r=b$(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=S$(e.version,e.sourceDigest??null),a=S$(tt,it());return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}const y$=Object.keys(p$.referenceSnapshot());function b$(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!x$(e))return[];if(!x$(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(...b$(e[i],t[i],a)):r.push(a)}return r}function x$(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function S$(e,t){return`${e} [${t===null?`no digest`:et(t)}]`}function C$(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function w$(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function T$(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 E$(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${S$(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${T$(e.uptimeSec)}`),t.push(` rss ${C$(e.rssBytes)}`),t.push(` heapUsed ${C$(e.heapUsedBytes)}`),t.push(` heapTotal ${C$(e.heapTotalBytes)}`),t.push(` external ${C$(e.externalBytes)}`),t.push(` arrayBuffers ${C$(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 ${w$(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 ${w$(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 ${ol(e.fileEvents)}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${C$(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${C$(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 ${C$(e.renderCache.accountedBytes)} / ${C$(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`menuIdle`),t.push(` sessions ${e.menuIdle.sessions}`),t.push(` armed ${e.menuIdle.armed}`),t.push(` pending ${e.menuIdle.pending}`),t.push(``),t.push(`journalTurns`),t.push(` holder ${e.journalTurns.holder??`-`}`),t.push(` held ${e.journalTurns.heldMs}ms`),t.push(` queued ${e.journalTurns.queued}`),t.push(` gathers ${e.journalTurns.gathers}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` refused ${e.watchers.refused}`),t.push(` errors ${e.watchers.errors}`),t.push(` dirs ${e.watchers.dirs.active} open (${e.watchers.dirs.opened} opened, ${e.watchers.dirs.closed} closed)`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let o=Object.entries(e.subprocesses.byCategory),s=Object.entries(e.subprocesses.refused).map(([e,t])=>[`${e} refused`,t]),c=[...o,...s].reduce((e,[t])=>Math.max(e,t.length),13);for(let[n,r]of o){let i=e.subprocesses.p50DurationMs[n],a=e.subprocesses.p99DurationMs[n],o=i!==void 0&&a!==void 0?` (p50 ${i}ms · p99 ${a}ms)`:``;t.push(` ${n.padEnd(c)} ${r}${o}`)}for(let[e,n]of s)t.push(` ${e.padEnd(c)} ${n}`);return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
|
|
476
476
|
`)+`
|
|
477
|
-
`}const
|
|
478
|
-
`).join(` — `));let t=v$(e.value,[`handlerProbes`]);if(t!==null)return
|
|
479
|
-
`);return{inMode:r!==`0`,screen:i}}function Z$(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 Q$(e,t,n){let r=await Y$(e,t,`claude-input.type`,Z$(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 $$(e){return{read:t=>X$(e,t),type:(t,n)=>Q$(e,t,n)}}function e1(e){let t=typeof e==`string`?e===``?`is empty`:e===`.`||e===`..`?`is ${JSON.stringify(e)}, which names a folder, not a session`:/[/\\\0]/.test(e)?`contains a path separator or NUL: ${JSON.stringify(e)}`:Buffer.byteLength(e,`utf8`)>250?`is longer than 250 bytes`:null:`is not a string: ${JSON.stringify(e)??String(e)}`;return t===null?{ok:!0,id:e}:{ok:!1,problem:t}}const t1=e=>({gathers:!1,prepare:async t=>n=>e(t,n)});function n1(e){let t=e1(e);if(!t.ok)throw new Y(`session id ${t.problem}`);return t.id}function r1(e){return XC(()=>decodeURIComponent(e))}const i1=5e3;function a1(e,t,n,r){if(e.reason===`rate-limited`){r(`warn`,`${t} rate-limited: ${e.said}`);return}throw e.reason===`aborted`?new JC(n):Error(`${n} failed (${e.reason}, exit ${e.exitCode??`null`})${e.said===``?``:`: ${e.said}`}`)}async function o1(e,t,n,r){let i=await e.launch({...t,timeoutMs:i1});i.ok||a1({reason:i.reason,exitCode:i.exitCode,said:i.error??i.stderr.trim()},t.category,n,r)}async function s1(e,t,n,r,i){let a=v(o.join(O(),`cc-candybar-handoff-`));try{let s={stdout:`/dev/null`,stderr:o.join(a,`stderr`),status:o.join(a,`status`)},c=e.launchJobSync(t,s);if(!c.ok){a1({reason:c.reason,exitCode:null,said:c.error},t.category,n,r);return}c.release();let l=performance.now()+i;for(;;){let e=Un(c.pid),a=Vn(s.status);if(a!==null){if(a.kind===`exit`&&a.code===0)return;a1(a.kind===`exit`?{reason:`non-zero`,exitCode:a.code,said:b(s.stderr,`utf8`).trim()}:{reason:`timeout`,exitCode:null,said:``},t.category,n,r);return}if(!e)throw Error(`${n} failed (lost): the opener ended with no verdict`);if(performance.now()>=l){r(`info`,`${t.category} handed off at ${i}ms, pid ${c.pid}`);return}await new Promise(e=>setTimeout(e,50))}}finally{S(a,{recursive:!0,force:!0,maxRetries:3})}}function c1(e,t){return t.launch({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`)}const l1=(e,t)=>c1(r1(e),t),u1=new Set([`request`,`feed`]);function d1(e){if(!u1.has(e))throw new Y(`unknown renderer ${JSON.stringify(e)}`);return e}const f1=async(e,t)=>{let[n=``,r=``,i=``]=XC(()=>wa(e)),a=n1(n),o=t.diagnosticCopy(a,d1(r),i);if(o===void 0)throw new Y(`that message is no longer listed in session ${a}'s diagnostics — open ⚠ again and copy from there`);await c1(o,t)},p1=(e,t)=>t.launch({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,r1(e)],category:`click.open`},`open -a "Visual Studio Code"`),m1=async(e,t)=>{let n=n1(r1(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},h1=async(e,t)=>{let[n=``,...r]=XC(()=>wa(e)),i=n1(n),a=sq(j1(t,i));if(r.length===0)throw new Y(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new Y(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new Y(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new Y(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}y1(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.log(`info`,`set-state: ${s} (session=${i})`)},g1=/^-?\d+$/;function _1(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const v1=async(e,t)=>{let[n=``,r=``,i=``]=XC(()=>wa(e)),a=n1(n);if(!r)throw new Y(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!g1.test(i))throw new Y(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=j1(t,a),c=sq(s),l=c.rangeParamsFor(r);if(!l)throw new Y(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&g1.test(u)?b1(l,parseInt(u,10)):x1(`step-state`,r,l,uq(s,e=>t.sessionState.get(a,e),r)),f=_1(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new Y(`step-state: ${p.reason}`);y1(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.log(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function y1(e,t,n,r){let i=r.filter(e=>e.key.startsWith(iF));if(i.length===0)return;let a=BK(j1(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new Y(`${n}: refused — ${a.join(`; `)}`)}function b1(e,t){return Math.max(e.min,Math.min(e.max,t))}function x1(e,t,n,r){if(r===null)return n.min;if(!g1.test(r))throw new Y(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return b1(n,parseInt(r,10))}const S1=`render-origin`;function C1(e,t,n){let r=t.get(n,m0);return r===null?e:{...e,target:{source:`pick`,path:r}}}function w1({projectDir:e,cwd:t,target:n}){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path??null,source:n.source})}function T1(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function E1(e){let t;try{t=JSON.parse(e)}catch{throw new Y(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new Y(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i,source:a}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new Y(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,target:T1(a,i)}}function D1(e,t){let n=k1(e,t);if(n===null)throw new Y(`session ${t} has not rendered yet — no config to act on`);return n}function O1(e,t){let n=e.sessionState.get(t,S1);return n===null?null:E1(n)}function k1(e,t){let n=O1(e,t);return n===null?null:C1(n,e.sessionState,t)}function A1(e,t,n){let r=k1(e,t);if(r===null)return;let{path:i}=P1(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function j1(e,t){return e.configFor(D1(e,t))}function M1(e,t){let n=O1(e,t);if(n===null)return null;let r=()=>e.lanes.of(C1(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function N1(e,t){let n=k1(e,t);return n===null?Nq:Lq(e.configFor(n))}function P1(e){return NG(kq().read(),e.projectDir,e.cwd,e.target.path)}function F1(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.log}}const I1=async(e,t)=>{let[n=``,r=``,i=``]=XC(()=>wa(e)),a=n1(n),o=D1(t,a),s=t.configFor(o),c=uB(s);if(!r)throw new Y(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new Y(`set-config: ${l.reason}`);let u=P1(o),d=RK(s,e=>t.sessionState.get(a,e),r);kJ(F1(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.log(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},L1=async(e,t)=>{let[n=``,r=``,i=``]=XC(()=>wa(e)),a=n1(n);if(!r)throw new Y(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!g1.test(i))throw new Y(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=D1(t,a),c=t.configFor(s),l=uB(c),u=l.rangeParamsFor(r);if(!u)throw new Y(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=P1(s),f=RK(c,e=>t.sessionState.get(a,e),r),p=OJ(d.path,f.key),m=typeof p==`number`?b1(u,p):x1(`step-config`,r,u,fB(f.globals,r)),h=_1(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new Y(`step-config: ${g.reason}`);kJ(F1(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.log(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},R1=async(e,t)=>{let[n=``]=XC(()=>wa(e)),r=n1(n),i=D1(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=IK(a,o),c=zK(a,o);if(s.length+c.length===0){t.log(`info`,`save: nothing unsaved (session=${r})`);return}let l=sq(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new Y(`save: ${t.reason}`);return[e.target,t.value]});B1(`save`,l,c);let d=P1(i);AJ(F1(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.log(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(z1)].join(` `)} → ${d.path} (session=${r})`)},z1=e=>`${e.preset}/${e.id}.settings.${e.setting}=${bb(e.value)}`;function B1(e,t,n){for(let r of n){let n=t.validate(r.key,bb(r.value));if(!n.ok)throw new Y(`${e}: ${n.reason}`)}}const V1=async(e,t)=>{let[n=``]=XC(()=>wa(e)),r=n1(n),i=D1(t,r),a=t.configFor(i),o=UK(a,e=>t.sessionState.get(r,e)),s=sq(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new Y(`save-preset: ${t.reason}`);return[e.configKey,t.value]});B1(`save-preset`,s,o.placements);let l=P1(i),u=LJ(F1(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Xx.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Jx.preset.sessionKey,u),t.log(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(z1)].join(` `)} → ${l.path} (session=${r})`)},H1=async(e,t)=>{let[n=``]=XC(()=>wa(e)),r=n1(n),i=D1(t,r),a=GK(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new Y(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=P1(i);RJ(F1(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(IK(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=Vx.map(e=>Jx[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.log(`info`,`save-theme-default: ${a.theme} ${Vx.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},U1=async(e,t)=>{let[n=``,r=``]=XC(()=>wa(e)),i=n1(n);if(!r)throw new Y(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=D1(t,i),o=P1(a);zJ(F1(t,i),o,r),t.reloadConfig(a);let s=Jx.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.log(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},W1=async(e,t)=>{let[n=``,...r]=XC(()=>wa(e)),i=n1(n),a=D1(t,i),o=uB(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new Y(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=P1(a),l=r.map(KK),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);PJ(F1(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.log(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function G1(e,t){let n=(e,t)=>[...nb(Ow(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Tw(t.presets).flatMap(e=>n(t,e).map(t=>aF(XN(e),Qy(t)))));return Tw(e.presets).flatMap(t=>n(e,t).map(e=>({member:aF(XN(t),Qy(e)),node:e})).filter(({member:e})=>!r.has(e)))}function K1(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[tF]:[]])}const q1=async(e,t)=>{let[n=``,r=``,i=``]=XC(()=>wa(e)),a=n1(n),o=D1(t,a),s=t.configFor(o),c=uB(s);if(!r)throw new Y(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new Y(`apply-layout-op: ${l.reason}`);let u=Xz(l.value);if(u===null)throw new Y(`apply-layout-op: "${l.value}" is not a layout op token`);let d=P1(o),f=BJ(F1(t,a),d,r,u);t.reloadConfig(o);let p=K1(G1(s,t.configFor(o)),t.sessionState.get(a,tF)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.log(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},J1=async(e,t)=>{let[n=``]=XC(()=>wa(e)),r=n1(n);t.journal.commit();let i=t.history.undo(r);t.journal.wrote(),A1(t,r,i),t.log(`info`,`undo: restored ${dY(i)} (session=${r})`)},Y1=async(e,t)=>{let n=n1(r1(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,sq(j1(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.log(`info`,`back: ${a} discarded=${i} (session=${n})`)},X1=async(e,t)=>{let n=n1(r1(e));t.journal.commit(),t.journal.wrote();let r=t.history.rewind(n);A1(t,n,r),t.log(`info`,`rewind: put back ${dY(r)||`nothing`} as edit mode found it (session=${n})`)},Z1=async(e,t)=>{let[n=``]=XC(()=>wa(e)),r=n1(n);t.journal.commit();let i=t.history.redo(r);t.journal.wrote(),A1(t,r,i),t.log(`info`,`redo: re-applied ${dY(i)} (session=${r})`)},Q1=async(e,t)=>{n1(r1(e)),await t.applyUpdate()},$1=`client-hints`;function e0(e,t){let n=e.sessionState.get(t,$1);if(n===null)throw new Y(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new Y(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new Y(`client hints record is not an object: ${n}`);return Lt(r)}function t0(e,t,n){let r=GI(n);e.sessionState.setBatch(t,cL(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${YI(n.config)} ${oL(n.nerdFont,n.marks)} ${XI(n.terminal,n.clicked)} ${ZI(n.terminal,n.width)} ${QI(n.install)} ${eL(n.daemon)} ${tL(n.data)} ${aL(n.transcripts)} ${nL(n.frames,n.claudeSettings)} ${iL(n.claudeSettings.origin.sources)} (session=${t})`)}async function n0(e,t,n,r){let i={kind:`clicked`,sessionId:t,via:e.arrival.via},a=e.clients.ofSession(t,e.now()),o;try{o=await u$({...n,loadConfig:()=>r},e0(e,t),D1(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:a.map(e=>e.rateLimits)},{kind:`ok`,value:a.map(e=>e.transcript)},i,{kind:`ok`,value:MY(i,a)},l$(t,a),IQ(e.doctorStores))}catch(e){throw e instanceof OY?new Y(e.message):e}let s={facts:o,install:PQ(n.install,e.bundle,a.map(e=>e.client)),current:async e=>{let i=n.loadConfig(D1(e,t));return i.config===r.config&&i.error===r.error&&i.warning===r.warning?s:n0(e,t,n,i)}};return s}const r0=(e,t)=>{let n=LQ(e.doctor);return n0(e,t,n,n.loadConfig(D1(e,t)))};async function i0(e,t,n){let{facts:r,install:i}=await e.gather(n.current),a=IQ(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:o$(e.arrival),install:i,clicked:a0(e,o)}}function a0(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?HF(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>EY(e,r))}catch(t){return e.log(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const o0={gathers:!0,prepare:async(e,t)=>{let n=n1(r1(e)),r=await r0(t,n);return async e=>t0(e,n,await i0(e,n,r))}},s0=async(e,t)=>{let n=A$(r1(e));if(n===null)throw new Y(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new Y(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.log(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},c0={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``]=XC(()=>wa(e)),i=n1(n),a=KI(r);if(a===void 0)throw new Y(`doctor-fix: unknown check "${r}"`);let o=await r0(t,i);return async e=>{let t=await i0(e,i,o),n=a.probe(t);if(n.ok||n.fix===void 0)throw new Y(`doctor-fix: ${a.label} — ${n.ok?`nothing to fix`:n.reason}`);let r=d$(e.doctorStores,n.fix,t);if(r.kind===`failed`)throw new Y(`doctor-fix: ${a.label} — ${r.reason}`);e.log(`info`,`doctor-fix: ${a.name} → ${eI(n.fix)} (session=${i})`),t0(e,i,r.value)}}},l0={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``,i=``]=XC(()=>wa(e)),a=n1(n),o=KI(r);if(o===void 0)throw new Y(`doctor-mark: unknown check "${r}"`);if(!ZF.includes(i))throw new Y(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${ZF.join(` or `)}`);let s=await r0(t,a);return async e=>{let t=await i0(e,a,s),n=o.probe(t);if(n.ok||n.sighting===void 0)throw new Y(`doctor-mark: ${o.label} — ${n.ok?`nothing to mark`:`shows nothing to look at`}`);let r=[o.name,n.sighting.id,i],c=e.doctorStores.marks.update(e=>CY(e,...r));if(c.kind===`failed`)throw new Y(`doctor-mark: ${c.reason}`);e.log(`info`,`doctor-mark: ${o.name} ${i} on ${n.sighting.id} (session=${a})`),t0(e,a,{...t,marks:c})}}},u0=async(e,t)=>{let[n=``,r=``]=XC(()=>wa(e)),i=n1(n),a=Object.values(t.configFor(D1(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new Y(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=await t.typing(e0(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.log(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new Y(`${r} was not typed: ${s.reason}`);t.log(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)};function d0([e=``,t=``,n=``,r=``],i){let a=n1(e),o=D1(i,a),s=i.configFor(o).actions,c=Object.hasOwn(s,t)?s[t]:void 0;if(c===void 0||!(`run`in c))throw new Y(`"${t}" is not a run action this session's config declares`);let l=Vw(c);if(!i.links.verify({sessionId:a,action:t,declaration:l,evaluated:n},r))throw new Y(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let u;try{u=JSON.parse(n)}catch{throw new Y(`run ${t}: what the link carries is not JSON`)}let[d,...f]=u.run;if(d===void 0||d===``)throw new Y(`run ${t}: the program evaluated to nothing`);let p=i.sourcesFor(o);return{sessionId:a,action:t,argv:[d,...f],env:{...bY(process.env,{sessionId:a,projectDir:o.projectDir,claudeConfigDir:e0(i,a).claudeConfigDir}),...u.env},cwd:c.cwd,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const f0=async(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=XC(()=>wa(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=d0(i,t)}catch(e){throw e instanceof Y&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)},p0=async(e,t)=>{let[n=``,r=``,i=``,a=``]=XC(()=>wa(e)),o=n1(n),s=i;if(!t.links.verify(jq(o,r,s),a))throw new Y(`the answer's signature does not match what it carries: it was not drawn by this daemon`);let c=Aq(kq(),r,s);if(c.kind===`failed`)throw Error(`${r} was not ${s}: ${c.reason}`);t.journal.wrote();let{superseded:l,absent:u,unchecked:d}=c.value;t.log(`info`,`repo-config: ${r} ${s} superseded=${l.join(`,`)||`-`} absent=${u.join(`,`)||`-`} unchecked=${d.length===0?`-`:JSON.stringify(d)} (session=${o})`),t.reloadConfig(D1(t,o))},m0=`config-override`,h0=new Map([[Ki,t1(l1)],[Yi,t1(async(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new Y(`load-config: expected <sessionId>/<path> (missing separator)`);let r=n1(XC(()=>decodeURIComponent(e.slice(0,n)))),i=XC(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new Y(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new Y(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,m0),t.log(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,m0,i),t.log(`info`,`load-config: ${i} (session=${r})`))})],[qi,t1(p1)],[Wi,t1(h1)],[Gi,t1(v1)],[Xi,t1(I1)],[Zi,t1(L1)],[na,t1(W1)],[Qi,t1(R1)],[$i,t1(V1)],[ea,t1(H1)],[ta,t1(U1)],[ra,t1(q1)],[ia,t1(J1)],[aa,t1(Z1)],[oa,t1(Y1)],[sa,t1(X1)],[Ji,t1(m1)],[ca,t1(Q1)],[la,o0],[ua,c0],[da,l0],[fa,t1(s0)],[pa,t1(u0)],[`run`,t1(f0)],[ma,t1(p0)],[ha,t1(f1)]]),g0=new Set([Wi,Gi,Xi,Zi,na,Qi,$i,ea,ta,ra,ia,aa,oa,sa,Ji,ca,la,ua,da,pa,`run`,ma,Yi,ha]);function _0(e,t){return v0(e===`dispatch`?Da(t):[{verb:e,value:t}])}function v0(e){let t=e.find(e=>g0.has(e.verb)),n=t===void 0?``:XC(()=>Ta(t.value));return n===``?null:e1(n)}const y0=(e,t,n)=>n.journalTurns.gathering(()=>e.prepare(t,n)).catch(e=>()=>Promise.reject(e));async function b0(e,t,n,r){await(r??await n.gather(n=>e.prepare(t,n)))(n)}async function x0(e,t){let[n]=ka(Da(e)),r=n===void 0?void 0:h0.get(n.verb);return r?.gathers?y0(r,n.value,t):void 0}async function S0(e,t,n){let r=[],i=!1,a=Da(e),o=v0(a);for(let[e,{verb:o,value:s}]of ka(a).entries()){let a=h0.get(o);if(!a){r.push(`unknown effect verb "${o}"`);continue}try{await b0(a,s,t,e===0?n:void 0)}catch(e){if(e instanceof JC)throw r.length>0&&t.log(`warn`,`dispatch: ${r.join(`; `)}`),e;e instanceof Y||(i=!0),r.push(`${o}: ${e instanceof Error?e.message:String(e)}`)}}if(r.length>0){o?.ok&&Ec(t.sessionState,o.id,r.join(`
|
|
480
|
-
`),t.now());let e=`dispatch: ${r.join(`; `)}`;throw i?Error(e):new Y(e)}}function C0(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}async function w0(e,t,n,r){let i=e===null?null:M1(t,e),a=t.history.begin(),o=t.navigation.begin(a.sessionState),s=n.holds(()=>{let e=[];for(let t of[o,a])try{t.commit()}catch(t){e.push(t)}C0(e)}),c=[],l=e=>Bq(e,e=>N1(t,e),e=>t.log(`info`,e)),u={...t,sessionState:l(a.sessionState),journal:a,navigating:l(o.sessionState)},d={launch:(e,r)=>n.landed(o1(t.launcher,e,r,t.log)),typing:(e,r)=>n.landed(J$(t.claudeInput,e,r)),applyUpdate:()=>n.landed(t.applyUpdate())};try{await r({...u,...d,gather:e=>n.landed(e(u))})}catch(e){c.push(e)}let f=!0;try{f=s()}catch(e){c.push(e)}if(f&&i!==null)try{let e=i.read();t.lanes.clicked(i.sessionId,a.written()?i.before:e,e)}catch(e){c.push(e)}if(f&&e!==null)try{let n=k1(t,e);n!==null&&t.views.follow(e,n)}catch(e){c.push(e)}C0(c)}function T0(e,t,n){return async(r,i)=>{let a=_0(e,r),o=a?.ok?a.id:null;return i.journalTurns.click(e,o,{placed:i.placeWaited,waited:i.turnWaited,gone:i.clientGone,gathered:i.gatherTook},()=>t(r,i),(e,t)=>w0(o,i,t,async t=>{try{await n(r,t,e)}finally{o!==null&&i.clickLanded(o)}}))}}const E0=new Map([...[...h0].map(([e,t])=>[e,T0(e,async(e,n)=>t.gathers?y0(t,e,n):void 0,(e,n,r)=>b0(t,e,n,r))]),[Ui,T0(Ui,x0,S0)],[fa,s0]]);Object.freeze([...E0.keys()]);function D0(e,t,n){return n.journalTurns.take(`menu-idle`,{waited:t=>n.log(`info`,`menu-idle: waited=${t}ms (session=${e})`),gone:()=>!1},r=>w0(e,n,r,async n=>{if(!t.stillIdle()){n.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}t.closed();let r=zq(N1(n,e),t=>n.navigating.get(e,t));n.navigating.setBatch(e,r.map(({key:e})=>({key:e,value:N}))),n.log(`info`,`menu-idle: closed=${r.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)}))}function O0(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const k0={kind:`hidden`},A0={kind:`shown`};function j0(e,t){try{return O0(e,t)?A0:k0}catch(e){let t=LT(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function M0(e,t){let n=K.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function N0(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function P0({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function F0({text:e,placement:t,lead:n,trail:r}){return{text:I0(e),placement:t,...n!==void 0&&{lead:I0(n)},...r!==void 0&&{trail:I0(r)}}}function I0(e){let t=e.blankCopy(e.plain);t.style=pS(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(pS(i).clearMetaAndLinks(),n,r);return t}function L0(e){let t=P0(e);if(t.length===1)return e.text;let n=M0(t);return n.style=e.text.style,n}function R0(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=M0(e,a).pad(o),d=new K(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:M0([d,...c],a)},...l.length>0&&{trail:M0([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(N0(u,n,p),[{text:u,...f}])}function z0(e,t,n){let r=`x`.repeat(Math.min(n,t)).replace(/x$/,` `),i=r+e,a=[],o=0;return tC(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 B0(e,t){if(e.length===0)return 0;let{lines:n}=nC(e.map(({owner:e})=>e),t),r=z(VS(n[n.length-1]));return Math.max(0,r-YS(t)+XS(t))}function V0(e,t,n){if(e.cellLength<=t)return!0;let{lines:r}=nC([e],{...n,width:1/0});return z(VS(r.flat()))<=n.width}function H0(e,t,n,r){if(V0(e.owner,t,r))return[e];let i=e.owner.copy().expandTabs(),a=B0(n,r);return i.divide(z0(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 U0(e,t){let n=Math.max(2,eC(t)-YS(t)-t.padding);return W0(e,t).reduce((e,r)=>[...e,...H0(r,n,e,t)],[])}function W0(e,t){let n=()=>e.map(e=>({owner:L0(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=nC(e.map(L0),t).lines;if(i.length>1)return n();let a=Math.max(0,t.width-z(VS(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];N0(c,c.cellLength+a,n)}),n()}function G0(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=K0(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:pS(a.style)};if(e.style.link){i();let r=K0([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function K0(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>q0(e.frag,n?n.add(e.style):e.style)),i=K.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function q0(e,t){let n=e.copy();return n.style=t,n}function J0(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 Y0(e,t){let{look:n}=J0(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function X0(e,t){let{layout:n}=J0(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function Z0(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 Q0(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,$0(e,t,o,n,r,i));return i}function $0(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=Lw(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=$x.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=Lw(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=Lw(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:n2(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:n2(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:Vw(n),argv:n.run.map(n=>n2(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,n2(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:n2(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 e2(e){return e.kind===`do`?e2(e.head):e}function t2(e){switch(e2(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 n2(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function r2(e,t){return e.has(t)?NT(e.read(t)):``}function i2(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function a2(e,t,n,r){let i=new K(e,{style:U.combine([r,new U({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function o2(e,t,n=!1){let r=new U({link:t,bold:n?!0:void 0}),i=new K(e.plain,{style:U.combine([pS(e.style),r])});for(let t of e.spans)i.stylize(U.combine([pS(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function s2(e,t){return Math.max(e.members.indexOf(r2(t,e.stateVar)),0)}function c2(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=r2(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=r2(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=r2(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(s2(e,r)+1)%e.members.length];return{effects:[{verb:Wi,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Gi,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Ki,args:[i2(e.text,cN(r))]}],active:!1};case`open`:return{effects:[{verb:qi,args:[i2(e.target,cN(r))]}],active:!1};case`persist-literal`:{let t=r2(r,e.stateVar);return{effects:[{verb:Xi,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=r2(r,e.stateVar);return{effects:[{verb:Xi,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(s2(e,r)+1)%e.members.length];return{effects:[{verb:Xi,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Zi,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:na,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ia,args:[i]}],active:!1};case`redo`:return{effects:[{verb:aa,args:[i]}],active:!1};case`back`:return{effects:[{verb:oa,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:sa,args:[i]}],active:!1};case`save`:return{effects:[{verb:Qi,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:$i,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:ea,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:ta,args:[i,i2(e.name,cN(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:la,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:ua,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:da,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:pa,args:[i,e.line]}],active:!1};case`run`:{let t=cN(r),n=JSON.stringify({run:e.argv.map(e=>i2(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,i2(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:ra,args:[i,e.key,Yz(e.op)]}],active:!1};case`do`:{let o=c2(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>c2(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:ra,args:[i,e.key,Yz(r)]}],active:!1}}}}function l2(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:xi(`action "${e}"`,n,t.members.length,s2(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 u2(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=J0(n,`action "${e}"`).store,{display:a,boundValue:o}=l2(e,e2(r),t,i),s=r2(i,`session.id`),{effects:c,active:l}=c2(r,a.plain,o,i,s,n.signer);return o2(a,Ea(c),l)}function d2(e){return{action:{fn:(t,...n)=>u2(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function f2(e,t){return a2(`✕`,Ea([{verb:Wi,args:[r2(e,`session.id`),t,N]}]),!1)}function p2(e,t,n){return new U({bgcolor:H.fromRgba(t),color:H.fromRgba(Vv(e,t,n))})}function m2({tint:e,text:t}){return new U({bgcolor:H.fromRgba(e),color:H.fromRgba(t)})}function h2(e,t,n){return new U({color:H.fromRgba(cd(e.get(`warning`),t,Bv,n))})}function g2(e,t,n){return U.combine([p2(e,t,n),h2(e,t,n)])}function _2(e,t,n){return m2($v(e.palette,e.disclosure,t,n))}function v2(e){let t=H.fromRgba(e.get(`background`)),n=K.fromFragments(U_.map(n=>new K(`▀`,{style:new U({color:H.fromRgba(e.get(n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const y2=(e,t)=>{let n=typeof e==`string`?new K(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},b2=e=>new U({bold:e});function x2(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>y2(a,U.combine([_2(e,{...n,distribution:t},i),b2(o)]));let o=p2(e.palette,a,i);return(e,t,i,a)=>S2(i,U.combine([o,b2(a)]),r(t,n))}const S2=(e,t,n)=>y2(K.fromFragments([y2(e,t),y2(` `,t),v2(n)]));function C2(e,t,n,r){return t===void 0?y2(r):S2(r,void 0,t(n,e))}function w2(e,t,n,r,i){let a=p2(e.palette,i,r);return(e,r,i,o)=>y2(K.fromFragments([y2(o?`[`:` `,a),v2(n(r,t)),y2(o?`]`:` `,a)]))}function T2(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=>E2(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function E2(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function D2(e,t){return new K(e).truncate(t,{marker:`…`}).plain}function O2(e){return{current:null,drawnAt:e}}function k2(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 A2(e,t,n){return M2(e,()=>n(k2(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function j2(e,t){return M2(e,()=>(e.current=null,t()))}function M2(e,t){let n=e.current;try{return t()}finally{e.current=n}}function N2(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 P2(e){return new K(e).cellLength}function F2(e){let{width:t,chromeCols:n,padding:r}=J0(e,`a row fit`);return Math.max(1,t-n-2*r)}function I2(e){let{padding:t,seamCols:n}=J0(e,`a row fit`);return Math.max(1,F2(e)-(P2(`✕`)+2*t+n))}function L2(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 R2(e,t,n){let r=P2(`←`)+1+P2(`→`)+1,i=L2(e,t,n);return(i.length>1?L2(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function z2(e){let t=[];for(let n of e)t.length>0&&t.push(new K(` `)),t.push(n);let n=K.fromFragments(t);return n.overflow=`ignore`,n.end=``,n}function B2(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 V2(e,t,n){let r=e.compiled.get(t),i=r&&e2(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 H2(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=J0(a,`picker`).store,d=r2(u,`session.id`),f=`stateVar`in t?r2(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`?I2(a):F2(a):1/0,h=(r.kind===`led`?0:P2(`✕`)+1)+c.reduce((e,t)=>e+P2(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?R2(v.map(e=>e.cellLength),m,h):T2(g.entries,g.groups,i),b=parseInt(r2(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,ee=y[C]??[],te=e=>Ea([{verb:Wi,args:[d,n.key,String(e)]}]),w=r.kind===`led`?[]:[{verb:Wi,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],ne=r.kind===`own`&&r.onPick?w:[],T=e=>Ea([...c2(l,e,e,u,d,a.signer).effects,...ne]),re=(e,n)=>o2(e,T(t.options[n])),E=r.kind===`led`?[]:[a2(`✕`,Ea(w),!1,s)];E.push(...c.map(({glyph:e,option:r})=>a2(e,Ea([...c2(l,r,r,u,d,a.signer).effects,{verb:Wi,args:[d,n.key,String(x(t.options.indexOf(r)))]}]),!1))),C>0&&E.push(a2(`←`,te(C-1),!1));let D=C<y.length-1?[a2(`→`,te(C+1),!1)]:[];if(g===void 0){let e=ee.flatMap(e=>e.indices);return[z2([...E,...e.map(e=>re(v[e],e)),...D])]}let ie=new U({bold:!0}),O=y.length>1?` ${C+1}/${y.length}`:``,ae=ee.length===1?[new K(`${ee[0].label}${O}`,{style:ie})]:[],oe=[z2([...E,...ae,...D])];for(let e of ee){ee.length>1&&oe.push(z2([new K(e.label,{style:ie})]));let n=Math.max(...e.indices.map(e=>P2(_(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:aS(i),o=` `.repeat(n-P2(e)+2),s=a===void 0?e:`${e}${o}${a}`;oe.push(z2([re(p(r,D2(s,m)),r)]))}}return oe}function U2(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{RM(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=B2(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=V2(e,n,`picker`),u=N2(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=>H2(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,x2(u,Tv(void 0),Y0(e,`{{ picker }}`),l.paletteOf,d,t),h2(u.palette,t,d)),p=Zv(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 W2(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function G2(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=J0(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=r2(a,`session.id`),{options:c}=t;if(c.length===0)return z2([]);let l=W2(c,r2(a,t.stateVar)),u=e=>c[l(e)],d=e=>Ea(c2(o,u(e),u(e),a,s,i.signer).effects);return z2([a2(`◀`,d(-1),!1),o2(C2(Y0(i,`{{ carousel }}`),t.paletteOf,u(0),r),Ea(c2(i.compiled.get(n),u(0),void 0,a,s,i.signer).effects)),a2(`▶`,d(1),!1)])}function K2(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(t2(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 G2(t,V2(e,t,`carousel`),n,r,e)},argTypes:[`string`,`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}function q2(e,t,n){let r=V2(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 J2(e,t,n){let r=Math.imul(e^e>>>16,73244475);return r=Math.imul(r^r>>>16,73244475),r^=r>>>16,(n+1+(r>>>0)%Math.max(t-1,1))%t}function Y2(e,t,n,r){let i=q2(e,t,n),a=r??r2(J0(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,Y0(e,`{{ ${n} }}`))}function X2(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(RM(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return v2(Y2(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function Z2(e,t,n){return{swatches:{fn:(r,i)=>{let a=q2(e,r,`swatches`),o=B2(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=N2(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]=H2(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,w2(s,Y0(e,`{{ swatches }}`),a.paletteOf,c,s.bg),h2(s.palette,s.bg,c),u===0?[]:(()=>{let t=W2(l,r2(J0(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[J2(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const Q2=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function $2(e,t,n,r){let i=Zv(e,n,r),a=(t,n)=>({text:t,colour:n,ink:Vv(e,n,r)});return[[dv(e,t,r).map((n,i)=>{let a=zv(e,n);return{text:Q2[i%Q2.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 e4(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new K(` ${e} `,{style:m2({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new K(e)),r.push(a)}return r}function t4(e,t,n,r,i){let a=$2(e,t,n,r).map(e=>e4(e,i)),o=K.fromFragments(a.flatMap((e,t)=>t===0?e:[new K(`
|
|
481
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}function
|
|
482
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}const
|
|
477
|
+
`}const D$=e=>({kind:`ok`,value:e}),O$=e=>({kind:`failed`,reason:e});var k$=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const A$=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function j$(e){return A$.test(e)?e:null}function M$(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return D$(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return D$({app:n,missing:O$(`its script could not be read (${r.reason})`)});let i=ks(r.value);return D$({app:n,missing:i===null?O$("its script is not one `cc-candybar install` wrote"):D$([i.node,i.script].filter(t=>!e.exists(t)))})}async function N$(e,t){let n=e.now()+5e3;for(;e.now()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,handler:r.handler,bar:n.value.version}}return null}async function P$(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${Hi}://${fa}/${n}`);return(r===null?await N$(e,n):null)??{kind:`lost`,unopened:r,opener:M$(e)}}function F$(e,t,n,r){let i=e.launchSync({bin:n,args:[...r],category:t,timeoutMs:5e3});return i.ok?D$(i.stdout):O$(i.stderr.trim()||i.error||i.reason)}const I$=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${Hi}://probe"));u.isNil() ? "" : u.path.js`;async function L$(){let e=await _$();if(e.kind!==`ok`)return O$(on(e).split(`
|
|
478
|
+
`).join(` — `));let t=v$(e.value,[`handlerProbes`]);if(t!==null)return O$(t);let{version:n,handlerProbes:r}=e.value;return D$({version:n,arrivals:r})}function R$(e){return{platform:process.platform,sockets:{own:_t(),handler:vt()},now:Date.now,nonce:re,daemon:L$,open:t=>{let n=F$(e,`doctor.open`,`/usr/bin/open`,[`-g`,t]);return n.kind===`ok`?null:n.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let t=F$(e,`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,I$]);if(t.kind===`failed`)return t;let n=t.value.trim();return D$(n===``?null:n)},script:t=>F$(e,`doctor.osadecompile`,`/usr/bin/osadecompile`,[As(t)]),exists:f.existsSync}}const z$=/^─{20,}/,B$=/^❯(\s|$)/,V$=/›\s*stashed$/;function H$(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>z$.test(e)?[t]:[]).at(-2);return n===void 0||!B$.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function U$(e){if(e.inMode)return{kind:`in-mode`};let t=H$(e);return t===null?{kind:`no-prompt`}:V$.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function W$(e){return/^❯\s*\S/u.test(H$(e)?.prompt??``)}const G$=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function K$(e){return e.screen.some(e=>G$.test(e))}const q$={"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 J$(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 Y$(e,t,n){let r=J$(t);if(r.kind===`refused`)return r;let i=r.hint,a=U$(await e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:q$[a.kind]};let o=await e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}async function X$(e,t,n,r,i){let a=await _c(e,t,n,r,i);if(a.kind===`failed`)throw Error(a.reason);return a}async function Z$(e,t){let n=await X$(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(`
|
|
479
|
+
`);return{inMode:r!==`0`,screen:i}}function Q$(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 $$(e,t,n){let r=await X$(e,t,`claude-input.type`,Q$(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 e1(e){return{read:t=>Z$(e,t),type:(t,n)=>$$(e,t,n)}}function t1(e){let t=typeof e==`string`?e===``?`is empty`:e===`.`||e===`..`?`is ${JSON.stringify(e)}, which names a folder, not a session`:/[/\\\0]/.test(e)?`contains a path separator or NUL: ${JSON.stringify(e)}`:Buffer.byteLength(e,`utf8`)>250?`is longer than 250 bytes`:null:`is not a string: ${JSON.stringify(e)??String(e)}`;return t===null?{ok:!0,id:e}:{ok:!1,problem:t}}const n1=e=>({gathers:!1,prepare:async t=>n=>e(t,n)});function r1(e){let t=t1(e);if(!t.ok)throw new Y(`session id ${t.problem}`);return t.id}function i1(e){return XC(()=>decodeURIComponent(e))}const a1=5e3;function o1(e,t,n,r){if(e.reason===`rate-limited`){r(`warn`,`${t} rate-limited: ${e.said}`);return}throw e.reason===`aborted`?new JC(n):Error(`${n} failed (${e.reason}, exit ${e.exitCode??`null`})${e.said===``?``:`: ${e.said}`}`)}async function s1(e,t,n,r){let i=await e.launch({...t,timeoutMs:a1});i.ok||o1({reason:i.reason,exitCode:i.exitCode,said:i.error??i.stderr.trim()},t.category,n,r)}async function c1(e,t,n,r,i){let a=v(o.join(O(),`cc-candybar-handoff-`));try{let s={stdout:`/dev/null`,stderr:o.join(a,`stderr`),status:o.join(a,`status`)},c=e.launchJobSync(t,s);if(!c.ok){o1({reason:c.reason,exitCode:null,said:c.error},t.category,n,r);return}c.release();let l=performance.now()+i;for(;;){let e=Un(c.pid),a=Vn(s.status);if(a!==null){if(a.kind===`exit`&&a.code===0)return;o1(a.kind===`exit`?{reason:`non-zero`,exitCode:a.code,said:b(s.stderr,`utf8`).trim()}:{reason:`timeout`,exitCode:null,said:``},t.category,n,r);return}if(!e)throw Error(`${n} failed (lost): the opener ended with no verdict`);if(performance.now()>=l){r(`info`,`${t.category} handed off at ${i}ms, pid ${c.pid}`);return}await new Promise(e=>setTimeout(e,50))}}finally{S(a,{recursive:!0,force:!0,maxRetries:3})}}function l1(e,t){return t.launch({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`)}const u1=(e,t)=>l1(i1(e),t),d1=new Set([`request`,`feed`]);function f1(e){if(!d1.has(e))throw new Y(`unknown renderer ${JSON.stringify(e)}`);return e}const p1=async(e,t)=>{let[n=``,r=``,i=``]=XC(()=>wa(e)),a=r1(n),o=t.diagnosticCopy(a,f1(r),i);if(o===void 0)throw new Y(`that message is no longer listed in session ${a}'s diagnostics — open ⚠ again and copy from there`);await l1(o,t)},m1=(e,t)=>t.launch({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,i1(e)],category:`click.open`},`open -a "Visual Studio Code"`),h1=async(e,t)=>{let n=r1(i1(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},g1=async(e,t)=>{let[n=``,...r]=XC(()=>wa(e)),i=r1(n),a=sq(M1(t,i));if(r.length===0)throw new Y(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new Y(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new Y(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new Y(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}b1(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.log(`info`,`set-state: ${s} (session=${i})`)},_1=/^-?\d+$/;function v1(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const y1=async(e,t)=>{let[n=``,r=``,i=``]=XC(()=>wa(e)),a=r1(n);if(!r)throw new Y(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!_1.test(i))throw new Y(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=M1(t,a),c=sq(s),l=c.rangeParamsFor(r);if(!l)throw new Y(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&_1.test(u)?x1(l,parseInt(u,10)):S1(`step-state`,r,l,uq(s,e=>t.sessionState.get(a,e),r)),f=v1(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new Y(`step-state: ${p.reason}`);b1(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.log(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function b1(e,t,n,r){let i=r.filter(e=>e.key.startsWith(iF));if(i.length===0)return;let a=BK(M1(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new Y(`${n}: refused — ${a.join(`; `)}`)}function x1(e,t){return Math.max(e.min,Math.min(e.max,t))}function S1(e,t,n,r){if(r===null)return n.min;if(!_1.test(r))throw new Y(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return x1(n,parseInt(r,10))}const C1=`render-origin`;function w1(e,t,n){let r=t.get(n,h0);return r===null?e:{...e,target:{source:`pick`,path:r}}}function T1({projectDir:e,cwd:t,target:n}){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path??null,source:n.source})}function E1(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function D1(e){let t;try{t=JSON.parse(e)}catch{throw new Y(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new Y(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i,source:a}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new Y(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,target:E1(a,i)}}function O1(e,t){let n=A1(e,t);if(n===null)throw new Y(`session ${t} has not rendered yet — no config to act on`);return n}function k1(e,t){let n=e.sessionState.get(t,C1);return n===null?null:D1(n)}function A1(e,t){let n=k1(e,t);return n===null?null:w1(n,e.sessionState,t)}function j1(e,t,n){let r=A1(e,t);if(r===null)return;let{path:i}=F1(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function M1(e,t){return e.configFor(O1(e,t))}function N1(e,t){let n=k1(e,t);if(n===null)return null;let r=()=>e.lanes.of(w1(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function P1(e,t){let n=A1(e,t);return n===null?Nq:Lq(e.configFor(n))}function F1(e){return NG(kq().read(),e.projectDir,e.cwd,e.target.path)}function I1(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.log}}const L1=async(e,t)=>{let[n=``,r=``,i=``]=XC(()=>wa(e)),a=r1(n),o=O1(t,a),s=t.configFor(o),c=uB(s);if(!r)throw new Y(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new Y(`set-config: ${l.reason}`);let u=F1(o),d=RK(s,e=>t.sessionState.get(a,e),r);kJ(I1(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.log(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},R1=async(e,t)=>{let[n=``,r=``,i=``]=XC(()=>wa(e)),a=r1(n);if(!r)throw new Y(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!_1.test(i))throw new Y(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=O1(t,a),c=t.configFor(s),l=uB(c),u=l.rangeParamsFor(r);if(!u)throw new Y(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=F1(s),f=RK(c,e=>t.sessionState.get(a,e),r),p=OJ(d.path,f.key),m=typeof p==`number`?x1(u,p):S1(`step-config`,r,u,fB(f.globals,r)),h=v1(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new Y(`step-config: ${g.reason}`);kJ(I1(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.log(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},z1=async(e,t)=>{let[n=``]=XC(()=>wa(e)),r=r1(n),i=O1(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=IK(a,o),c=zK(a,o);if(s.length+c.length===0){t.log(`info`,`save: nothing unsaved (session=${r})`);return}let l=sq(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new Y(`save: ${t.reason}`);return[e.target,t.value]});V1(`save`,l,c);let d=F1(i);AJ(I1(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.log(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(B1)].join(` `)} → ${d.path} (session=${r})`)},B1=e=>`${e.preset}/${e.id}.settings.${e.setting}=${bb(e.value)}`;function V1(e,t,n){for(let r of n){let n=t.validate(r.key,bb(r.value));if(!n.ok)throw new Y(`${e}: ${n.reason}`)}}const H1=async(e,t)=>{let[n=``]=XC(()=>wa(e)),r=r1(n),i=O1(t,r),a=t.configFor(i),o=UK(a,e=>t.sessionState.get(r,e)),s=sq(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new Y(`save-preset: ${t.reason}`);return[e.configKey,t.value]});V1(`save-preset`,s,o.placements);let l=F1(i),u=LJ(I1(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Xx.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Jx.preset.sessionKey,u),t.log(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(B1)].join(` `)} → ${l.path} (session=${r})`)},U1=async(e,t)=>{let[n=``]=XC(()=>wa(e)),r=r1(n),i=O1(t,r),a=GK(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new Y(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=F1(i);RJ(I1(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(IK(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=Vx.map(e=>Jx[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.log(`info`,`save-theme-default: ${a.theme} ${Vx.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},W1=async(e,t)=>{let[n=``,r=``]=XC(()=>wa(e)),i=r1(n);if(!r)throw new Y(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=O1(t,i),o=F1(a);zJ(I1(t,i),o,r),t.reloadConfig(a);let s=Jx.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.log(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},G1=async(e,t)=>{let[n=``,...r]=XC(()=>wa(e)),i=r1(n),a=O1(t,i),o=uB(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new Y(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=F1(a),l=r.map(KK),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);PJ(I1(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.log(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function K1(e,t){let n=(e,t)=>[...nb(Ow(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Tw(t.presets).flatMap(e=>n(t,e).map(t=>aF(XN(e),Qy(t)))));return Tw(e.presets).flatMap(t=>n(e,t).map(e=>({member:aF(XN(t),Qy(e)),node:e})).filter(({member:e})=>!r.has(e)))}function q1(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[tF]:[]])}const J1=async(e,t)=>{let[n=``,r=``,i=``]=XC(()=>wa(e)),a=r1(n),o=O1(t,a),s=t.configFor(o),c=uB(s);if(!r)throw new Y(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new Y(`apply-layout-op: ${l.reason}`);let u=Xz(l.value);if(u===null)throw new Y(`apply-layout-op: "${l.value}" is not a layout op token`);let d=F1(o),f=BJ(I1(t,a),d,r,u);t.reloadConfig(o);let p=q1(K1(s,t.configFor(o)),t.sessionState.get(a,tF)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.log(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},Y1=async(e,t)=>{let[n=``]=XC(()=>wa(e)),r=r1(n);t.journal.commit();let i=t.history.undo(r);t.journal.wrote(),j1(t,r,i),t.log(`info`,`undo: restored ${dY(i)} (session=${r})`)},X1=async(e,t)=>{let n=r1(i1(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,sq(M1(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.log(`info`,`back: ${a} discarded=${i} (session=${n})`)},Z1=async(e,t)=>{let n=r1(i1(e));t.journal.commit(),t.journal.wrote();let r=t.history.rewind(n);j1(t,n,r),t.log(`info`,`rewind: put back ${dY(r)||`nothing`} as edit mode found it (session=${n})`)},Q1=async(e,t)=>{let[n=``]=XC(()=>wa(e)),r=r1(n);t.journal.commit();let i=t.history.redo(r);t.journal.wrote(),j1(t,r,i),t.log(`info`,`redo: re-applied ${dY(i)} (session=${r})`)},$1=async(e,t)=>{r1(i1(e)),await t.applyUpdate()},e0=`client-hints`;function t0(e,t){let n=e.sessionState.get(t,e0);if(n===null)throw new Y(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new Y(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new Y(`client hints record is not an object: ${n}`);return Lt(r)}function n0(e,t,n){let r=GI(n);e.sessionState.setBatch(t,cL(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${YI(n.config)} ${oL(n.nerdFont,n.marks)} ${XI(n.terminal,n.clicked)} ${ZI(n.terminal,n.width)} ${QI(n.install)} ${eL(n.daemon)} ${tL(n.data)} ${aL(n.transcripts)} ${nL(n.frames,n.claudeSettings)} ${iL(n.claudeSettings.origin.sources)} (session=${t})`)}async function r0(e,t,n,r){let i={kind:`clicked`,sessionId:t,via:e.arrival.via},a=e.clients.ofSession(t,e.now()),o;try{o=await u$({...n,loadConfig:()=>r},t0(e,t),O1(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:a.map(e=>e.rateLimits)},{kind:`ok`,value:a.map(e=>e.transcript)},i,{kind:`ok`,value:MY(i,a)},l$(t,a),IQ(e.doctorStores))}catch(e){throw e instanceof OY?new Y(e.message):e}let s={facts:o,install:PQ(n.install,e.bundle,a.map(e=>e.client)),current:async e=>{let i=n.loadConfig(O1(e,t));return i.config===r.config&&i.error===r.error&&i.warning===r.warning?s:r0(e,t,n,i)}};return s}const i0=(e,t)=>{let n=LQ(e.doctor);return r0(e,t,n,n.loadConfig(O1(e,t)))};async function a0(e,t,n){let{facts:r,install:i}=await e.gather(n.current),a=IQ(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:o$(e.arrival),install:i,clicked:o0(e,o)}}function o0(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?HF(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>EY(e,r))}catch(t){return e.log(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const s0={gathers:!0,prepare:async(e,t)=>{let n=r1(i1(e)),r=await i0(t,n);return async e=>n0(e,n,await a0(e,n,r))}},c0=async(e,t)=>{let n=j$(i1(e));if(n===null)throw new Y(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new Y(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.log(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},l0={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``]=XC(()=>wa(e)),i=r1(n),a=KI(r);if(a===void 0)throw new Y(`doctor-fix: unknown check "${r}"`);let o=await i0(t,i);return async e=>{let t=await a0(e,i,o),n=a.probe(t);if(n.ok||n.fix===void 0)throw new Y(`doctor-fix: ${a.label} — ${n.ok?`nothing to fix`:n.reason}`);let r=d$(e.doctorStores,n.fix,t);if(r.kind===`failed`)throw new Y(`doctor-fix: ${a.label} — ${r.reason}`);e.log(`info`,`doctor-fix: ${a.name} → ${eI(n.fix)} (session=${i})`),n0(e,i,r.value)}}},u0={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``,i=``]=XC(()=>wa(e)),a=r1(n),o=KI(r);if(o===void 0)throw new Y(`doctor-mark: unknown check "${r}"`);if(!ZF.includes(i))throw new Y(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${ZF.join(` or `)}`);let s=await i0(t,a);return async e=>{let t=await a0(e,a,s),n=o.probe(t);if(n.ok||n.sighting===void 0)throw new Y(`doctor-mark: ${o.label} — ${n.ok?`nothing to mark`:`shows nothing to look at`}`);let r=[o.name,n.sighting.id,i],c=e.doctorStores.marks.update(e=>CY(e,...r));if(c.kind===`failed`)throw new Y(`doctor-mark: ${c.reason}`);e.log(`info`,`doctor-mark: ${o.name} ${i} on ${n.sighting.id} (session=${a})`),n0(e,a,{...t,marks:c})}}},d0=async(e,t)=>{let[n=``,r=``]=XC(()=>wa(e)),i=r1(n),a=Object.values(t.configFor(O1(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new Y(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=await t.typing(t0(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.log(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new Y(`${r} was not typed: ${s.reason}`);t.log(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)};function f0([e=``,t=``,n=``,r=``],i){let a=r1(e),o=O1(i,a),s=i.configFor(o).actions,c=Object.hasOwn(s,t)?s[t]:void 0;if(c===void 0||!(`run`in c))throw new Y(`"${t}" is not a run action this session's config declares`);let l=Vw(c);if(!i.links.verify({sessionId:a,action:t,declaration:l,evaluated:n},r))throw new Y(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let u;try{u=JSON.parse(n)}catch{throw new Y(`run ${t}: what the link carries is not JSON`)}let[d,...f]=u.run;if(d===void 0||d===``)throw new Y(`run ${t}: the program evaluated to nothing`);let p=i.sourcesFor(o);return{sessionId:a,action:t,argv:[d,...f],env:{...bY(process.env,{sessionId:a,projectDir:o.projectDir,claudeConfigDir:t0(i,a).claudeConfigDir}),...u.env},cwd:c.cwd,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const p0=async(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=XC(()=>wa(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=f0(i,t)}catch(e){throw e instanceof Y&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)},m0=async(e,t)=>{let[n=``,r=``,i=``,a=``]=XC(()=>wa(e)),o=r1(n),s=i;if(!t.links.verify(jq(o,r,s),a))throw new Y(`the answer's signature does not match what it carries: it was not drawn by this daemon`);let c=Aq(kq(),r,s);if(c.kind===`failed`)throw Error(`${r} was not ${s}: ${c.reason}`);t.journal.wrote();let{superseded:l,absent:u,unchecked:d}=c.value;t.log(`info`,`repo-config: ${r} ${s} superseded=${l.join(`,`)||`-`} absent=${u.join(`,`)||`-`} unchecked=${d.length===0?`-`:JSON.stringify(d)} (session=${o})`),t.reloadConfig(O1(t,o))},h0=`config-override`,g0=new Map([[Ki,n1(u1)],[Yi,n1(async(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new Y(`load-config: expected <sessionId>/<path> (missing separator)`);let r=r1(XC(()=>decodeURIComponent(e.slice(0,n)))),i=XC(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new Y(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new Y(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,h0),t.log(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,h0,i),t.log(`info`,`load-config: ${i} (session=${r})`))})],[qi,n1(m1)],[Wi,n1(g1)],[Gi,n1(y1)],[Xi,n1(L1)],[Zi,n1(R1)],[na,n1(G1)],[Qi,n1(z1)],[$i,n1(H1)],[ea,n1(U1)],[ta,n1(W1)],[ra,n1(J1)],[ia,n1(Y1)],[aa,n1(Q1)],[oa,n1(X1)],[sa,n1(Z1)],[Ji,n1(h1)],[ca,n1($1)],[la,s0],[ua,l0],[da,u0],[fa,n1(c0)],[pa,n1(d0)],[`run`,n1(p0)],[ma,n1(m0)],[ha,n1(p1)]]),_0=new Set([Wi,Gi,Xi,Zi,na,Qi,$i,ea,ta,ra,ia,aa,oa,sa,Ji,ca,la,ua,da,pa,`run`,ma,Yi,ha]);function v0(e,t){return y0(e===`dispatch`?Da(t):[{verb:e,value:t}])}function y0(e){let t=e.find(e=>_0.has(e.verb)),n=t===void 0?``:XC(()=>Ta(t.value));return n===``?null:t1(n)}const b0=(e,t,n)=>n.journalTurns.gathering(()=>e.prepare(t,n)).catch(e=>()=>Promise.reject(e));async function x0(e,t,n,r){await(r??await n.gather(n=>e.prepare(t,n)))(n)}async function S0(e,t){let[n]=ka(Da(e)),r=n===void 0?void 0:g0.get(n.verb);return r?.gathers?b0(r,n.value,t):void 0}async function C0(e,t,n){let r=[],i=!1,a=Da(e),o=y0(a);for(let[e,{verb:o,value:s}]of ka(a).entries()){let a=g0.get(o);if(!a){r.push(`unknown effect verb "${o}"`);continue}try{await x0(a,s,t,e===0?n:void 0)}catch(e){if(e instanceof JC)throw r.length>0&&t.log(`warn`,`dispatch: ${r.join(`; `)}`),e;e instanceof Y||(i=!0),r.push(`${o}: ${e instanceof Error?e.message:String(e)}`)}}if(r.length>0){o?.ok&&Ec(t.sessionState,o.id,r.join(`
|
|
480
|
+
`),t.now());let e=`dispatch: ${r.join(`; `)}`;throw i?Error(e):new Y(e)}}function w0(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}async function T0(e,t,n,r){let i=e===null?null:N1(t,e),a=t.history.begin(),o=t.navigation.begin(a.sessionState),s=n.holds(()=>{let e=[];for(let t of[o,a])try{t.commit()}catch(t){e.push(t)}w0(e)}),c=[],l=e=>Bq(e,e=>P1(t,e),e=>t.log(`info`,e)),u={...t,sessionState:l(a.sessionState),journal:a,navigating:l(o.sessionState)},d={launch:(e,r)=>n.landed(s1(t.launcher,e,r,t.log)),typing:(e,r)=>n.landed(Y$(t.claudeInput,e,r)),applyUpdate:()=>n.landed(t.applyUpdate())};try{await r({...u,...d,gather:e=>n.landed(e(u))})}catch(e){c.push(e)}let f=!0;try{f=s()}catch(e){c.push(e)}if(f&&i!==null)try{let e=i.read();t.lanes.clicked(i.sessionId,a.written()?i.before:e,e)}catch(e){c.push(e)}if(f&&e!==null)try{let n=A1(t,e);n!==null&&t.views.follow(e,n)}catch(e){c.push(e)}w0(c)}function E0(e,t,n){return async(r,i)=>{let a=v0(e,r),o=a?.ok?a.id:null;return i.journalTurns.click(e,o,{placed:i.placeWaited,waited:i.turnWaited,gone:i.clientGone,gathered:i.gatherTook},()=>t(r,i),(e,t)=>T0(o,i,t,async t=>{try{await n(r,t,e)}finally{o!==null&&i.clickLanded(o)}}))}}const D0=new Map([...[...g0].map(([e,t])=>[e,E0(e,async(e,n)=>t.gathers?b0(t,e,n):void 0,(e,n,r)=>x0(t,e,n,r))]),[Ui,E0(Ui,S0,C0)],[fa,c0]]);Object.freeze([...D0.keys()]);function O0(e,t,n){return n.journalTurns.take(`menu-idle`,{waited:t=>n.log(`info`,`menu-idle: waited=${t}ms (session=${e})`),gone:()=>!1},r=>T0(e,n,r,async n=>{if(!t.stillIdle()){n.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}t.closed();let r=zq(P1(n,e),t=>n.navigating.get(e,t));n.navigating.setBatch(e,r.map(({key:e})=>({key:e,value:N}))),n.log(`info`,`menu-idle: closed=${r.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)}))}function k0(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const A0={kind:`hidden`},j0={kind:`shown`};function M0(e,t){try{return k0(e,t)?j0:A0}catch(e){let t=LT(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function N0(e,t){let n=K.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function P0(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function F0({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function I0({text:e,placement:t,lead:n,trail:r}){return{text:L0(e),placement:t,...n!==void 0&&{lead:L0(n)},...r!==void 0&&{trail:L0(r)}}}function L0(e){let t=e.blankCopy(e.plain);t.style=fS(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(fS(i).clearMetaAndLinks(),n,r);return t}function R0(e){let t=F0(e);if(t.length===1)return e.text;let n=N0(t);return n.style=e.text.style,n}function z0(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=N0(e,a).pad(o),d=new K(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:N0([d,...c],a)},...l.length>0&&{trail:N0([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(P0(u,n,p),[{text:u,...f}])}function B0(e,t,n){let r=`x`.repeat(Math.min(n,t)).replace(/x$/,` `),i=r+e,a=[],o=0;return tC(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 V0(e,t){if(e.length===0)return 0;let{lines:n}=nC(e.map(({owner:e})=>e),t),r=z(VS(n[n.length-1]));return Math.max(0,r-YS(t)+XS(t))}function H0(e,t,n){if(e.cellLength<=t)return!0;let{lines:r}=nC([e],{...n,width:1/0});return z(VS(r.flat()))<=n.width}function U0(e,t,n,r){if(H0(e.owner,t,r))return[e];let i=e.owner.copy().expandTabs(),a=V0(n,r);return i.divide(B0(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 W0(e,t){let n=Math.max(2,eC(t)-YS(t)-t.padding);return G0(e,t).reduce((e,r)=>[...e,...U0(r,n,e,t)],[])}function G0(e,t){let n=()=>e.map(e=>({owner:R0(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=nC(e.map(R0),t).lines;if(i.length>1)return n();let a=Math.max(0,t.width-z(VS(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];P0(c,c.cellLength+a,n)}),n()}function K0(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=q0(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:fS(a.style)};if(e.style.link){i();let r=q0([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function q0(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>J0(e.frag,n?n.add(e.style):e.style)),i=K.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function J0(e,t){let n=e.copy();return n.style=t,n}function Y0(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 X0(e,t){let{look:n}=Y0(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function Z0(e,t){let{layout:n}=Y0(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function Q0(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 $0(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,e2(e,t,o,n,r,i));return i}function e2(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=Lw(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=Qx.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=Lw(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=Lw(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:r2(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:r2(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:Vw(n),argv:n.run.map(n=>r2(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,r2(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:r2(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 t2(e){return e.kind===`do`?t2(e.head):e}function n2(e){switch(t2(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 r2(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function i2(e,t){return e.has(t)?NT(e.read(t)):``}function a2(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function o2(e,t,n,r){let i=new K(e,{style:U.combine([r,new U({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function s2(e,t,n=!1){let r=new U({link:t,bold:n?!0:void 0}),i=new K(e.plain,{style:U.combine([fS(e.style),r])});for(let t of e.spans)i.stylize(U.combine([fS(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function c2(e,t){return Math.max(e.members.indexOf(i2(t,e.stateVar)),0)}function l2(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=i2(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=i2(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=i2(r,e.stateVar);return{effects:[{verb:Wi,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(c2(e,r)+1)%e.members.length];return{effects:[{verb:Wi,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Gi,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Ki,args:[a2(e.text,cN(r))]}],active:!1};case`open`:return{effects:[{verb:qi,args:[a2(e.target,cN(r))]}],active:!1};case`persist-literal`:{let t=i2(r,e.stateVar);return{effects:[{verb:Xi,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=i2(r,e.stateVar);return{effects:[{verb:Xi,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(c2(e,r)+1)%e.members.length];return{effects:[{verb:Xi,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Zi,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:na,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ia,args:[i]}],active:!1};case`redo`:return{effects:[{verb:aa,args:[i]}],active:!1};case`back`:return{effects:[{verb:oa,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:sa,args:[i]}],active:!1};case`save`:return{effects:[{verb:Qi,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:$i,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:ea,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:ta,args:[i,a2(e.name,cN(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:la,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:ua,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:da,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:pa,args:[i,e.line]}],active:!1};case`run`:{let t=cN(r),n=JSON.stringify({run:e.argv.map(e=>a2(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,a2(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:ra,args:[i,e.key,Yz(e.op)]}],active:!1};case`do`:{let o=l2(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>l2(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:ra,args:[i,e.key,Yz(r)]}],active:!1}}}}function u2(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:xi(`action "${e}"`,n,t.members.length,c2(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 d2(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=Y0(n,`action "${e}"`).store,{display:a,boundValue:o}=u2(e,t2(r),t,i),s=i2(i,`session.id`),{effects:c,active:l}=l2(r,a.plain,o,i,s,n.signer);return s2(a,Ea(c),l)}function f2(e){return{action:{fn:(t,...n)=>d2(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function p2(e,t){return o2(`✕`,Ea([{verb:Wi,args:[i2(e,`session.id`),t,N]}]),!1)}function m2(e,t,n){return new U({bgcolor:H.fromRgba(t),color:H.fromRgba(Vv(e,t,n))})}function h2({tint:e,text:t}){return new U({bgcolor:H.fromRgba(e),color:H.fromRgba(t)})}function g2(e,t,n){return new U({color:H.fromRgba(cd(e.get(`warning`),t,Bv,n))})}function _2(e,t,n){return U.combine([m2(e,t,n),g2(e,t,n)])}function v2(e,t,n){return h2($v(e.palette,e.disclosure,t,n))}function y2(e){let t=H.fromRgba(e.get(`background`)),n=K.fromFragments(U_.map(n=>new K(`▀`,{style:new U({color:H.fromRgba(e.get(n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const b2=(e,t)=>{let n=typeof e==`string`?new K(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},x2=e=>new U({bold:e});function S2(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>b2(a,U.combine([v2(e,{...n,distribution:t},i),x2(o)]));let o=m2(e.palette,a,i);return(e,t,i,a)=>C2(i,U.combine([o,x2(a)]),r(t,n))}const C2=(e,t,n)=>b2(K.fromFragments([b2(e,t),b2(` `,t),y2(n)]));function w2(e,t,n,r){return t===void 0?b2(r):C2(r,void 0,t(n,e))}function T2(e,t,n,r,i){let a=m2(e.palette,i,r);return(e,r,i,o)=>b2(K.fromFragments([b2(o?`[`:` `,a),y2(n(r,t)),b2(o?`]`:` `,a)]))}function E2(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=>D2(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function D2(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function O2(e,t){return new K(e).truncate(t,{marker:`…`}).plain}function k2(e){return{current:null,drawnAt:e}}function A2(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 j2(e,t,n){return N2(e,()=>n(A2(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function M2(e,t){return N2(e,()=>(e.current=null,t()))}function N2(e,t){let n=e.current;try{return t()}finally{e.current=n}}function P2(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 F2(e){return new K(e).cellLength}function I2(e){let{width:t,chromeCols:n,padding:r}=Y0(e,`a row fit`);return Math.max(1,t-n-2*r)}function L2(e){let{padding:t,seamCols:n}=Y0(e,`a row fit`);return Math.max(1,I2(e)-(F2(`✕`)+2*t+n))}function R2(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 z2(e,t,n){let r=F2(`←`)+1+F2(`→`)+1,i=R2(e,t,n);return(i.length>1?R2(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function B2(e){let t=[];for(let n of e)t.length>0&&t.push(new K(` `)),t.push(n);let n=K.fromFragments(t);return n.overflow=`ignore`,n.end=``,n}function V2(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 H2(e,t,n){let r=e.compiled.get(t),i=r&&t2(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 U2(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=Y0(a,`picker`).store,d=i2(u,`session.id`),f=`stateVar`in t?i2(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`?L2(a):I2(a):1/0,h=(r.kind===`led`?0:F2(`✕`)+1)+c.reduce((e,t)=>e+F2(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?z2(v.map(e=>e.cellLength),m,h):E2(g.entries,g.groups,i),b=parseInt(i2(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,ee=y[C]??[],te=e=>Ea([{verb:Wi,args:[d,n.key,String(e)]}]),w=r.kind===`led`?[]:[{verb:Wi,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],ne=r.kind===`own`&&r.onPick?w:[],T=e=>Ea([...l2(l,e,e,u,d,a.signer).effects,...ne]),re=(e,n)=>s2(e,T(t.options[n])),E=r.kind===`led`?[]:[o2(`✕`,Ea(w),!1,s)];E.push(...c.map(({glyph:e,option:r})=>o2(e,Ea([...l2(l,r,r,u,d,a.signer).effects,{verb:Wi,args:[d,n.key,String(x(t.options.indexOf(r)))]}]),!1))),C>0&&E.push(o2(`←`,te(C-1),!1));let D=C<y.length-1?[o2(`→`,te(C+1),!1)]:[];if(g===void 0){let e=ee.flatMap(e=>e.indices);return[B2([...E,...e.map(e=>re(v[e],e)),...D])]}let ie=new U({bold:!0}),O=y.length>1?` ${C+1}/${y.length}`:``,ae=ee.length===1?[new K(`${ee[0].label}${O}`,{style:ie})]:[],oe=[B2([...E,...ae,...D])];for(let e of ee){ee.length>1&&oe.push(B2([new K(e.label,{style:ie})]));let n=Math.max(...e.indices.map(e=>F2(_(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:iS(i),o=` `.repeat(n-F2(e)+2),s=a===void 0?e:`${e}${o}${a}`;oe.push(B2([re(p(r,O2(s,m)),r)]))}}return oe}function W2(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{RM(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=V2(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=H2(e,n,`picker`),u=P2(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=>U2(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,S2(u,Tv(void 0),X0(e,`{{ picker }}`),l.paletteOf,d,t),g2(u.palette,t,d)),p=Zv(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 G2(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function K2(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=Y0(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=i2(a,`session.id`),{options:c}=t;if(c.length===0)return B2([]);let l=G2(c,i2(a,t.stateVar)),u=e=>c[l(e)],d=e=>Ea(l2(o,u(e),u(e),a,s,i.signer).effects);return B2([o2(`◀`,d(-1),!1),s2(w2(X0(i,`{{ carousel }}`),t.paletteOf,u(0),r),Ea(l2(i.compiled.get(n),u(0),void 0,a,s,i.signer).effects)),o2(`▶`,d(1),!1)])}function q2(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(n2(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 K2(t,H2(e,t,`carousel`),n,r,e)},argTypes:[`string`,`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}function J2(e,t,n){let r=H2(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 Y2(e,t,n){let r=Math.imul(e^e>>>16,73244475);return r=Math.imul(r^r>>>16,73244475),r^=r>>>16,(n+1+(r>>>0)%Math.max(t-1,1))%t}function X2(e,t,n,r){let i=J2(e,t,n),a=r??i2(Y0(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,X0(e,`{{ ${n} }}`))}function Z2(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(RM(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return y2(X2(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function Q2(e,t,n){return{swatches:{fn:(r,i)=>{let a=J2(e,r,`swatches`),o=V2(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=P2(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]=U2(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,T2(s,X0(e,`{{ swatches }}`),a.paletteOf,c,s.bg),g2(s.palette,s.bg,c),u===0?[]:(()=>{let t=G2(l,i2(Y0(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[Y2(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const $2=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function e4(e,t,n,r){let i=Zv(e,n,r),a=(t,n)=>({text:t,colour:n,ink:Vv(e,n,r)});return[[dv(e,t,r).map((n,i)=>{let a=zv(e,n);return{text:$2[i%$2.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 t4(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new K(` ${e} `,{style:h2({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new K(e)),r.push(a)}return r}function n4(e,t,n,r,i){let a=e4(e,t,n,r).map(e=>t4(e,i)),o=K.fromFragments(a.flatMap((e,t)=>t===0?e:[new K(`
|
|
481
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}function r4(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(RM(`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}=X0(e,`{{ themePreview }}`);return n4(r===void 0?a:X2(e,r,`themePreview`),o,{...P2(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),L2(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const i4=e=>e.slice(e.lastIndexOf(`.`)+1),a4=(e,t)=>{let n=new K(i4(e));return n.truncate(t,{marker:`…`}),n.plain};function o4(e,t){let n=e.map(e=>e.map(({name:e})=>F2(i4(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 s4(e,t,n,r){let i=o4(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new K(` ${a4(s,i)} `,{style:h2(ly(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=K.fromFragments(a.flatMap((e,t)=>t===0?e:[new K(`
|
|
482
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}const c4=`layoutPreview`;function l4(e,t){return{[c4]:{fn:()=>s4(Z0(e,`{{ layoutPreview }}`),X0(e,`{{ layoutPreview }}`).decor,t.drawnAt(),L2(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function u4(e,t,n,r){let i=P2(r.activeSegment,`{{ menu }}`),a=r.action,o=QN(i.placementId,e,n.key),s=tP(o),c=ZN(e),l=Y0(a,`menu`).store,u=i2(l,o)===c,d=i2(l,`session.id`),f=u?N:c,p=o2(xi(`{{ menu "${e}" }}`,t,2,+!!u),Ea([{verb:Wi,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=Zv(i.palette,i.disclosure,t).plane,l=H2(a,e,`menu`);return U2(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,N],[s,`0`]],onPick:n.closeOnPick},n.paged,a,S2(i,n.distribution,X0(a,`{{ menu }}`),l.paletteOf,t,c),g2(i.palette,c,t))})():[]),p}const d4=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function f4(e,t){let n=t[t.length-1],r=d4(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:aP(r??{})}}function p4(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=f4(t,n);return u4(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function m4(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=h4(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new K(t?i:a,{style:l===void 0?void 0:new U({color:l})}))}let l=K.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function h4(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 g4(e){let t={fn:(()=>{let t=P2(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:(()=>P2(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=P2(e,`{{ roleTextOn }}`);return y4(r,t,Xu(r,n)).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i={fn:((t,n)=>{let{palette:r}=P2(e,`{{ keptOn }}`),i=Xu(r,t),a=Xu(r,n),o=Bl(ud(i,V.TRUECOLOR),ud(a,V.TRUECOLOR)),s=Math.min(Bv,Math.max(o,3));return(ld(i,e.drawnAt(),(e,t)=>Bl(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},a=yM(()=>P2(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),o={fn:((e,t,n,r,i,o,...s)=>{let c=o===void 0?void 0:[o,...b4(s)];return m4({value:e,max:t,width:n,filled:r,empty:i,colourAt:c===void 0?void 0:e=>String(a.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...a,bgOf:t,tint:n,roleTextOn:r,keptOn:i,gauge:o}}const _4={"#000000":[`darken-1`,`darken-2`,`darken-3`],"#ffffff":[`lighten-1`,`lighten-2`,`lighten-3`]},v4=Object.values(_4).flat();function y4(e,t,n){let r=ud(n,V.TRUECOLOR),i=t=>{let n=Xu(e,t);return{colour:n,ratio:Bl(ud(n,V.TRUECOLOR),r)}},a=sd(r).hex,o=_4[a];if(o===void 0)throw Error(`contrastFor named ${a} for ${n.hex}, which is neither pole`);let s=`text-${t}`,c=e=>`${t}-${e}`,l=new Map([s,t,...v4.map(c)].map(e=>[e,i(e)]));return([s,t,...o.map(c)].map(e=>l.get(e)).find(({ratio:e})=>e>=4.5)??[...l.values()].reduce((e,t)=>t.ratio>e.ratio?t:e)).colour}function b4(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function x4(e,t){if(e.kind!==`shell`&&e.kind!==`file`)return[];let n=`key`in e.cache&&[...t.calls(e.cache.key)].some(e=>oN.has(e));return[...t.ofVariable(e).flatMap(({reaches:e})=>e.length===0?[null]:e),...n?[null]:[]]}const S4={input:`view`,state:`view`,template:`view`,time:`view`,literal:`directory`,env:`directory`,dropped:`directory`,source:`view`},C4=new WeakMap;function w4(e){let t=C4.get(e);return t===void 0&&(t=T4(e),C4.set(e,t)),t}function T4(e){let t=new Map(hT(e)),n=jU(e),r=new Map([...t].map(([e,t])=>[e,t.kind===`shell`||t.kind===`file`?`directory`:S4[t.kind]])),i=new Map([...t].map(([e,t])=>[e,x4(t,n)]));for(let e=!0;e;){e=!1;for(let[t,n]of i)r.get(t)!==`view`&&n.some(e=>e===null||r.get(e)!==`directory`)&&(r.set(t,`view`),e=!0)}return r}function E4(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
483
483
|
`)){n.push(r);continue}let e=r.split(`
|
|
484
|
-
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function E4(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 D4=e=>e.kind===`failed`?k0:e;function O4(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function k4(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 A4(e){return{...e,cells:e.cells.map(F0)}}function j4(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,...M4(e,r)]}function M4(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 N4(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:j4(e.direction,e.children.map((t,i)=>n(t,[...r,P4(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function P4(e,t){return e.steps[t]}function F4(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=I4(e);return{width:L4(t),reach:R4(t)}}function I4(e){let t=e.children.map(F4),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 L4=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),R4=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function z4(e,t){let n=I4(e);if(t?.axis===`cell`)return n.map(({start:e,span:n,ownLine:r})=>{let i=t.index+e;return r?{...t,index:i,lineStart:i,lineEnd:i+n.width-1}:{...t,index:i}});let r=Zy[e.direction],i=Tv(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),R4(n),L4(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const B4={compile(e,t){let n=z4(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,rb(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),j4(e.direction,e.children.map((n,r)=>t.renderChild(n,D4(t.gate),P4(e,r))))}},V4={drop:e=>e.place,above:()=>`above`},H4={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},U4={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:Qy(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(wi(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,ib(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,W4(e,t))};function W4(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=uN(t.scope,e.settings);if(t.gate.kind===`failed`)return X4(e,r,t,t.gate.message);try{let i=t.placement(e),a=O4(t.gate,i.gate());if(a.kind===`failed`)return X4(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 X4(e,r,t,s.message);let c=$C(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:dF(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`?G4(f.variable):K4(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?q4(p.segment,u):J4(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:k0,h.disclosure).map(e=>({...e,place:V4[v.placement](e)})),b=(e,t,n)=>R0(G0([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?H4[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},ee=S.flatMap(e=>b(new K(` `.repeat(Y4(P0(e)))),h.trigger,0)),te=(e,t)=>e.band===`own`?t===x?S:ee:[],w=y.map((e,t)=>({cells:[...te(e,t),...e.cells],band:`deeper`,place:e.place})),ne=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ne.flatMap(e=>e.cells),...y.flatMap(te)].flatMap(P0)),[...ne,...w]}catch(n){return X4(e,r,t,n.message??String(n))}}const G4=e=>({kind:`waiting`,variable:e});function K4(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=LT(e);if(t===void 0)throw e;return G4(t.variable)}}function q4(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:T4(G0(r,c)).map((e,t)=>({cells:R0(e,{...l,lead:t===0?G0(i,c):[],trail:t===0?G0(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:R0(G0([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function J4(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=G0(Z4(e.lead,e,t,n),l),d=G0(Z4(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 R0(G0([new K(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function Y4(e){return e.reduce((e,t)=>e+t.cellLength,0)}function X4(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:R0([new K(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:dF(n.palette)},lead:Z4(e.lead,e,t,n),trail:Z4(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function Z4(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=LT(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const Q4={container:B4,segment:U4};function $4(e){return Q4[e]}var e3=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?t3:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const t3={kind:`hidden`},n3={palette:`theme`,style:`style`,effect:`effect`},r3=$x.get(`colorCompatibility`),i3={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function a3(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function o3(e){if(e.ok)return e.value;throw e.error}const s3=e=>({read:()=>e}),c3=V_({basePalette:B_,palette:B_,decor:ny});var l3=class{evaluated=0;memory=new e3;scope;binding;facts;look=X.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&c3(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=cN(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(r3);return typeof e==`string`&&By(e)?e:`truecolor`});let i=(0,X.observable)(i3,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 N4(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=Lz(e);return i===void 0?[]:[{name:i,address:n,palette:$C(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>Vy(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=qN(e);return t===void 0?GN(e)===void 0?PN(this.view.get().payload(),e):PN(this.projected,e):this.slotName(t)}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[n3[e]];if(t.kind===`decided`)return f3(t.name,null,null);let r=m3(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=h3(this.source,e,i.name,r.where,e=>{t=e}),f3(n,t,null)}case`pending`:return f3(n??Dy[e],null,i.variable);case`failed`:return n=Dy[e],f3(n,Oy(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!p3(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)??Dy[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 j0(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>j2(this.source.activeSegment,()=>j0(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new g3(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:Z0(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=LT(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:a3(e)}),o3(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:Lz(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function u3(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new l3(t,n,e,r);return e.views.set(t,a),a}function d3(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 f3=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),p3=(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 m3(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 h3(e,t,n,r,i){switch(t){case`palette`:return iw(n,r,i).name;case`style`:return wy(n,e.styles).name;case`effect`:return Py(n).name}}var g3=class{where=_3(V_({palette:B_,region:ey}));ground=_3(V_({colours:y3,bodyOpen:B_}));opened=_3(V_({colours:y3,open:B_}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=uN(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?s3(A0):e.derive(`${t.id} when`,e.readsInstant(a),()=>j2(r,()=>j0(a,i))),this.open=d===void 0?s3(k0):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>j2(r,()=>j0(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return S3(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 C3(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?s3(T3):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return w3(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}),D3(n,r,this.affixes.read())}};function _3(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 v3=(e,t)=>e.hex===t.hex,y3=V_({palette:B_,drawnAt:B_,tint:v3,text:v3,bg:v3,disclosure:ry});function b3(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const x3=e=>Zv(e.palette,e.disclosure,e.drawnAt);function S3(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...ly(n,r,i)};return A2(e,b3(t,c),e=>{let t=wte(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function C3(e,t,n,r,i,a){return A2(e,b3(t,n),e=>(e.bg=i?x3(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function w3(e,t,n,r,i,a,o){return A2(e,b3(t,n),e=>(e.bg=r?x3(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const T3={lead:[],trail:[],drops:[]};function E3(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return p2(t,x3(e).state,n)},get band(){return p2(t,x3(e).plane,n)},get close(){return g2(t,x3(e).state,n)},disclosure:r}}function D3(e,t,n){return{styles:E3(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function O3(e,t,n,r,i,a,o){let s=S3(e,t,n,r,i,void 0,void 0,o);return D3(s,C3(e,t,s,a,!1,o),T3)}function k3(e,t,n,r,i){return E3(S3(e,t,n,r,i,void 0,void 0,{}))}function A3(e,t){return{payload:()=>e,selections:()=>t}}function j3(e){if(`ttl`in e)return{kind:`ttl`,durationMs:CN(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 M3(e,t){switch(sb(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 N3(e,t,n,r,i){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`source`:e.declareSourceDocument(t);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default,i);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:j3(n.cache),parse:M3(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:j3(n.cache),parse:M3(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 P3(e,t,n,r=TE.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 F3(e,t,n){let{compiled:r,loadWarnings:i}=L3(e,t,n.cwd,I3(n.signer),V3);return{...r,loadWarnings:i}}const I3=e=>(t,n)=>H3(n,e);function L3(e,t,n,r,i=V3){let a=R3(e),o=z3(a);return{compiled:r(o,a),compileKey:o,loadWarnings:B3(e,t,n,i)}}function R3(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of eS)n in t&&r.set(e,n);for(let[t,n]of fb(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...FU(e)].sort(([e],[t])=>e<t?-1:1)}}function z3(e){return w(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function B3(e,t,n,r){let i=C4(e),a=FU(e),o=[];for(let[s,c]of hT(e))if(r.has(i.get(s)))try{N3(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const V3=new Set([`directory`,`view`]);function H3({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>J0(i,`drawnAt`).registry.drawnAt(),o=O2(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=Tw(e.presets),u=Ez(e),d=[e=>Z2(i,o,e.now)],f=sN({extraFuncs:{...d2(i),...X2(i),...U2(i,o),...K2(i),...n4(i,o),...c4(i,o),...f4(s),...h4(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=P3(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=Q0(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:P3(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=gb(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Eee(t,e,a,t=>String(J0(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 $4(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=Ow(e,t);C.set(t,S(n,r,void 0))}let ee=new Map(yy.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of LU(e)){let e=t.join(`.`),i=ee.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:G3(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let te=new Set(n.map(([e])=>e)),w={reads:OU({names:te,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:iN(d)},ne=BU(w),T=[...C.values()].flatMap(W3(y)).some(e=>ne(m.get(e))),re=T?new Set([...w.clock,s4]):w.clock,E=BU({...w,clock:re}),D=new Set([...m].flatMap(([e,t])=>E(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=BU({reads:OU({names:te,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:w.projections,clock:re});for(let e of lW){let n=y[t][e];n!==void 0&&r(m.get(n))&&D.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:ee,instant:D,layoutReadsInstant:T,styles:e.styles,runtime:i,views:new WeakMap}}function U3(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 W3=e=>t=>{let n=[];return N4(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 G3(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 K3=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function q3(e,t,n,r,i){let a=J3(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function J3(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??Dy[e];case`failed`:return r({kind:`rule`,slot:e,message:Oy(t.where,e,`the rule failed — ${n.error}`)}),Dy[e]}}function Y3(e){return X3(e).filter(e=>!e.name.startsWith(Fi)).map(e=>e.id)}function X3(e){return e.kind===`container`?e.children.flatMap(X3):[e,...e.opens===void 0?[]:X3(e.opens.body)]}function Z3(e,t,n,r,i,a){let o={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return u3(e,t,n,A3(o,a)),o}function Q3(e,t,n,r,i,a,o,s,c){try{var l=jo();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new wS(``),h=m.clockAt(a,Ay[c.animationSpeed]),g=l.u(JM(a,h.timeline)),_=d3(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:YS(v),padding:v.padding,seamCols:XS(v),preset:c.preset},i);let y=_.evaluated;l.u(Z0(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:lv[c.variation],shade:ev[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},ee=_.memory.begin(C,k4),te=_.memory.from(C),w=new Set,ne={held:e=>te?.rules.get(e),waited:e=>w.add(e),settled:ee.rule},T=new Map,re=e=>{let n=_.slot(e);if(T.set(e,n.kind===`settled`?`kept`:`per-draw`),n.kind===`settled`)return n.warning!==null&&p({kind:`rule`,slot:e,message:n.warning}),n.waited!==null&&w.add(n.waited),n.name;let r=h3(t,e,q3(e,n.rule,_,p,ne),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:E,style:D,effect:ie}=_.selections(),O=E.kind===`decided`?E:iw(re(`palette`),``,K3),ae=D.kind===`decided`?D:wy(re(`style`),e.styles),oe=ie.kind===`decided`?ie:Py(re(`effect`)),se=O.value,ce=tw(se,ae.value);_.publishLook({basePalette:se,palette:ce,decor:S});let le=ce.get(`warning`),ue=c.idleSince===void 0?null:{idleSince:c.idleSince,timeoutS:c.menuTimeout,fill:le,text:Vv(ce,le,r.drawnAt())},de=m.motion(oe.value,h,{transitions:x,source:C,last:te,returned:k4,hold:A4},ue);u?.clear();let fe=t=>e.segments[t],pe=(e,i,a)=>{let o=i.kind===`hidden`?i:O4(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${Y3(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:o.message,message:`${t}: ${o.message} — what it gates is hidden`})}}:o,c={scope:_.scope,palette:ce,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,i,o)=>O3(t.activeSegment,e,i,a,r.drawnAt(),o,n),lookupSegment:fe,renderChild:(e,t,n)=>pe(e,t,sy(a,n)),renderBody:(e,t,n)=>pe(e,t,cy(n)),closeDisclosure:e=>f2(n,e),placed:(e,t)=>ee.placed(e,de.placed(e,t)),lastDrawn:e=>te?.placements.get(e),waited:e=>w.add(e),decorations:(e,n)=>k3(t.activeSegment,e,n,a,r.drawnAt())};return $4(e.kind).render(e,c)},me=t.roots.get(b);if(me===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${Cw}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let he=E4(pe(me,A0,oy(S))).map(({line:e,row:t})=>{let n=U0(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...nC(n.map(e=>e.owner),v,de.row(t,r,n))}});de.drawn(),ee.commit();let ge=()=>he.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||X3(me).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`),_e=Math.min(g.heard(),...he.map(e=>e.nextChange)),ve=Number.isFinite(_e)?`moves`:ge()?`can-move`:`still`;for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{frame:{depth:v.colorCompatibility,rows:he.flatMap(({kind:e,lines:t})=>t.map(t=>({kind:e,runs:t}))),nextChange:_e,motion:ve,pending:[...w].sort()},evaluated:_.evaluated-y,cellBreaks:he.reduce((e,t)=>e+t.cellBreaks,0),rules:T}}catch(e){l.e=e}finally{l.d()}}const $3={moving:1e3/30,still:1e3},e6=[`data`,`state`,`reload`,`visibility`];function t6(e){return ox.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 n6(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const r6=(e,t)=>ax[t].handsOff?e.resp:e.statusline,i6=e=>Math.round(1e3/e);var a6=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&i.noted++}subscribe(e,t){let n=this.deps.lanes(e);if(n!==null&&!n[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e),i=r??this.open(e);return i.followers.set(t,null),i.rates.has(t.lane)||i.rates.set(t.lane,[]),r!==void 0&&this.send(i,t),this.hasten(i),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${i.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(i,t)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e,t){let n=this.feeds.get(e);n!==void 0&&(n.woke[t]++,this.hasten(n)||n.coalesced++)}wakeWhere(e,t){for(let{sessionId:n,req:r}of this.watched())t(r)&&this.wake(n,e)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}latest(e){return this.requests.get(e)?.req??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e,t){let n=this.feeds.get(e);if(n===void 0)return px;let r=t-1,i=this.shown(n);return fx(e=>{let a=n.rates.get(e);if(a===void 0)return ux;let o=0;for(let t of n.followers.keys())t.lane===e&&o++;let s=0;for(let e of a)e>r&&e<=t&&s++;return{subscribers:o,fps:s,shown:i}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.now(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e,`state`)),unpin:this.deps.pin(e),phase:{kind:`waiting`},lastStart:-1/0,last:null,since:t,drawn:0,noted:0,noView:0,moving:0,unseen:0,failed:0,pushed:0,drawMs:0,evaluated:0,cellBreaks:0,woke:{data:0,state:0,reload:0,visibility:0},coalesced:0,summarizedAt:t,refreshesAtOpen:this.deps.refreshes()};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),n}close(){for(let e of[...this.feeds.values()])for(let t of[...e.followers.keys()])this.unsubscribe(e,t)}unsubscribe(e,t){if(e.followers.delete(t)){if([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),e.followers.size>0){this.hasten(e);return}e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),e.unpin(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)}}draw(e,t){e.phase={kind:`drawing`};let n=this.deps.now(),r=this.deps.instant(),i=Math.min(Math.max(t,r),r+.002),a=n+(i-r)*1e3;try{this.step(e,n,a,i)}catch(t){if(e.lastStart=a,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${le(t)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,i)}}step(e,t,n,r){let i=this.deps.render(e.sessionId,i6(this.spacingOf(e)),r);if(i===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=n;let a=this.deps.now();this.drawn++,e.drawn++,e.drawMs+=a-t,e.evaluated+=i.evaluated,e.cellBreaks+=i.cellBreaks,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,i),this.push(e,i,r),this.feeds.get(e.sessionId)===e&&(a-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,i,r)))}schedule(e,t,n){let{moving:r,still:i}=this.deps.periods,a=((t?.bar.nextChange??1/0)-n)*1e3,o=Math.min(Math.max(a,r),i),s=this.shown(e);o<i&&s&&e.moving++,o<i&&!s&&e.unseen++;let c=s?o:i;this.arm(e,n+c/1e3,this.deps.instant())}spacingOf(e){return this.shown(e)?this.deps.periods.moving:this.deps.periods.still}hasten(e){let{phase:t}=e;if(t.kind===`drawing`)return!1;let n=this.deps.now(),r=Math.max(n,e.lastStart+this.spacingOf(e));if(t.kind===`due`&&t.at<=r)return!1;let i=this.deps.instant();return this.arm(e,i+(r-n)/1e3,i),!0}arm(e,t,n){let r=Math.max(0,(t-n)*1e3);this.setTimer(e,t,this.deps.now()+r,r)}setTimer(e,t,n,r){e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.phase={kind:`due`,at:n,timer:setTimeout(()=>this.fire(e,t,n),r)}}fire(e,t,n){let r=n-this.deps.now();r>0?this.setTimer(e,t,n,r):this.draw(e,t)}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t,n){let r=this.deps.lanes(e.sessionId);if(r!==null)for(let t of[...e.followers.keys()])r[t.lane]||(this.unsubscribe(e,t),this.refuse(e.sessionId,t));if(e.followers.size===0)return;t.delivered();let i={resp:JSON.stringify(t.resp),statusline:JSON.stringify(t.statusline)};if(e.last?.answers.resp===i.resp&&e.last.answers.statusline===i.statusline)return;let a=e.last?.answers??null;e.last={bar:t.bar,answers:i},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);for(let[t,r]of e.rates)(a===null||r6(a,t)!==r6(i,t))&&n6(r,n);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let n=r6(e.last.answers,t.lane);e.followers.get(t)!==n&&(t.frame(e.last.bar,n),e.followers.set(t,n))}refuse(e,t){this.refused++,this.deps.log(`info`,`feed sid=${JSON.stringify(e)} refused lane=${t.lane} switched-off`),t.refused({ok:!1,error:CP(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now(),r=this.deps.refreshes(),i=(n-e.since)/1e3,a=i===0?`-`:`${(e.drawn/i).toFixed(1)}fps`,o=vN.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=${i6(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${e6.map(t=>`${t}:${e.woke[t]}`).join(`,`)} coalesced=${e.coalesced} daemonRefreshed=${o} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function o6(e,t){return ox.filter(n=>e[n]&&ax[n].handsOff&&t.has(n))}function s6(e,t){return{severity:cC,lines:[[lC(`[⟲ claude]`,Ea([{verb:na,args:[e,...t.map(e=>ax[e].switch.setting)]}]))]]}}function c6(e,t){for(let n of Object.entries(t))e.push(n)}const l6={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function u6(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,le(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function d6(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...u6(n)];return{level:l6[n.kind],line:`${e}${i.map(([e,t])=>` ${e}=${R(t)}`).join(``)}`}}const f6=()=>{},p6=e=>({ok:!1,error:e instanceof Error?e.message:le(e),code:`RENDER_FAILED`,daemonV:3}),m6={ansi:e=>({ok:!0,output:RS(e)}),frame:e=>({ok:!0,frame:e})};function h6(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.date().getTime(),s=[];try{try{var c=jo();let i=c.u(x6(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=C6(e,i,{by:`feed`,fps:n}),p=m6.ansi(o.body),m=A6(t,o,o6(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:m6.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}=d6(`render`,s,{kind:`threw`,error:e},i.date().getTime()-o),r=p6(e);return{bar:OS(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:f6,failure:{level:t,line:`frame ${n}`}}}}function g6(e,t,n){let{sessionState:r}=e;return TK(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function _6(e,t){try{var n=jo();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:SK(i.view.source.effective(),Wc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function v6(e,t,n){try{var r=jo();let{renderCache:i,frameFeeds:a}=e,o=r.u(i.hold(t.projectDir,t.cwd,t.target.path)),s=a.latest(n);return SK(g6(e,n,o.state),s===null||Wc(s.hints.tmux))}catch(e){r.e=e}finally{r.d()}}function y6(e,t,n){c6(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=Rt(e,r),a=zt(i);return c6(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:i.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits}),a}function b6(e,t,n,r){let{sessionState:i,renderCache:a}=e,s=t.hookData.workspace?.current_dir??t.cwd,c={...t,hookData:{...t.hookData,...s!==void 0&&o.isAbsolute(s)&&{location:Hc(s)}}},l=c.sessionId,u=y6(c,n,r);c6(r,{encoding:c.encoding});let d=C1(c.requested,i,l);return S6(e,a.holdSession(d.projectDir,d.cwd,d.target.path,c),c,u,n,r)}function x6(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=y6(o,n,r)}catch(e){throw a[Symbol.dispose](),e}return S6(e,a,o,s,n,r)}function S6(e,t,n,r,i,a){let{payloadProviders:o}=e;try{let{entry:e,state:s,view:c}=t,{sessionId:l,hints:u}=n,d=c.source.effective();return{req:n,at:i,facts:a,sessionId:l,entry:e,state:s,view:c,hintsError:r,payloadInputs:{hookData:n.hookData,deps:{...o,lanes:c.lanes},cwd:n.cwd,neededInputPaths:s.neededInputPaths(d.preset),hints:u},[Symbol.dispose]:()=>t[Symbol.dispose]()}}catch(e){throw t[Symbol.dispose](),e}}function C6(e,t,n){let{sessionState:r,frameFeeds:i,renderCache:a,updateWatch:o,linkSigner:s,fileEvents:c,renderWarnings:l,payloadProviders:u,effectSessions:d,menuIdle:f,launcher:p}=e,{req:m,at:h,facts:g,sessionId:_,entry:v,state:y,view:b,hintsError:x}=t,S=b.source.effective(),C=SK(S,Wc(b.facts().hints.tmux));c6(g,{lanes:ox.filter(e=>C[e]).join(`,`)||`-`});let{hints:ee}=b.facts(),te=YX(ee);c6(g,{width:String(te)});let w=b.source.payload(),ne=tee(r,_,h,n.by),T=ne.kind===`held`||ne.kind===`owed`?ne.error:null,re=o.notice({sessionId:_,dismissed:r.get(_,pq),enabled:S.updateNotice}),E=Mq(v.repos,_,s),D=(e,t)=>({about:e,text:t,copy:t}),ie=e=>D(e??``,e),O=[ie(Vt(m.refusedArgs)),ie(x),D(`load`,v.lastError),D(`update-act`,o.error()),...y.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),ie(T?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),ae=v.watch===null?null:ST(`config watch`,v.watch,null),oe=[...al(c.delivery()),...p.lifelineWarnings(),...ae===null?[]:[{kind:`config-watch`,message:ae}],...v.lastWarning===null?[]:[{kind:`load`,message:v.lastWarning}]],se={config:y.config},ce=uC(_,n.by,O,[...re,...E],[...oe,...l.ofSession(_,n.by,se)].map(e=>({about:`${e.kind}\0${e.message}`,text:e.message,copy:e.message}))),le={diagnostics:bC(ce),drawing:n,feeds:i.feedsOf(_,h),today:dZ(u,b.lanes().today,b.facts().hookData,h)},ue=Ao(w.metrics)?void 0:w.metrics;c6(g,oZ(b.lanes().sources)),c6(g,{prompts:String(ue?.messageCount??`-`),nonPrompts:String(ue?.nonPrompts??`-`),pr:NX(w.git,GX(t.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:t6(le.feeds)});let de=[],fe=AX(S,te),pe=d.of(_),me=f.since(_,h),{frame:he,evaluated:ge,cellBreaks:_e,rules:ve}=Q3(y.config,y.compiled,b.store,b.registry,le,h,fe,{perSegmentSink:b.lastRenderCellsBySegment,onRenderWarning:e=>de.push(e)},{...S,effects:pe,idleSince:me}),ye=fC(ce),be=new Map(ce.map((e,t)=>[ye[t],e.copy])),xe=()=>a.delivered(_,n.by,be);f.observe(_,h,he.rows.some(e=>e.kind===`menu`),S.menuTimeout);let Se=f.since(_,h);c6(g,{menuIdle:Se===void 0?`-`:`${(h-Se).toFixed(1)}s/${S.menuTimeout}s`});let Ce=l.drawn(_,n.by,se,de),we={width:te,rows:SC(ee.termRows,n.by===`feed`?ox.flatMap(e=>{let t=ax[e].rows;return C[e]&&t!==null?[t]:[]}):[]),colorCompatibility:he.depth},Te=xC(r.get(_,Vi),ce),Ee=Te===null?he:ES(he,CC(ce,Te,_,n.by,we)),De=u.gitProvider.getStats(),Oe=u.usageStore.getStats(),ke=pe.lastFrame(),Ae=ke.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,je=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,Me=e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`file-events`:return`${e.kind}:${e.state}`;case`load`:case`config-watch`:case`lifeline`:case`when`:return e.kind}},Ne=[...oe,...de].map(Me).join(`,`)||`-`;return c6(g,{git:`${De.size}/${De.hits}h/${De.misses}m`,usage:`${Oe.size}/${Oe.hits}h/${Oe.misses}m`,effect:ke.effect,effectT:ke.t.toFixed(3),speed:`${ke.speed}x`,effectRows:`${ke.made}made/${ke.reused}reused`,effectOwn:Ae,fadeBasis:ke.basis,stateRev:String(ke.revision),fades:je(ke.fades),leaves:je(ke.leaves),motion:Ee.motion,evaluated:String(ge),cellBreaks:String(_e),pending:Ee.pending.join(`,`)||`-`,rules:[...ve].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:O.length>0?`Y`:`N`,clickError:ne.kind===`none`?`-`:ne.kind,upd:String(re.length),ask:String(E.length),warn:Ne,diag:String(ce.length),warnRecord:Ce?`new`:`kept`,viewer:Te===null?`-`:`${Te.index}/${ce.length}p${Te.page+1}`}),{drawn:{body:Ee,viewerOpen:Te!==null,diagnostics:ce,geometry:we},evaluated:ge,cellBreaks:_e,clickShown:T,delivered:xe,lanes:C}}function w6(e,t){let{sessionState:n}=e,r=t.sessionId,{client:i,...a}=t.hints,o=JSON.stringify(a);n.get(r,`client-hints`)!==o&&n.set(r,$1,o);let s=w1(t.requested);n.get(r,`render-origin`)!==s&&n.set(r,S1,s)}async function T6(e,t,n,r,i){return w6(e,t),k6(e,t,n,r,i)}function E6(e,t,n){let{laneSetups:r,tmuxStatusLines:i}=e;r.noted(D6(e,t),n),i.observe(t.hookData.session_id,t.hints.tmux,n.tmuxStatus)}function D6(e,t){let{sessionState:n}=e,r=t.hookData.session_id;return{sessionId:r,hints:t.hints,origin:C1(t.requested,n,r),transcript:t.hookData.transcript_path,answered:DF(t.hookData)}}function O6(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);a.clicked(t,s===null?null:D6(e,s),n,r),s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus)}async function k6(e,t,n,r,i){try{var a=jo();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(b6(e,t,n,i));E6(e,t,SK(l.view.source.effective(),Wc(t.hints.tmux)));let u=o.monotonic(),d=r-u;c6(i,{deadline:`${t.deadline.kind}:${Math.round(d)}ms`});let f=new Map,p=await EX(e=>Promise.all([fZ(l.payloadInputs,n,f),l.view.registry.inFlight(e)]),d,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${le(e)}`),o.after),m=o.monotonic();c6(i,{waited:`${Math.round(m-u)}ms`,ended:p,refreshed:ZX(f)});let{drawn:h,clickShown:g,delivered:_,lanes:v}=C6(e,l,cx),y=t.sessionId,b=o6(v,s.following(y)),x=kF(t.hints.client??null)===`statusline`,S=m6[t.encoding](x?A6(y,h,b):h.body);return c6(i,{handoff:(x?b:[]).join(`,`)||`-`,drew:`${Math.round(o.monotonic()-m)}ms`}),{resp:S,motion:h.body.motion,clickShown:g,delivered:_}}catch(e){a.e=e}finally{a.d()}}function A6(e,t,n){let[r,...i]=n;return r===void 0||t.viewerOpen?t.body:ES(t.body,wC(s6(e,[r,...i]),t.diagnostics,e,t.geometry))}const j6=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`]),M6=[[`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`]],N6=[[`workspace.added_dirs`,`string-list`]];function P6(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of M6){let i=L6(n,e);if(i==null)t.missingRequired.push(e);else{let n=F6(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of N6){let i=L6(n,e),a=i===void 0?r:I6(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))j6.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function F6(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function I6(e){return Array.isArray(e)&&e.every(e=>F6(e)===`string`)?`string-list`:F6(e)}function L6(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 R6(e,t){let{tokens:n}=ue({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=(n??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),i=(n??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===r&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:xF(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function z6(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=Ft.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${Ft.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function B6(e,t,n){let{report:r}=P6(e.hookData),i=[];for(let e of r.missingRequired)i.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of r.typeMismatches)i.push(`field '${e}' expected ${t}, got ${n}`);let a=e1(e.hookData?.session_id);a.ok||i.push(`field 'session_id' ${a.problem}`),(typeof e.cwd!=`string`||!l(e.cwd))&&i.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&i.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let o=z6(e.encoding);o.ok||i.push(o.problem);let s=sn(e.deadline);if(s.kind===`refused`)return{ok:!1,problems:[...i,s.problem]};if(i.length>0||!a.ok||!o.ok)return{ok:!1,problems:i};for(let e of r.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let c=Lt(e),{configFile:u,refusedArgs:d}=R6(e.args,e.cwd);return{ok:!0,req:{...e,deadline:s,encoding:o.encoding,sessionId:a.id,hints:c,rateLimits:Ate(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:wF(u,c.configEnv)},refusedArgs:d}}}function V6(e,t){switch(e){case`vars`:return{what:e,vars:H6(t)};case`segments`:return{what:e,segments:q6(t)};case`config`:return{what:e,config:Z6(t)}}}function H6(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=G6(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=U6(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:W6(r.lastUpdatedMs())})}return o}function U6(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 W6(e){return e===null?null:Math.max(0,Date.now()-e)}function G6(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,K6(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}`,K6(i));return t}function K6(e){return e.kind}function q6(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=Y6(n),o=J6(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:X6(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function J6(e){let t=new Map;for(let n of Tw(e.presets))for(let r of nb(Ow(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=Qy(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function Y6(e){let t=[],n=new Set;for(let r of nb(pw(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 X6(e,t,n){let r=new Set([...cT(e,t).keys()].flatMap(e=>gT(e,n)));return Array.from(r).sort()}function Z6(e){return e===null?null:e.config}const Q6=[`vars`,`segments`,`config`];function $6(e){return typeof e==`string`&&Q6.includes(e)}const e8=e=>({resp:e,exitAfterFlush:null,delivered:f6}),t8=e=>({kind:`reply`,...e}),n8={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},r8=(e,t)=>t8(e8({ok:!1,error:t,code:e,daemonV:3}));function i8(e){let t=e1(e.sessionId);if(!t.ok)return r8(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return r8(`VERSION_MISMATCH`,`this client's subscribe names no lane (${ox.join(`, `)}): it predates the lane toggles — update it`);let n=mx(e.lane);return n===null?r8(`BAD_REQUEST`,`subscribe needs a lane, one of ${ox.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function a8(e,t,n,r,i){return!t||typeof t!=`object`||typeof t.v!=`number`?r8(`BAD_REQUEST`,`malformed request`):t.v===3?t.kind===`subscribe`?i8(t):typeof t.kind!=`string`||!Object.hasOwn(n8,t.kind)?r8(`BAD_REQUEST`,`unknown kind`):t8(await o8(e,t,n,r,i)):(t.v>3?e.log(`info`,`version mismatch: client=${t.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):e.log(`info`,`version mismatch: client=${t.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${t.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:t.v>3?0:null,delivered:f6})}async function o8(e,t,n,r,i){let{stats:a,clock:o,frameFeeds:s,renderCache:c,payloadProviders:{gitProvider:l,usageStore:u},fileEvents:d,runs:f,effectSessions:p,menuIdle:m,journalTurns:h,sessionState:g,tmuxStatusLines:_,watcherRegistry:v,limits:y,handlerProbes:b,renderSightings:x,bundle:S,sourceDigest:C,doctorStores:ee}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:f6};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return e8(typeof e!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:s.newestWhere(({hints:{tmux:t}})=>t!=null&&t.socket===e&&t.pane===n)})}if(t.kind===`stats`)return e8({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:s8(e),fileEvents:d.stats(),runs:f.stats(),transcriptReads:zo(),renderCache:c.stats,effectCache:p.getStats(),menuIdle:m.getStats(),journalTurns:h.getStats(),sessionState:{sessions:g.size(),observers:g.observers(),revision:g.latestRevision()},frameFeeds:s.getStats(),tmuxStatus:_.stats(),watchersActive:v.size(),dirWatchesActive:v.dirWatches(),nextRestartReason:y.describeNextRestart(),handlerProbes:b.list(),clients:x.list(GM(o.date())),bundle:S,sourceDigest:C,daemon:y.serving(),doctorStores:IQ(ee)})});if(t.kind===`render`){let c=o.date(),l=GM(c),u=o.monotonic(),d=Math.round(u-r),f=[],p=++a.requestsTotal,m=B6(t,a,e.log),h=(e,t)=>x.see(e.sessionId,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:Xo(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:jte(e.hookData),frame:t},l,p);m.ok&&(h(m.req,`drawing`),s.note(m.req.sessionId,m.req,p));let _=m.ok?await T6(e,m.req,l,u+cn(m.req.deadline,r,{epochMs:c.getTime(),monoMs:u}),f).then(({resp:e,motion:t,clickShown:n,delivered:r})=>(h(m.req,t),{outcome:{kind:`ok`},resp:e,delivered:()=>{r(),n!==null&&eee(g,m.req.sessionId,n)}}),e=>(h(m.req,`failed`),{outcome:{kind:`threw`,error:e},resp:p6(e),delivered:f6})):g8(m.problems);_.outcome.kind!==`ok`&&a.requestsErrored++,c6(f,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:v,line:y}=d6(`render`,f,_.outcome,Math.round(o.monotonic()-u));return e.log(v,y),{resp:_.resp,exitAfterFlush:null,delivered:_.delivered}}if(t.kind===`click`){let a=o.monotonic(),s=[[`queued`,`${Math.round(a-r)}ms`]],c=await d8(e,t,s,()=>n()||i());c6(s,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`});let{level:l,line:u}=d6(`click`,s,c,Math.round(o.monotonic()-a));return e.log(l,u),e8(m8(c))}if(t.kind===`debug`){if(!$6(t.what))return e8({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${Q6.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`?u8(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??Wx(`colorCompatibility`)):l8};return e8({ok:!0,debug:V6(t.what,n)})}throw Error(`no reply for request ${le(t)}`)}function s8(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 c8={endcaps:Wx(`endcaps`),colorCompatibility:Wx(`colorCompatibility`),wrap:Wx(`autoWrap`),padding:Wx(`padding`),width:1/0},l8=new Map;function u8(e,t){let n=new Map;for(let[r,i]of e)n.set(r,rC(i,{...c8,colorCompatibility:t}));return n}async function d8(e,t,n,r){let{verb:i,value:a}=t;if(typeof i!=`string`||typeof a!=`string`)return{kind:`bad-request`,problems:[`a click's verb and value are strings, got ${typeof i} and ${typeof a}`]};try{return await p8(e,i,a,{via:`link`,handler:qt(t.clientVersion)},n,r)}catch(e){return e instanceof Y?{kind:`bad-request`,problems:[e.message]}:e instanceof JC?{kind:`closing`,error:e}:e instanceof YC?{kind:`abandoned`,error:e}:{kind:`threw`,error:e}}}const f8={link:`verb`,"tmux-status":`linkVerb`};async function p8(e,t,n,r,i,a){let{menuIdle:o,verbCtx:s}=e;if(t===`tmux-status-click`)return c6(i,{verb:t}),h8(e,n,i,a);let c=E0.get(t);if(!c)return{kind:`bad-request`,problems:[`unknown click verb: ${t}`]};c6(i,{[f8[r.via]]:t});let l=_0(t,n),u=l?.ok?l.id:null;l===null?c6(i,{sid:`-`}):u!==null&&(c6(i,{sid:u}),o.clickArrived(u));try{await c(n,{...s,arrival:r,placeWaited:e=>c6(i,{placeWait:`${e}ms`}),gatherTook:e=>c6(i,{gather:`${e}ms`}),turnWaited:e=>c6(i,{turnWait:`${e}ms`}),clientGone:a})}finally{u!==null&&o.clickSettled(u)}return{kind:`ok`}}function m8(e){switch(e.kind){case`ok`:return{ok:!0,output:``};case`bad-request`:return{ok:!1,error:e.problems.join(`; `),code:`BAD_REQUEST`,daemonV:3};case`threw`:case`closing`:case`abandoned`:return p6(e.error)}}async function h8(e,n,r,i){let{tmuxStatusLines:a}=e,o=e=>({kind:`bad-request`,problems:[e]}),s=a.linkAt(n);if(s.kind===`refused`)return o(s.reason);if(c6(r,{link:s.url}),s.url.startsWith(`cc-candybar://`)){let t=XC(()=>zs(s.url));return t.verb===`tmux-status-click`?o(`a status-line link names another status-line click`):p8(e,t.verb,t.value,{via:`tmux-status`},r,i)}return await s1(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,i1),{kind:`ok`}}const g8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:f6});function _8(e,t){try{return F(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?I:L(e.message)}}function v8(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function y8(e){let{targets:t,intervalMs:n,stat:r,held:i,exit:a,log:o}=e,s=Fe(o),c=t.map(e=>({path:e,stamp:_8(e,r)})),l=c.filter(({stamp:e})=>e.kind!==`failed`),u=null,d=!1,f=()=>{d=!0,u&&clearInterval(u)},p=async()=>{if(!d)for(let{path:e,stamp:t}of l){let n=_8(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!v8(t,n)){let t=`binary ${n.kind===`absent`?`gone`:`changed`} (${e})`,r=await i();if(d)return;if(r){s([`info`,`${t}; the restart waits for the running update`]);return}o(`info`,`${t}; shutting down`),f(),a();return}}},m=()=>p().catch(e=>{o(`error`,`binary check failed: ${e.message}`)});return{arm(){for(let{path:e,stamp:t}of c)t.kind===`failed`&&o(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);u=setInterval(()=>void m(),n),u.unref()},checkNow:m,close:f}}function b8(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var x8=class{timer=null;state=`released`;last=null;constructor(e,t=Date.now){this.tick=e,this.now=t}landed(e,t=this.now()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.now());this.timer=setTimeout(()=>{this.timer=null,this.tick()},e),this.timer.unref?.()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};const S8=`pass`,C8={okMs:5*6e4,failedMs:45e3};function w8(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function T8(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function E8(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function D8(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:o.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>Yc(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${Xc(i[t])}`).join(`|`)}`,targets:{dirs:r},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function O8(e){return e.find(e=>e.kind===`ok`)?.value.branch}function k8(e){e.missed=!0,bX(e,`unread`)}function A8(e,t){return e.missed&&e.reading.get().kind===`pending`&&yX(e,t.size>0?L([...t].join(`; `)):I),`unkeyed`}function j8(e,t){let n=CX(e);return t===null||n.kind!==`ok`?n:F({...n.value,pullRequest:CX(t)})}function M8(e){return t=>L(`${e} threw: ${String(t)}`)}var N8=class{repos=new Map;resolutions=new Map;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;watchers;ownsWatchers;logger;constructor(e){this.inner=e.inner,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Ie;let t=e.ledger??new yN(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 OT({logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=L(`resolver threw: ${String(e)}`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`not-a-repo`)return DX(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>j8(a,o)}}asked(e,t,n,r){let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`not-a-repo`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n={root:e,refresh:new _N,watch:this.followWatch(e,null).watch,period:new x8(()=>{n.refresh.share(S8,()=>this.refreshPass(n))}),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,n),n}followWatch(e,t){let n=this.inner.resolveGitDir(e),r=D8(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(S8,()=>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&&k8(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(S8,()=>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:_X(),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=E8(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(T8(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}async pass(e){if(this.repos.get(e.root)!==e)return;let t=Date.now(),n=[...e.asked];e.asked.clear();let r=this.followWatch(e.root,e.watch);e.watch=r.watch;let i=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?i.push(t):t.missed=!0;let a=e.pr,[o,s]=await Promise.all([Promise.all(i.map(t=>this.inner.getGitInfo(e.root,t.options).catch(M8(`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,yX(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of VY(n.value))c.add(e)});let l=O8(o),u=a===null||i.length===0?`-`:l===void 0?A8(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}`,w8(n),c.size===0?F(null):L([...c].join(`; `)),Date.now()-t)}prSource(e){let t={period:new x8(()=>{this.readPr(e,t,`period`)}),seen:new Map,holders:0,missed:!0,key:``,remote:I,reading:_X(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(M8(`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?(k8(t),`owed`):(bX(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,yX(t,a.outcome),t.period.landed(b8(C8,a.outcome),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=Date.now(),o=(i.kind===`ok`?this.inner.resolvePullRequest(e.root,i.value).catch(M8(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:I)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${R(r)}`,n,i,Date.now()-a);let o=Date.now();t.seen.delete(r),t.seen.set(r,{outcome:i,at:o});for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==r||t.missed||(yX(t,i),t.period.landed(b8(C8,i),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=L(`git state dropped: ${e.root}`);for(let n of e.values.values())xX(n,t);e.pr!==null&&xX(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watch.handle.release(),e.period.dispose(),e.pr?.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},P8=class{static CACHE_DIR=ht();static USAGE_CACHE_DIR=o.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=o.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=o.join(this.LOCKS_DIR,e);if(!f.existsSync(t))return!1;try{let n=f.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return k(`Invalid PID in lock file ${e}, removing stale lock`),f.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(k(`Removing stale lock file ${e} for dead process ${r}`),f.unlinkSync(t),!1):(k(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return k(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=o.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await f.promises.writeFile(n,i,{flag:`wx`}),k(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await xe(50);else throw e}return k(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=o.join(this.LOCKS_DIR,e);try{await f.promises.unlink(t),k(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&k(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([f.promises.mkdir(this.CACHE_DIR,{recursive:!0}),f.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),f.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){k(`Failed to create cache directories:`,e)}}static createProjectHash(e){return w(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=o.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){k(`Cache for ${e} is locked, waiting...`),await xe(75);continue}try{let r=await f.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(k(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(k(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return k(`No shared ${e} usage cache found`),null;k(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await xe(75)}}return k(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){k(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=o.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await f.promises.writeFile(r,i,`utf-8`),k(`[CACHE-SET] ${e} disk cache stored`)}catch(t){k(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const F8={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var I8=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await P8.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await P8.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=be({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){k(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){k(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(k(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),k(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(k(`Invalid pricing data structure`),e(null))}catch(t){k(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{k(`Response error:`,t),e(null)})});r.on(`error`,t=>{k(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{k(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return k(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return k(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),k(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(k(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(F8).length} models`),this.executionCache=F8,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(F8).length} models`),F8)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return k(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),k(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}},L8=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}},R8=class{entries=new Map;refreshes;constructor(e){this.spec=e,this.refreshes=e.ledger.declare({name:e.name,scope:e.scope,refresh:e.every===null?[`first`,`change`,`supersede`]:[`first`,`period`,`change`,`supersede`]})}declare(e,t){let n=this.spec.keyOf(t),r=this.touched(n)??this.firstRead(this.created(n,t));return e.take(`${this.spec.name}:${n}`,()=>this.hold(r)),{current:()=>CX(r)}}supersede(e){let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,bX(n,`superseded`),n.flight=null,n.changed=!1,this.evict();let r=!1;return()=>{r||(r=!0,n.superseding--,this.entries.get(n.key)===n&&this.refresh(n,`supersede`))}}changed(e){for(let t of this.entries.values())t.holders>0&&e(t.input)&&this.refresh(t,`change`)}isHeld(e){for(let t of this.entries.values())if(t.holders>0&&e(t.input))return!0;return!1}stats(){let e=0;for(let t of this.entries.values())t.holders>0&&e++;let{refreshes:t,failures:n,lastMs:r}=this.refreshes.record();return{entries:this.entries.size,held:e,refreshes:t,failures:n,lastMs:r}}close(){for(let e of[...this.entries.values()])this.drop(e)}touched(e){let t=this.entries.get(e);if(t!==void 0)return this.entries.delete(e),this.entries.set(e,t),t}created(e,t){let n={key:e,input:t,reading:_X(),holders:0,flight:null,changed:!1,superseding:0,revisit:z8(this.spec.every,{period:()=>this.refresh(n,`period`),holdReturned:()=>this.refresh(n,`change`)})};return this.entries.set(e,n),n}firstRead(e){return this.refresh(e,`first`),e}refresh(e,t){if(e.superseding>0)return;if(e.flight!==null){e.changed||=t===`change`;return}let n={};e.flight=n;let r=Date.now();V8(()=>this.spec.read(e.input)).then(i=>{let a=e.flight===n;try{this.refreshes.recorded(`${this.spec.fields(e.input)} stored=${a?`Y`:`N`}`,t,i,Date.now()-r)}finally{a&&this.store(e,i)}}).catch(t=>{this.spec.logger(`error`,`${this.spec.name} refresh threw (${this.spec.fields(e.input)}): ${String(t)}`)})}store(e,t){e.flight=null;try{yX(e,t)}finally{e.revisit.landed(t),e.changed&&(e.changed=!1,this.refresh(e,`change`))}}hold(e){return e.holders++,e.revisit.hold(!0),this.evict(),()=>{e.holders--,e.revisit.hold(e.holders>0)}}evict(){for(let e of[...this.entries.values()]){if(this.entries.size<=this.spec.maxEntries)return;e.holders===0&&e.superseding===0&&this.drop(e)}}drop(e){this.entries.delete(e.key),e.flight=null,e.revisit.dispose(),xX(e,L(`${this.spec.name} entry dropped`))}};function z8(e,t){if(e===null)return new B8(t.holdReturned);let n=new x8(t.period);return{landed:t=>n.landed(b8(e,t)),hold:e=>n.hold(e),dispose:()=>n.dispose()}}var B8=class{state=`released`;answered=!1;constructor(e){this.reread=e}landed(){this.answered=!0}hold(e){if(this.state===`disposed`)return;let t=e&&this.state===`released`&&this.answered;this.state=e?`held`:`released`,t&&this.reread()}dispose(){this.state=`disposed`}};function V8(e){let t=e=>L(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function H8(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const U8={okMs:60*1e3,failedMs:10*1e3},W8={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},G8={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function K8(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function q8(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function J8(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const Y8={entries:0,cost:0,breakdown:J8(),days:new Map};async function X8(e,t){let n=K8(new Date(q8())),r=e.entries,i=e.cost,a={...e.breakdown},o=new Map;for(let[t,r]of e.days)t>=n&&o.set(t,{...r});for(let e of t){let t=e.message?.usage;if(!t)continue;r++;let s=e.costUSD??await I8.calculateCostForEntry(e.raw);i+=s,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0;let c=K8(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...W8};l.cost+=s,l.input+=t.input_tokens||0,l.output+=t.output_tokens||0,l.cacheCreation+=t.cache_creation_input_tokens||0,l.cacheRead+=t.cache_read_input_tokens||0,o.set(c,l)}return{entries:r,cost:i,breakdown:a,days:o}}function Z8(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function Q8(e){let t=0,n=0,r=J8(),i=new Map;for(let{value:a}of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...W8};Z8(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:G8,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}function $8(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function e5(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!$8(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...W8};Z8(r,t),n.set(e,r)}return n}async function t5(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 n5(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function r5(e,t){(0,X.runInAction)(()=>e.set(t))}var i5=class{sessions=X.observable.map(void 0,{deep:!1});flight=new L8;scans;daySets=new Map;speedFlight=new L8;requestFlight=new L8;staleAgeMs;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;sweepTimer=null;constructor(e={}){this.log=e.logger??Ie,this.ledger=e.ledger??new yN(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new R8({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${R(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??U8,maxEntries:8,logger:this.log,ledger:this.ledger});let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps}}scanStats(){return this.scans.stats()}getUsageInfo(e,t){return this.request(e,t?.transcript_path).usage(t)}request(e,t){let n=null,r=()=>{if(n!==null)return n;let r=Mo(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(n5(t.kind===`ok`?t.value.sessionInfo:G8,e))},speed:t=>this.observed(e,r,t),today:async e=>{await OX(e),await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return ko;let r=n.failure.get();return r===null?F(n5(n.record?.sessionInfo??G8,t)):L(r)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=Date.now(),a=await this.ingest(e,t,r,n);return this.renderTally.hits+=r.hits,this.renderTally.misses+=r.misses,r.misses>0&&this.usage.recorded(`sid=${R(e)}`,`request`,a,Date.now()-i),r5(this.hold(e).failure,a.kind===`failed`?a.reason:null),a})}refreshToday(e,t){return this.request(t?.session_id??``,t?.transcript_path).today(e)}declareToday(e,t){let n=EZ(t),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?F({roots:i.roots,sums:i.sums.read()}):e}}}todayAt(e,t,n){let r=this.sessions.get(t?.session_id??``),i=r?.failure.get()??null;if(i!==null)return L(i);let a=K8(KM(n)),o={...W8},s=e.sums.get(a);s!==void 0&&Z8(o,s);let c=$8(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&Z8(o,c),s===void 0&&c===void 0?I:F({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:a})}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return I;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return r5(this.hold(e).speed,t),t;let r=H8(t.kind===`ok`?t.value.sessionInfo.tokenBreakdown:null,n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=F({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return r5(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??ko:I}async ingest(e,t,n,r){if(!e)return I;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,F(i);if(!t)return i?F(i):I;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,sessionInfo:s.value.sessionInfo,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),F(c)):l===void 0?F(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,X.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[],failure: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=>u(e,`projects`)+d),i={roots:r,sums:new BT(`today over ${e.join(`,`)}`,()=>e5(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await kZ(e,c(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of RZ(r.longLines))this.log(`info`,e);let i=new Map,a=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),o=await zZ(e,r,Y8,X8);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{folded:s,longLines:c}=o.value;for(let e of RZ(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...Q8(i),mainStamp:a})}async scan(e){try{let t=q8(),n=await DZ(e),r=[];for(let e of n){let n=await OZ(Io(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=u(e,i),a=await OZ(Lo(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:No(a)})}}let i=[],a={hits:0,misses:0};return await t5(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,a,e.stamp);t.kind===`failed`&&(i.push(t.reason),this.log(`warn`,`usageStore scan: ${t.reason}`))}),this.log(`info`,`usageStore scan dirs=${R(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?L(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`):F({sessions:r.length,read:a.misses})}catch(e){return L(`usage scan: ${e instanceof Error?e.message:String(e)}`)}}sweepStale(){let e=Date.now(),t=K8(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.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.scans.close(),(0,X.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},a5=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)}})}},o5=class{sessions;constructor(e,t,n,r=Ie,i=256){this.empty=e,this.step=t,this.refreshes=n,this.log=r,this.sessions=new a5(i)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=Mo(t);if(n?.folded&&i!==``&&n.folded.cursor.stamp===i){let{folded:t,answer:r}=n;return r.kind===`ok`&&r.value===t.value?(this.sessions.touch(e),r):this.store(e,t,{kind:`ok`,value:t.value})}let a=Date.now(),o=await zZ(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${R(e)}`,`request`,o,Date.now()-a),o.kind===`failed`)return this.store(e,r,o);if(o.kind===`absent`)return this.store(e,r,{kind:`ok`,value:r?.value??this.empty});let{folded:s,longLines:c}=o.value;for(let e of RZ(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??ko}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function s5(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 c5=class{fold;constructor(e={}){let t=e.logger??Ie;this.fold=new o5(void 0,s5,(e.ledger??new yN(t)).declare({name:`context`,scope:`session`,refresh:[`request`]}),t)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return k(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);k(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){return this.contextFrom(await this.fold.read(e,t),n)}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t?F(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,l5(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,l5(e))}contextFrom(e,t){if(e.kind===`failed`)return L(`context transcript: ${e.reason}`);let n=e.value;return n===void 0?(k(`No main chain entries with usage data found`),I):(k(`Most recent main chain context: ${n} tokens (limit: ${t})`),F({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function l5(e){return e.context_window?.context_window_size??2e5}const u5={messageCount:0,nonPrompts:0,recent:[]},d5=new Set([`turn`,`interrupt`,`claude-code`]);function f5(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!d5.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function p5(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 m5=class{fold;constructor(e={}){let t=e.logger??Ie;this.fold=new o5(u5,f5,(e.ledger??new yN(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),t)}async getMetricsInfo(e,t){k(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?h5(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:h5(e,n,r)}};function h5(e,t,n){return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`):F({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:p5(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 g5={command:null,todos:[],pending:[],done:[]};function _5(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 v5(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 y5(e,t){if(t.isSidechain)return e;let n=v5(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=_5(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 b5(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>_5(e,t.name),[]),done:e.done}}var x5=class{fold;constructor(e={}){let t=e.logger??Ie;this.fold=new o5(g5,y5,(e.ledger??new yN(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),t)}async getActivityInfo(e,t){return S5(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:S5(e,t)}};function S5(e,t){return t.kind===`failed`?L(`activity (${e}): ${t.reason}`):F(b5(t.value))}const C5=3e4;var w5=class{names;constructor(e){let t=e.logger??Ie;this.names=new R8({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${R(e.pane)} socket=${R(e.socket)}`,read:t=>T5(e.launcher,t),every:{okMs:C5,failedMs:C5},maxEntries:64,logger:t,ledger:e.ledger??new yN(t)})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function T5(e,t){let n=await _c(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return L(n.reason);let r=n.stdout.trim();return r?F(r):I}const E5=6e4,D5={okMs:E5,failedMs:E5};function O5(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function k5(e,t){try{let e=t();return Promise.resolve(e===``?I:F(e))}catch(t){return Promise.resolve(L(`host.${e}: ${String(t)}`))}}var A5=class{name;user;constructor(e={}){let t=e.logger??Ie,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:D5,maxEntries:1,logger:t,ledger:e.ledger??new yN(t)};this.name=new R8({...n,name:`host.name`,read:()=>k5(`name`,()=>O5(D.hostname()))}),this.user=new R8({...n,name:`host.user`,read:()=>k5(`user`,()=>D.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()}},j5=class{known=new a5(64);refreshes;constructor(e=Ie,t=new yN(e)){this.refreshes=t.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=M5(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=Date.now(),i=EL(e);return this.refreshes.recorded(`path=${R(e)} stamp=${R(t)}`,`request`,i,Date.now()-r),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??ko}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}};function M5(e){try{let t=f.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:No(t)}catch(e){return`unread:${e.code??`error`}`}}const N5=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function P5(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 F5=class{known=new a5(256);refreshes;constructor(e=Ie,t=new yN(e)){this.refreshes=t.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=Mo(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??ko}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}async read(e,t,n){let r=Date.now(),i=await I5(t);return this.refreshes.recorded(`sid=${R(e)} stamp=${R(n)}`,`request`,i,Date.now()-r),i}};async function I5(e){let t=await L5(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function L5(e){for(let t of[65536,1048576]){let n=await Ko(e,t);if(n.kind!==`ok`)return n;let r=R5(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function R5(e,t){let n=e.toString(`utf8`).split(`
|
|
485
|
-
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!N5.test(t))continue;let r=P5(t);if(r!=null)return r}return null}var z5=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)}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)})}};const B5=e=>qU(e),V5=e=>o.join(e.storage.folder,B5(e.sessionId)),H5=e=>JSON.stringify([e.folder,e.generation]),U5=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var W5=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;identityOf;fileEvents;unsubscribe;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??Kc,this.fileEvents=e.fileEvents,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new R8({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${R(V5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new yN(e.logger)})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{f.mkdirSync(e,{recursive:!0}),n=this.identityOf(e)}catch(e){t.unusable=`could not be created or read: ${e.message}`}return(t.lost||t.identity!==null&&(n===`gone`||!qc(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${R(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(H5(e))??this.opened(e);t.holders++;let n=!1;return()=>{n||(n=!0,t.holders--,t.holders===0&&this.closed(t))}}declare(e,t,n){return this.sessions.declare(e,{storage:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({storage:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost}}close(){this.unsubscribe(),this.sessions.close();for(let e of[...this.watched.values()])this.closed(e)}recorded(e){let t={generation:0,identity:null,lost:!1,unusable:null};return this.folders.set(e,t),t}opened(e){let t=this.folders.get(e.folder);if(t===void 0)throw Error(`plugin storage: no key was asked for ${e.folder}`);let n=e.generation===t.generation?t.unusable:null,r=n===null?this.identityOf(e.folder):`gone`;e.generation===t.generation&&(t.identity=r===`gone`?null:r);let i={key:e,folder:t,identity:r,holders:0,handle:this.watchers.acquire(`plugin-storage:${H5(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),sweep:setInterval(()=>void this.sweep(e),864e5),health:{kind:`watching`}};i.sweep.unref(),this.watched.set(H5(e),i),n!==null&&this.faulted(i,`unusable`,n);for(let e of i.handle.deaf)this.faulted(i,`refused`,e.reason);return this.sweep(e),i}closed(e){let t=H5(e.key);this.watched.delete(t),e.health={kind:`closed`},clearInterval(e.sweep),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>U5(e.storage,n);switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.has(o.join(n.folder,o.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(V5(e)));return}case`failed`:this.judged(e,()=>this.faulted(e,`error`,t.reason));return}}judged(e,t){let{health:n}=e;if(n.kind!==`watching`)return;let{key:r,folder:i}=e,a;try{a=this.identityOf(r.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let o=e.identity;if(a!==`gone`&&o!==`gone`&&qc(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${R(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>U5(e.storage,r)))}faulted(e,t,n){let{key:r,folder:i}=e;e.health.kind===`watching`&&(e.health={kind:`faulted`,reason:n},this.faultCounts[t]++,r.generation===i.generation&&(i.lost=!0),this.logger(`warn`,`plugin storage fault folder=${R(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>U5(e.storage,r)))}noticed(e){switch(e.kind){case`period`:for(let e of[...this.watched.values()])this.judged(e,()=>{});return;case`moved`:case`caught-up`:this.sessions.changed(()=>!0);return}}standing(e){let t=this.watched.get(H5(e));if(t===void 0)return null;let{health:n}=t;switch(n.kind){case`faulted`:return`cannot refresh: ${e.folder} ${n.reason}; reload the config or restart the daemon`;case`watching`:case`lost`:{let t=il(this.fileEvents.delivery());return t===null?null:`cannot refresh: ${e.folder}: ${t}`}case`closed`:return null}}async read(e){let t=this.standing(e.storage);if(t!==null)return L(t);let n=V5(e),r;try{r=await f.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?I:L(`${n}: ${t.message}`)}if(r.trim()===``)return I;let i=gN(r);return i.kind===`failed`?L(`${n}: ${i.reason}`):i}async sweep(e){let t=Date.now(),n=t-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${R(e.folder)} scanned=${r} removed=${i} took=${Date.now()-t}ms`;try{let t=await f.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=o.join(e.folder,a.name);try{let{mtimeMs:r}=await f.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&B5(t.sessionId)===a.name);if(r>=n||o)continue;await f.promises.unlink(t),i++}catch(e){if(e.code!==`ENOENT`)throw e}}this.logger(`info`,a())}catch(e){this.logger(`warn`,`${a()} outcome=failed reason=${JSON.stringify(e.message)}`)}}};function G5(e){let{launcher:t,logger:n,ledger:r}=e;return{hostService:new A5({logger:n,ledger:r}),gitProvider:new N8({inner:new hX(t),watchers:e.watchers,logger:n,ledger:r}),usageStore:new i5({logger:n,ledger:r}),contextProvider:new c5({logger:n,ledger:r}),metricsProvider:new m5({logger:n,ledger:r}),activityProvider:new x5({logger:n,ledger:r}),tmuxService:new w5({launcher:t,logger:n,ledger:r}),autoCompact:new j5(n,r),cacheExpiry:new F5(n,r),managedStorage:new W5({watchers:e.watchers,fileEvents:e.fileEvents,logger:n,ledger:r}),faults:new z5,log:e.logger}}function*K5(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*q5(e){for(let t of Object.values(e.segments)){for(let e of[t.template,t.bg,t.fg,t.when])e!==void 0&&(yield e);yield*Object.values(t.partials??{})}for(let t of Tw(e.presets)){for(let n of nb(Ow(e,t).node))n.when!==void 0&&(yield n.when);let n=jw(e,t);for(let e of yy){let t=n[e];by(t)&&(yield t)}}for(let[,t]of K5(e))for(let[,e]of db(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of Hw(t))yield e}function J5(e,t,n){let r=jU(t),i=new Set,a=new Set,o=new Set;for(let e of q5(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of dT(e,t.helpers))a.add(n);for(let n of tte(e,t.helpers))o.add(n)}for(let[,e]of K5(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 Tw(t.presets))for(let n of nb(Ow(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=>!Li(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(K5(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 Y5(e){return w(`sha256`).update(JSON.stringify(e)).digest(`hex`)}var X5=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 Z5(e){return Math.floor(Math.max(e/4,e*Hr-67108864))}const Q5={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function $5(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[KU(Kw(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[Kw(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>qw(e)(t)&&t!==KU(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${EF(e,`<default>`)}: projections=${[...FU(n).keys()].join(`,`)||`-`} instantSegments=${U3(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 e7=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},t7=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${e7(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function n7(e,t,n){let r=e=>R(e.join(`,`)||`-`);return`config loaded projectDir=${R(e.projectDir)} cwd=${R(e.cwd)} cause=${R(t7(t))} state=${n} files=${R(EF(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 r7(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function i7(e,t,n){return e+`\0`+t+`\0`+(n??``)}function a7(e,t){return new Set(Tw(e.presets).filter(n=>Ow(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function o7(e){let{loaded:t,dropped:n,unreached:r}=e.state.plugins,i=[...new Set([...e.state.plugins.roots,o.join(e.projectDir,lG)])];return xT({named:[...TG(e.projectDir,e.cwd,e.configFile),...i,...t.map(e=>e.path),...[...n,...r].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))],whole:i})}function s7(e){return e.filter(Boolean).join(`
|
|
486
|
-
`)||null}const c7=e=>e instanceof Error?e.message:String(e);function l7(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function u7(e){let{loaded:t,chain:n}=e;return Y5({cwd:e.cwd,chain:{layers:n.layers,home:n.home,repo:n.repo},loaded:{layers:t.layers.map(e=>({path:e.path,raw:e.raw,config:e.config,plugins:l7(e.plugins),source:null,warnings:null})),base:t.base,installed:{...l7(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 d7(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 f7(e,t,n){let r=[];try{let i=WG(t.layers,gK,{warned:e=>r.push(...e)},{repo:t.repo,cwd:e}),a={cwd:e,chain:t,loaded:i,sources:d7(i.config,n)};return{kind:`resolved`,...a,key:u7(a),warnings:r}}catch(e){return e instanceof Cb&&r.push(...e.warnings),{kind:`failed`,cause:e,warnings:r}}}function p7(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??gK,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new XT,m=new RN(t.launcher,p,o.globals.default_empty_value??``,t.sessionState,null,t.ledger,t.fileEvents,t.watchers),h;try{h=L3(o,m,n,t.compile??I3(t.signer),v7),f.push(...h.loadWarnings);let r=m.view();f.push(...B3(o,r,n,y7)),r.dispose(),sq(o),uB(o);for(let n of new Set(e.sources.values()))m.own(t.storage.watch(n))}catch(e){return m.dispose(),e instanceof Cb&&f.push(...e.warnings),{kind:`failed`,cause:e,warnings:f}}return{kind:`built`,state:{config:o,dropped:c,compileKey:h.compileKey,loadKey:e.key,buildWarnings:f,store:p,registry:m,compiled:h.compiled,neededInputPaths:UX(o),authoredRoots:a7(l,u),fileHeldSettings:qK(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>J5(e.raw,i.placed,d)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{checkout:s.checkout,roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering},sources:e.sources}}}function m7(e,t,n,r){let i={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:Math.round(performance.now()-e.started)},a=t=>s7([...e.advisories,...n,...t]);switch(r.kind){case`built`:case`kept`:return{...i,kind:r.kind,warning:a(r.state.buildWarnings),state:r.state,error:null};case`failed`:return{...i,kind:`failed`,warning:a(r.warnings),state:null,error:c7(r.cause),cause:r.cause}}}function h7(e,t,n,r,i=null){let a=f7(t,n,r.storage);if(a.kind===`failed`)return m7(e,n,[],a);let o=i?.loadKey===a.key?{kind:`kept`,state:i}:p7(a,r);return m7(e,n,a.warnings,o)}function g7(e,t,n,r,i=null){let a=performance.now(),o=kG(kq().read(),e,t,n),{repos:s}=o,c={layers:o.kind===`chain`?o.layers:[],home:o.home,repo:s.plugins};return h7({repos:s,advisories:[IG(e,t),PG(o),SG(s)],started:a},t,c,r,i)}function _7(e,t,n){let r=f7(e,{layers:[],home:``,repo:t},n.storage),i=r.kind===`failed`?r:p7(r,n);if(i.kind===`failed`)throw Error(`bundled default failed to load: ${c7(i.cause)}`,{cause:i.cause});return i.state}const v7=new Set([`directory`]),y7=new Set([`view`]);function Lte(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new X5;B3(e.config,l,t,y7);let d=()=>wK(e.config,e=>r.get(c,e)),f=(t,n)=>{try{let r=e.neededInputPaths(n),{result:{lanes:a,faults:o},acquired:l,released:d}=u.declare(()=>i(u,t,r,e.sources));for(let e of o)s(`error`,`session view declaration threw sid=${JSON.stringify(c)} ${e}`);return l+d>0&&s(`info`,`session view declared sid=${JSON.stringify(c)} acquired=${l} released=${d} held=${u.size}`),a}catch(t){return s(`error`,`session view declaration threw sid=${JSON.stringify(c)}: ${String(t)}`),eZ(L(`view declaration threw: ${String(t)}`),[...e.sources.keys()])}},p=(e,t)=>({facts:e,preset:t,lanes:f(e,t)}),m=X.observable.box(p(n,d()),{deep:!1}),h=(e,t)=>{let n=m.get();if(e===n.facts&&t===n.preset)return;let r=p(e,t);(0,X.runInAction)(()=>m.set(r))},g=(0,X.reaction)(d,e=>h(m.get().facts,e),{fireImmediately:!0}),_=a({sessionId:c,state:e,store:l.variableStore,declared:()=>m.get()});u3(e.compiled,l.variableStore,l,_);let v=(0,X.reaction)(()=>{let{sources:t,...n}=m.get().lanes;return[_.payload(),_.selections(),l.published(),e.registry.published(),...[...Object.values(n),...t.values()].map(e=>e.current())]},()=>o(c),{equals:X.compareShallow,fireImmediately:!0,onError:e=>s(`error`,`session view change threw sid=${JSON.stringify(c)}: ${String(e)}`)});return{sessionId:c,state:e,store:l.variableStore,registry:l,holds:u,source:_,requested:e=>h(e,d()),facts:()=>m.get().facts,lanes:()=>m.get().lanes,lastRenderCellsBySegment:new Map,retire:v,dispose:()=>(g(),v(),u.close(),l.dispose())}}var Rte=class{entries=new Map;answersWatch;sweep=null;closed=!1;holds=new Map;views=new Map;copies=new Map;viewHolds=new Map;pins=new Map;openFailures=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Ie,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},f.mkdirSync(Dq(),{recursive:!0});let{dir:n,name:r}=yT(Oq());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)??H3(t,this.deps.signer)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760+this.views.size*2621440}getOrCreate(e,t,n){let r=i7(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.load(e,t,n,null);a.state!==null&&this.log(`info`,$5(a.layers,a.state,a.ms));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,repos:a.repos,lastError:a.error,lastWarning:a.warning,state:a.state??_7(t,a.repos.plugins,this.deps),watch:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${Lr(this.accountedBytes())}/${Lr(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o,[],{kind:`open`},a.kind),o}hold(e,t,n){let r=this.getOrCreate(e,t,n);return this.holdState(r,r.state)}holdState(e,t){let n=this.holdOf(t);n.holders++,this.armSweep();let r=!1;return{entry:e,state:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache hold released twice`);r=!0,n.holders--,this.reclaim(t,n)}}}holdSession(e,t,n,r){let i=this.hold(e,t,n),a,o;try{a=this.viewOf(i.entry,i.state,r,`request`),o=this.leaseOf(a)}catch(e){throw i[Symbol.dispose](),e}return o.read=!0,this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}follow(e,t,n,r){try{var i=jo();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(i7(t,n,r));if(a!==void 0&&s?.state===a.state)return;let c=i.u(this.hold(t,n,r));this.viewOf(c.entry,c.state,o,`click`)}catch(e){i.e=e}finally{i.d()}}pin(e){this.pins.set(e,(this.pins.get(e)??0)+1);let t=!1;return()=>{if(t)throw Error(`render-cache pin released twice`);t=!0;let n=(this.pins.get(e)??0)-1;n>0?this.pins.set(e,n):this.pins.delete(e)}}viewOf(e,t,n,r){let{sessionId:i}=n,a=this.views.get(i);if(a?.state===t)return this.views.delete(i),this.views.set(i,a),a.requested(n),a;this.views.delete(i);let o=a!==void 0&&this.leaseOf(a).read,s;try{s=this.opened(e,t,n,o,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),s}opened(e,t,n,r,i){let{sessionId:a}=n,o;try{o=Lte(t,e.cwd,n,{sessionState:this.deps.sessionState,declare:this.deps.declare,source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(a,{error:e,facts:n}),e}return this.openFailures.delete(a),this.views.set(a,o),this.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}leaseOf(e){let t=this.viewHolds.get(e);if(t===void 0)throw Error(`render-cache view never served`);return t}retireView(e,t){this.views.get(e.sessionId)===e&&this.views.delete(e.sessionId),this.views.has(e.sessionId)||this.copies.delete(e.sessionId),e.retire();let n=this.leaseOf(e);n.retired={reason:t,held:n.holders},this.reclaimView(e,n)}reclaimView(e,t){t.retired===null||t.holders>0||(this.viewHolds.delete(e),this.log(`info`,`session view closed sid=${JSON.stringify(e.sessionId)} reason=${t.retired.reason} released=${e.dispose()} held=${t.retired.held} views=${this.views.size}`))}armSweep(){this.sweep===null&&(this.sweep=setInterval(()=>this.releaseIdle(),15e4),this.sweep.unref?.())}releaseIdle(){for(let[e,t]of this.viewHolds)t.retired!==null||this.pins.has(e.sessionId)||(t.read?t.read=!1:this.retireView(e,`idle`));for(let e of this.openFailures.keys())this.pins.has(e)||this.openFailures.delete(e);this.entries.size===0&&this.sweep!==null&&(clearInterval(this.sweep),this.sweep=null)}close(){if(this.closed)return;this.closed=!0,this.sweep!==null&&clearInterval(this.sweep),this.sweep=null,this.answersWatch.release();let e=this.entries.size;for(let[e,t]of this.entries)this.drop(e,t,`close`);this.log(`info`,`render-cache closed entries=${e} deferred=${this.stats.retired}`)}load(e,t,n,r){if(this.closed)throw Error(`render cache used after close`);return g7(e,t,n,this.deps,r)}drop(e,t,n){t.watch?.held.handle.release(),this.entries.delete(e),this.retire(t.state,n,null)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;let n=0;for(let e of this.viewHolds.values())e.retired!==null&&n++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,views:this.views.size,pinned:this.pins.size,retiredViews:n,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes(),n=new Set([...this.pins.keys()].flatMap(e=>{let t=this.views.get(e);return t===void 0?[]:[t.state]}));for(let[r,i]of this.entries){if(t())return;i===e||n.has(i.state)||this.drop(r,i,`evict`)}t()||this.log(`warn`,`render-cache over budget entries=${this.entries.size} views=${this.views.size} pinned=${n.size} accounted=${Lr(this.accountedBytes())}/${Lr(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`,r7(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}sessionsOn(e){return[...this.views.values()].filter(t=>t.state===e.state).map(e=>e.sessionId)}reload(e,t,n,r){this.reloadInto(this.getOrCreate(e,t,n),r)}reloadInto(e,t){let n=this.sessionsOn(e),r=e.state,i=this.load(e.projectDir,e.cwd,e.configFile,r);e.lastWarning=i.warning,e.lastError=i.error,i.state!==null&&this.log(`info`,$5(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=o7(e),{targets:r,unresolved:i}=n,a=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${n.key}`,{watch:o,move:s}=this.deps.watchers.follow(e.watch?.held??null,{...n,key:a},t=>this.reloadInto(e,{kind:`config-watch`,heard:t}));if(e.watch={derived:{...n,key:a},held:o},s!==`kept`){this.log(`info`,`config watch bound projectDir=${e.projectDir} cwd=${e.cwd} dirs=${r.dirs.map(e=>e.path).join(`,`)} deaf=${o.handle.deaf.length}`);for(let{path:t,reason:n}of i)this.log(`warn`,`config watch unresolved projectDir=${e.projectDir} path=${t} reason=${n}`)}}get size(){return this.entries.size}latestView(){return[...this.views.values()].at(-1)??null}delivered(e,t,n){if(!this.views.has(e))return;let r=this.copies.get(e)??new Map;this.copies.set(e,r.set(t,n))}drawnCopy(e,t,n){return this.copies.get(e)?.get(t)?.get(n)}stopDrawing(e,t){this.copies.get(e)?.delete(t)}};const zte=e=>!qJ(e)&&!mL(e)&&e!==`update.dismissed`&&e!==Vi;var Bte=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))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:HJ(e,zte,(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 Y(`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)})}};function Vte(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>TK(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return uZ({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...JK(n.config,n.fileHeldSettings,a),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})});return{payload:()=>s.read(),effective:()=>o.read(),selections:()=>o.read()}}}const b7=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,x7=`#{session_id} #{client_control_mode} #{pane_id}`;function S7(e){let t=new Set;for(let n of e.split(`
|
|
487
|
-
`)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function
|
|
488
|
-
`)){let[e,i,a,o,s,c]=r.trim().split(` `);e===void 0||e===``||i===void 0||Number(a)>0&&(o===`1`||t.has(i))&&(s!==`1`||c===`1`)&&n.add(e)}return n}function
|
|
484
|
+
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function D4(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 O4=e=>e.kind===`failed`?A0:e;function k4(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function A4(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 j4(e){return{...e,cells:e.cells.map(I0)}}function M4(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,...N4(e,r)]}function N4(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 P4(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:M4(e.direction,e.children.map((t,i)=>n(t,[...r,F4(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function F4(e,t){return e.steps[t]}function I4(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=L4(e);return{width:R4(t),reach:z4(t)}}function L4(e){let t=e.children.map(I4),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 R4=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),z4=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function B4(e,t){let n=L4(e);if(t?.axis===`cell`)return n.map(({start:e,span:n,ownLine:r})=>{let i=t.index+e;return r?{...t,index:i,lineStart:i,lineEnd:i+n.width-1}:{...t,index:i}});let r=Zy[e.direction],i=Tv(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),z4(n),R4(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const V4={compile(e,t){let n=B4(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,rb(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),M4(e.direction,e.children.map((n,r)=>t.renderChild(n,O4(t.gate),F4(e,r))))}},H4={drop:e=>e.place,above:()=>`above`},U4={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},W4={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:Qy(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(wi(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,ib(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,G4(e,t))};function G4(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=uN(t.scope,e.settings);if(t.gate.kind===`failed`)return Z4(e,r,t,t.gate.message);try{let i=t.placement(e),a=k4(t.gate,i.gate());if(a.kind===`failed`)return Z4(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 Z4(e,r,t,s.message);let c=$C(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:dF(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`?K4(f.variable):q4(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?J4(p.segment,u):Y4(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:A0,h.disclosure).map(e=>({...e,place:H4[v.placement](e)})),b=(e,t,n)=>z0(K0([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?U4[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},ee=S.flatMap(e=>b(new K(` `.repeat(X4(F0(e)))),h.trigger,0)),te=(e,t)=>e.band===`own`?t===x?S:ee:[],w=y.map((e,t)=>({cells:[...te(e,t),...e.cells],band:`deeper`,place:e.place})),ne=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ne.flatMap(e=>e.cells),...y.flatMap(te)].flatMap(F0)),[...ne,...w]}catch(n){return Z4(e,r,t,n.message??String(n))}}const K4=e=>({kind:`waiting`,variable:e});function q4(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=LT(e);if(t===void 0)throw e;return K4(t.variable)}}function J4(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:E4(K0(r,c)).map((e,t)=>({cells:z0(e,{...l,lead:t===0?K0(i,c):[],trail:t===0?K0(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:z0(K0([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function Y4(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=K0(Q4(e.lead,e,t,n),l),d=K0(Q4(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 z0(K0([new K(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function X4(e){return e.reduce((e,t)=>e+t.cellLength,0)}function Z4(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:z0([new K(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:dF(n.palette)},lead:Q4(e.lead,e,t,n),trail:Q4(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function Q4(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=LT(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const $4={container:V4,segment:W4};function e3(e){return $4[e]}var t3=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?n3:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const n3={kind:`hidden`},r3={palette:`theme`,style:`style`,effect:`effect`},i3=Qx.get(`colorCompatibility`),a3={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function o3(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function s3(e){if(e.ok)return e.value;throw e.error}const c3=e=>({read:()=>e}),l3=V_({basePalette:B_,palette:B_,decor:ny});var u3=class{evaluated=0;memory=new t3;scope;binding;facts;look=X.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&l3(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=cN(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(i3);return typeof e==`string`&&By(e)?e:`truecolor`});let i=(0,X.observable)(a3,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 P4(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=Lz(e);return i===void 0?[]:[{name:i,address:n,palette:$C(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>Vy(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=qN(e);return t===void 0?GN(e)===void 0?PN(this.view.get().payload(),e):PN(this.projected,e):this.slotName(t)}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[r3[e]];if(t.kind===`decided`)return p3(t.name,null,null);let r=h3(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=g3(this.source,e,i.name,r.where,e=>{t=e}),p3(n,t,null)}case`pending`:return p3(n??Dy[e],null,i.variable);case`failed`:return n=Dy[e],p3(n,Oy(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!m3(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)??Dy[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 M0(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>M2(this.source.activeSegment,()=>M0(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new _3(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:Q0(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=LT(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:o3(e)}),s3(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:Lz(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function d3(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new u3(t,n,e,r);return e.views.set(t,a),a}function f3(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 p3=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),m3=(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 h3(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 g3(e,t,n,r,i){switch(t){case`palette`:return iw(n,r,i).name;case`style`:return wy(n,e.styles).name;case`effect`:return Py(n).name}}var _3=class{where=v3(V_({palette:B_,region:ey}));ground=v3(V_({colours:b3,bodyOpen:B_}));opened=v3(V_({colours:b3,open:B_}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=uN(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?c3(j0):e.derive(`${t.id} when`,e.readsInstant(a),()=>M2(r,()=>M0(a,i))),this.open=d===void 0?c3(A0):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>M2(r,()=>M0(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return C3(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 w3(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?c3(E3):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return T3(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}),O3(n,r,this.affixes.read())}};function v3(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 y3=(e,t)=>e.hex===t.hex,b3=V_({palette:B_,drawnAt:B_,tint:y3,text:y3,bg:y3,disclosure:ry});function x3(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const S3=e=>Zv(e.palette,e.disclosure,e.drawnAt);function C3(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...ly(n,r,i)};return j2(e,x3(t,c),e=>{let t=wte(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function w3(e,t,n,r,i,a){return j2(e,x3(t,n),e=>(e.bg=i?S3(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function T3(e,t,n,r,i,a,o){return j2(e,x3(t,n),e=>(e.bg=r?S3(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const E3={lead:[],trail:[],drops:[]};function D3(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return m2(t,S3(e).state,n)},get band(){return m2(t,S3(e).plane,n)},get close(){return _2(t,S3(e).state,n)},disclosure:r}}function O3(e,t,n){return{styles:D3(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function k3(e,t,n,r,i,a,o){let s=C3(e,t,n,r,i,void 0,void 0,o);return O3(s,w3(e,t,s,a,!1,o),E3)}function A3(e,t,n,r,i){return D3(C3(e,t,n,r,i,void 0,void 0,{}))}function j3(e,t){return{payload:()=>e,selections:()=>t}}function M3(e){if(`ttl`in e)return{kind:`ttl`,durationMs:CN(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 N3(e,t){switch(sb(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 P3(e,t,n,r,i){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`source`:e.declareSourceDocument(t);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default,i);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:M3(n.cache),parse:N3(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:M3(n.cache),parse:N3(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 F3(e,t,n,r=TE.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 I3(e,t,n){let{compiled:r,loadWarnings:i}=R3(e,t,n.cwd,L3(n.signer),H3);return{...r,loadWarnings:i}}const L3=e=>(t,n)=>U3(n,e);function R3(e,t,n,r,i=H3){let a=z3(e),o=B3(a);return{compiled:r(o,a),compileKey:o,loadWarnings:V3(e,t,n,i)}}function z3(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of $x)n in t&&r.set(e,n);for(let[t,n]of fb(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...FU(e)].sort(([e],[t])=>e<t?-1:1)}}function B3(e){return w(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function V3(e,t,n,r){let i=w4(e),a=FU(e),o=[];for(let[s,c]of hT(e))if(r.has(i.get(s)))try{P3(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const H3=new Set([`directory`,`view`]);function U3({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>Y0(i,`drawnAt`).registry.drawnAt(),o=k2(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=Tw(e.presets),u=Ez(e),d=[e=>Q2(i,o,e.now)],f=sN({extraFuncs:{...f2(i),...Z2(i),...W2(i,o),...q2(i),...r4(i,o),...l4(i,o),...p4(s),...g4(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=F3(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=$0(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:F3(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=gb(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Eee(t,e,a,t=>String(Y0(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 e3(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=Ow(e,t);C.set(t,S(n,r,void 0))}let ee=new Map(yy.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of LU(e)){let e=t.join(`.`),i=ee.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:K3(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let te=new Set(n.map(([e])=>e)),w={reads:OU({names:te,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:iN(d)},ne=BU(w),T=[...C.values()].flatMap(G3(y)).some(e=>ne(m.get(e))),re=T?new Set([...w.clock,c4]):w.clock,E=BU({...w,clock:re}),D=new Set([...m].flatMap(([e,t])=>E(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=BU({reads:OU({names:te,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:w.projections,clock:re});for(let e of lW){let n=y[t][e];n!==void 0&&r(m.get(n))&&D.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:ee,instant:D,layoutReadsInstant:T,styles:e.styles,runtime:i,views:new WeakMap}}function W3(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 G3=e=>t=>{let n=[];return P4(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 K3(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 q3=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function J3(e,t,n,r,i){let a=Y3(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function Y3(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??Dy[e];case`failed`:return r({kind:`rule`,slot:e,message:Oy(t.where,e,`the rule failed — ${n.error}`)}),Dy[e]}}function X3(e){return Z3(e).filter(e=>!e.name.startsWith(Fi)).map(e=>e.id)}function Z3(e){return e.kind===`container`?e.children.flatMap(Z3):[e,...e.opens===void 0?[]:Z3(e.opens.body)]}function Q3(e,t,n,r,i,a){let o={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return d3(e,t,n,j3(o,a)),o}function $3(e,t,n,r,i,a,o,s,c){try{var l=jo();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new CS(``),h=m.clockAt(a,Ay[c.animationSpeed]),g=l.u(JM(a,h.timeline)),_=f3(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:YS(v),padding:v.padding,seamCols:XS(v),preset:c.preset},i);let y=_.evaluated;l.u(Q0(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:lv[c.variation],shade:ev[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},ee=_.memory.begin(C,A4),te=_.memory.from(C),w=new Set,ne={held:e=>te?.rules.get(e),waited:e=>w.add(e),settled:ee.rule},T=new Map,re=e=>{let n=_.slot(e);if(T.set(e,n.kind===`settled`?`kept`:`per-draw`),n.kind===`settled`)return n.warning!==null&&p({kind:`rule`,slot:e,message:n.warning}),n.waited!==null&&w.add(n.waited),n.name;let r=g3(t,e,J3(e,n.rule,_,p,ne),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:E,style:D,effect:ie}=_.selections(),O=E.kind===`decided`?E:iw(re(`palette`),``,q3),ae=D.kind===`decided`?D:wy(re(`style`),e.styles),oe=ie.kind===`decided`?ie:Py(re(`effect`)),se=O.value,ce=tw(se,ae.value);_.publishLook({basePalette:se,palette:ce,decor:S});let le=ce.get(`warning`),ue=c.idleSince===void 0?null:{idleSince:c.idleSince,timeoutS:c.menuTimeout,fill:le,text:Vv(ce,le,r.drawnAt())},de=m.motion(oe.value,h,{transitions:x,source:C,last:te,returned:A4,hold:j4},ue);u?.clear();let fe=t=>e.segments[t],pe=(e,i,a)=>{let o=i.kind===`hidden`?i:k4(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${X3(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:o.message,message:`${t}: ${o.message} — what it gates is hidden`})}}:o,c={scope:_.scope,palette:ce,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,i,o)=>k3(t.activeSegment,e,i,a,r.drawnAt(),o,n),lookupSegment:fe,renderChild:(e,t,n)=>pe(e,t,sy(a,n)),renderBody:(e,t,n)=>pe(e,t,cy(n)),closeDisclosure:e=>p2(n,e),placed:(e,t)=>ee.placed(e,de.placed(e,t)),lastDrawn:e=>te?.placements.get(e),waited:e=>w.add(e),decorations:(e,n)=>A3(t.activeSegment,e,n,a,r.drawnAt())};return e3(e.kind).render(e,c)},me=t.roots.get(b);if(me===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${Cw}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let he=D4(pe(me,j0,oy(S))).map(({line:e,row:t})=>{let n=W0(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...nC(n.map(e=>e.owner),v,de.row(t,r,n))}});de.drawn(),ee.commit();let ge=()=>he.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||Z3(me).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`),_e=Math.min(g.heard(),...he.map(e=>e.nextChange)),ve=Number.isFinite(_e)?`moves`:ge()?`can-move`:`still`;for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{frame:{depth:v.colorCompatibility,rows:he.flatMap(({kind:e,lines:t})=>t.map(t=>({kind:e,runs:t}))),nextChange:_e,motion:ve,pending:[...w].sort()},evaluated:_.evaluated-y,cellBreaks:he.reduce((e,t)=>e+t.cellBreaks,0),rules:T}}catch(e){l.e=e}finally{l.d()}}const e6={moving:1e3/30,still:1e3},t6=[`data`,`state`,`reload`,`visibility`];function n6(e){return ox.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 r6(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const i6=(e,t)=>ax[t].handsOff?e.resp:e.statusline,a6=e=>Math.round(1e3/e);var o6=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&i.noted++}subscribe(e,t){let n=this.deps.lanes(e);if(n!==null&&!n[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e),i=r??this.open(e);return i.followers.set(t,null),i.rates.has(t.lane)||i.rates.set(t.lane,[]),r!==void 0&&this.send(i,t),this.hasten(i),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${i.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(i,t)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e,t){let n=this.feeds.get(e);n!==void 0&&(n.woke[t]++,this.hasten(n)||n.coalesced++)}wakeWhere(e,t){for(let{sessionId:n,req:r}of this.watched())t(r)&&this.wake(n,e)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}latest(e){return this.requests.get(e)?.req??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e,t){let n=this.feeds.get(e);if(n===void 0)return px;let r=t-1,i=this.shown(n);return fx(e=>{let a=n.rates.get(e);if(a===void 0)return ux;let o=0;for(let t of n.followers.keys())t.lane===e&&o++;let s=0;for(let e of a)e>r&&e<=t&&s++;return{subscribers:o,fps:s,shown:i}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.now(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e,`state`)),unpin:this.deps.pin(e),phase:{kind:`waiting`},lastStart:-1/0,last:null,since:t,drawn:0,noted:0,noView:0,moving:0,unseen:0,failed:0,pushed:0,drawMs:0,evaluated:0,cellBreaks:0,woke:{data:0,state:0,reload:0,visibility:0},coalesced:0,summarizedAt:t,refreshesAtOpen:this.deps.refreshes()};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),n}close(){for(let e of[...this.feeds.values()])for(let t of[...e.followers.keys()])this.unsubscribe(e,t)}unsubscribe(e,t){if(e.followers.delete(t)){if([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),e.followers.size>0){this.hasten(e);return}e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),e.unpin(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)}}draw(e,t){e.phase={kind:`drawing`};let n=this.deps.now(),r=this.deps.instant(),i=Math.min(Math.max(t,r),r+.002),a=n+(i-r)*1e3;try{this.step(e,n,a,i)}catch(t){if(e.lastStart=a,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${le(t)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,i)}}step(e,t,n,r){let i=this.deps.render(e.sessionId,a6(this.spacingOf(e)),r);if(i===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=n;let a=this.deps.now();this.drawn++,e.drawn++,e.drawMs+=a-t,e.evaluated+=i.evaluated,e.cellBreaks+=i.cellBreaks,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,i),this.push(e,i,r),this.feeds.get(e.sessionId)===e&&(a-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,i,r)))}schedule(e,t,n){let{moving:r,still:i}=this.deps.periods,a=((t?.bar.nextChange??1/0)-n)*1e3,o=Math.min(Math.max(a,r),i),s=this.shown(e);o<i&&s&&e.moving++,o<i&&!s&&e.unseen++;let c=s?o:i;this.arm(e,n+c/1e3,this.deps.instant())}spacingOf(e){return this.shown(e)?this.deps.periods.moving:this.deps.periods.still}hasten(e){let{phase:t}=e;if(t.kind===`drawing`)return!1;let n=this.deps.now(),r=Math.max(n,e.lastStart+this.spacingOf(e));if(t.kind===`due`&&t.at<=r)return!1;let i=this.deps.instant();return this.arm(e,i+(r-n)/1e3,i),!0}arm(e,t,n){let r=Math.max(0,(t-n)*1e3);this.setTimer(e,t,this.deps.now()+r,r)}setTimer(e,t,n,r){e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.phase={kind:`due`,at:n,timer:setTimeout(()=>this.fire(e,t,n),r)}}fire(e,t,n){let r=n-this.deps.now();r>0?this.setTimer(e,t,n,r):this.draw(e,t)}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t,n){let r=this.deps.lanes(e.sessionId);if(r!==null)for(let t of[...e.followers.keys()])r[t.lane]||(this.unsubscribe(e,t),this.refuse(e.sessionId,t));if(e.followers.size===0)return;t.delivered();let i={resp:JSON.stringify(t.resp),statusline:JSON.stringify(t.statusline)};if(e.last?.answers.resp===i.resp&&e.last.answers.statusline===i.statusline)return;let a=e.last?.answers??null;e.last={bar:t.bar,answers:i},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);for(let[t,r]of e.rates)(a===null||i6(a,t)!==i6(i,t))&&r6(r,n);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let n=i6(e.last.answers,t.lane);e.followers.get(t)!==n&&(t.frame(e.last.bar,n),e.followers.set(t,n))}refuse(e,t){this.refused++,this.deps.log(`info`,`feed sid=${JSON.stringify(e)} refused lane=${t.lane} switched-off`),t.refused({ok:!1,error:CP(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now(),r=this.deps.refreshes(),i=(n-e.since)/1e3,a=i===0?`-`:`${(e.drawn/i).toFixed(1)}fps`,o=vN.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=${a6(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${t6.map(t=>`${t}:${e.woke[t]}`).join(`,`)} coalesced=${e.coalesced} daemonRefreshed=${o} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function s6(e,t){return ox.filter(n=>e[n]&&ax[n].handsOff&&t.has(n))}function c6(e,t){return{severity:cC,lines:[[lC(`[⟲ claude]`,Ea([{verb:na,args:[e,...t.map(e=>ax[e].switch.setting)]}]))]]}}function l6(e,t){for(let n of Object.entries(t))e.push(n)}const u6={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function d6(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,le(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function f6(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...d6(n)];return{level:u6[n.kind],line:`${e}${i.map(([e,t])=>` ${e}=${R(t)}`).join(``)}`}}const p6=()=>{},m6=e=>({ok:!1,error:e instanceof Error?e.message:le(e),code:`RENDER_FAILED`,daemonV:3}),h6={ansi:e=>({ok:!0,output:RS(e)}),frame:e=>({ok:!0,frame:e})};function g6(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.date().getTime(),s=[];try{try{var c=jo();let i=c.u(S6(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=w6(e,i,{by:`feed`,fps:n}),p=h6.ansi(o.body),m=j6(t,o,s6(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:h6.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}=f6(`render`,s,{kind:`threw`,error:e},i.date().getTime()-o),r=m6(e);return{bar:OS(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:p6,failure:{level:t,line:`frame ${n}`}}}}function _6(e,t,n){let{sessionState:r}=e;return TK(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function v6(e,t){try{var n=jo();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:SK(i.view.source.effective(),Wc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function y6(e,t,n){try{var r=jo();let{renderCache:i,frameFeeds:a}=e,o=r.u(i.hold(t.projectDir,t.cwd,t.target.path)),s=a.latest(n);return SK(_6(e,n,o.state),s===null||Wc(s.hints.tmux))}catch(e){r.e=e}finally{r.d()}}function b6(e,t,n){l6(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=Rt(e,r),a=zt(i);return l6(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:i.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits}),a}function x6(e,t,n,r){let{sessionState:i,renderCache:a}=e,s=t.hookData.workspace?.current_dir??t.cwd,c={...t,hookData:{...t.hookData,...s!==void 0&&o.isAbsolute(s)&&{location:Hc(s)}}},l=c.sessionId,u=b6(c,n,r);l6(r,{encoding:c.encoding});let d=w1(c.requested,i,l);return C6(e,a.holdSession(d.projectDir,d.cwd,d.target.path,c),c,u,n,r)}function S6(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=b6(o,n,r)}catch(e){throw a[Symbol.dispose](),e}return C6(e,a,o,s,n,r)}function C6(e,t,n,r,i,a){let{payloadProviders:o}=e;try{let{entry:e,state:s,view:c}=t,{sessionId:l,hints:u}=n,d=c.source.effective();return{req:n,at:i,facts:a,sessionId:l,entry:e,state:s,view:c,hintsError:r,payloadInputs:{hookData:n.hookData,deps:{...o,lanes:c.lanes},cwd:n.cwd,neededInputPaths:s.neededInputPaths(d.preset),hints:u},[Symbol.dispose]:()=>t[Symbol.dispose]()}}catch(e){throw t[Symbol.dispose](),e}}function w6(e,t,n){let{sessionState:r,frameFeeds:i,renderCache:a,updateWatch:o,linkSigner:s,fileEvents:c,renderWarnings:l,payloadProviders:u,effectSessions:d,menuIdle:f,launcher:p}=e,{req:m,at:h,facts:g,sessionId:_,entry:v,state:y,view:b,hintsError:x}=t,S=b.source.effective(),C=SK(S,Wc(b.facts().hints.tmux));l6(g,{lanes:ox.filter(e=>C[e]).join(`,`)||`-`});let{hints:ee}=b.facts(),te=YX(ee);l6(g,{width:String(te)});let w=b.source.payload(),ne=tee(r,_,h,n.by),T=ne.kind===`held`||ne.kind===`owed`?ne.error:null,re=o.notice({sessionId:_,dismissed:r.get(_,pq),enabled:S.updateNotice}),E=Mq(v.repos,_,s),D=(e,t)=>({about:e,text:t,copy:t}),ie=e=>D(e??``,e),O=[ie(Vt(m.refusedArgs)),ie(x),D(`load`,v.lastError),D(`update-act`,o.error()),...y.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),ie(T?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),ae=v.watch===null?null:ST(`config watch`,v.watch,null),oe=[...al(c.delivery()),...p.lifelineWarnings(),...ae===null?[]:[{kind:`config-watch`,message:ae}],...v.lastWarning===null?[]:[{kind:`load`,message:v.lastWarning}]],se={config:y.config},ce=uC(_,n.by,O,[...re,...E],[...oe,...l.ofSession(_,n.by,se)].map(e=>({about:`${e.kind}\0${e.message}`,text:e.message,copy:e.message}))),le={diagnostics:bC(ce),drawing:n,feeds:i.feedsOf(_,h),today:dZ(u,b.lanes().today,b.facts().hookData,h)},ue=Ao(w.metrics)?void 0:w.metrics;l6(g,oZ(b.lanes().sources)),l6(g,{prompts:String(ue?.messageCount??`-`),nonPrompts:String(ue?.nonPrompts??`-`),pr:NX(w.git,GX(t.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:n6(le.feeds)});let de=[],fe=AX(S,te),pe=d.of(_),me=f.since(_,h),{frame:he,evaluated:ge,cellBreaks:_e,rules:ve}=$3(y.config,y.compiled,b.store,b.registry,le,h,fe,{perSegmentSink:b.lastRenderCellsBySegment,onRenderWarning:e=>de.push(e)},{...S,effects:pe,idleSince:me}),ye=fC(ce),be=new Map(ce.map((e,t)=>[ye[t],e.copy])),xe=()=>a.delivered(_,n.by,be);f.observe(_,h,he.rows.some(e=>e.kind===`menu`),S.menuTimeout);let Se=f.since(_,h);l6(g,{menuIdle:Se===void 0?`-`:`${(h-Se).toFixed(1)}s/${S.menuTimeout}s`});let Ce=l.drawn(_,n.by,se,de),we={width:te,rows:SC(ee.termRows,n.by===`feed`?ox.flatMap(e=>{let t=ax[e].rows;return C[e]&&t!==null?[t]:[]}):[]),colorCompatibility:he.depth},Te=xC(r.get(_,Vi),ce),Ee=Te===null?he:ES(he,CC(ce,Te,_,n.by,we)),De=u.gitProvider.getStats(),Oe=u.usageStore.getStats(),ke=pe.lastFrame(),Ae=ke.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,je=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,Me=e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`file-events`:return`${e.kind}:${e.state}`;case`load`:case`config-watch`:case`lifeline`:case`when`:return e.kind}},Ne=[...oe,...de].map(Me).join(`,`)||`-`;return l6(g,{git:`${De.size}/${De.hits}h/${De.misses}m`,usage:`${Oe.size}/${Oe.hits}h/${Oe.misses}m`,effect:ke.effect,effectT:ke.t.toFixed(3),speed:`${ke.speed}x`,effectRows:`${ke.made}made/${ke.reused}reused`,effectOwn:Ae,fadeBasis:ke.basis,stateRev:String(ke.revision),fades:je(ke.fades),leaves:je(ke.leaves),motion:Ee.motion,evaluated:String(ge),cellBreaks:String(_e),pending:Ee.pending.join(`,`)||`-`,rules:[...ve].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:O.length>0?`Y`:`N`,clickError:ne.kind===`none`?`-`:ne.kind,upd:String(re.length),ask:String(E.length),warn:Ne,diag:String(ce.length),warnRecord:Ce?`new`:`kept`,viewer:Te===null?`-`:`${Te.index}/${ce.length}p${Te.page+1}`}),{drawn:{body:Ee,viewerOpen:Te!==null,diagnostics:ce,geometry:we},evaluated:ge,cellBreaks:_e,clickShown:T,delivered:xe,lanes:C}}function T6(e,t){let{sessionState:n}=e,r=t.sessionId,{client:i,...a}=t.hints,o=JSON.stringify(a);n.get(r,`client-hints`)!==o&&n.set(r,e0,o);let s=T1(t.requested);n.get(r,`render-origin`)!==s&&n.set(r,C1,s)}async function E6(e,t,n,r,i){return T6(e,t),A6(e,t,n,r,i)}function D6(e,t,n){let{laneSetups:r,tmuxStatusLines:i}=e;r.noted(O6(e,t),n),i.observe(t.hookData.session_id,t.hints.tmux,n.tmuxStatus)}function O6(e,t){let{sessionState:n}=e,r=t.hookData.session_id;return{sessionId:r,hints:t.hints,origin:w1(t.requested,n,r),transcript:t.hookData.transcript_path,answered:DF(t.hookData)}}function k6(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);a.clicked(t,s===null?null:O6(e,s),n,r),s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus)}async function A6(e,t,n,r,i){try{var a=jo();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(x6(e,t,n,i));D6(e,t,SK(l.view.source.effective(),Wc(t.hints.tmux)));let u=o.monotonic(),d=r-u;l6(i,{deadline:`${t.deadline.kind}:${Math.round(d)}ms`});let f=new Map,p=await EX(e=>Promise.all([fZ(l.payloadInputs,n,f),l.view.registry.inFlight(e)]),d,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${le(e)}`),o.after),m=o.monotonic();l6(i,{waited:`${Math.round(m-u)}ms`,ended:p,refreshed:ZX(f)});let{drawn:h,clickShown:g,delivered:_,lanes:v}=w6(e,l,cx),y=t.sessionId,b=s6(v,s.following(y)),x=kF(t.hints.client??null)===`statusline`,S=h6[t.encoding](x?j6(y,h,b):h.body);return l6(i,{handoff:(x?b:[]).join(`,`)||`-`,drew:`${Math.round(o.monotonic()-m)}ms`}),{resp:S,motion:h.body.motion,clickShown:g,delivered:_}}catch(e){a.e=e}finally{a.d()}}function j6(e,t,n){let[r,...i]=n;return r===void 0||t.viewerOpen?t.body:ES(t.body,wC(c6(e,[r,...i]),t.diagnostics,e,t.geometry))}const M6=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`]),N6=[[`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`]],P6=[[`workspace.added_dirs`,`string-list`]];function F6(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of N6){let i=R6(n,e);if(i==null)t.missingRequired.push(e);else{let n=I6(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of P6){let i=R6(n,e),a=i===void 0?r:L6(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))M6.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function I6(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function L6(e){return Array.isArray(e)&&e.every(e=>I6(e)===`string`)?`string-list`:I6(e)}function R6(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 z6(e,t){let{tokens:n}=ue({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=(n??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),i=(n??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===r&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:xF(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function B6(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=Ft.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${Ft.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function V6(e,t,n){let{report:r}=F6(e.hookData),i=[];for(let e of r.missingRequired)i.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of r.typeMismatches)i.push(`field '${e}' expected ${t}, got ${n}`);let a=t1(e.hookData?.session_id);a.ok||i.push(`field 'session_id' ${a.problem}`),(typeof e.cwd!=`string`||!l(e.cwd))&&i.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&i.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let o=B6(e.encoding);o.ok||i.push(o.problem);let s=sn(e.deadline);if(s.kind===`refused`)return{ok:!1,problems:[...i,s.problem]};if(i.length>0||!a.ok||!o.ok)return{ok:!1,problems:i};for(let e of r.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let c=Lt(e),{configFile:u,refusedArgs:d}=z6(e.args,e.cwd);return{ok:!0,req:{...e,deadline:s,encoding:o.encoding,sessionId:a.id,hints:c,rateLimits:Ate(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:wF(u,c.configEnv)},refusedArgs:d}}}function H6(e,t){switch(e){case`vars`:return{what:e,vars:U6(t)};case`segments`:return{what:e,segments:J6(t)};case`config`:return{what:e,config:Q6(t)}}}function U6(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=K6(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=W6(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:G6(r.lastUpdatedMs())})}return o}function W6(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 G6(e){return e===null?null:Math.max(0,Date.now()-e)}function K6(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,q6(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}`,q6(i));return t}function q6(e){return e.kind}function J6(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=X6(n),o=Y6(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:Z6(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function Y6(e){let t=new Map;for(let n of Tw(e.presets))for(let r of nb(Ow(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=Qy(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function X6(e){let t=[],n=new Set;for(let r of nb(pw(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 Z6(e,t,n){let r=new Set([...cT(e,t).keys()].flatMap(e=>gT(e,n)));return Array.from(r).sort()}function Q6(e){return e===null?null:e.config}const $6=[`vars`,`segments`,`config`];function e8(e){return typeof e==`string`&&$6.includes(e)}const t8=e=>({resp:e,exitAfterFlush:null,delivered:p6}),n8=e=>({kind:`reply`,...e}),r8={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},i8=(e,t)=>n8(t8({ok:!1,error:t,code:e,daemonV:3}));function a8(e){let t=t1(e.sessionId);if(!t.ok)return i8(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return i8(`VERSION_MISMATCH`,`this client's subscribe names no lane (${ox.join(`, `)}): it predates the lane toggles — update it`);let n=mx(e.lane);return n===null?i8(`BAD_REQUEST`,`subscribe needs a lane, one of ${ox.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function o8(e,t,n,r,i){return!t||typeof t!=`object`||typeof t.v!=`number`?i8(`BAD_REQUEST`,`malformed request`):t.v===3?t.kind===`subscribe`?a8(t):typeof t.kind!=`string`||!Object.hasOwn(r8,t.kind)?i8(`BAD_REQUEST`,`unknown kind`):n8(await s8(e,t,n,r,i)):(t.v>3?e.log(`info`,`version mismatch: client=${t.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):e.log(`info`,`version mismatch: client=${t.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${t.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:t.v>3?0:null,delivered:p6})}async function s8(e,t,n,r,i){let{stats:a,clock:o,frameFeeds:s,renderCache:c,payloadProviders:{gitProvider:l,usageStore:u},fileEvents:d,runs:f,effectSessions:p,menuIdle:m,journalTurns:h,sessionState:g,tmuxStatusLines:_,watcherRegistry:v,limits:y,handlerProbes:b,renderSightings:x,bundle:S,sourceDigest:C,doctorStores:ee}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:p6};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return t8(typeof e!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:s.newestWhere(({hints:{tmux:t}})=>t!=null&&t.socket===e&&t.pane===n)})}if(t.kind===`stats`)return t8({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:c8(e),fileEvents:d.stats(),runs:f.stats(),transcriptReads:zo(),renderCache:c.stats,effectCache:p.getStats(),menuIdle:m.getStats(),journalTurns:h.getStats(),sessionState:{sessions:g.size(),observers:g.observers(),revision:g.latestRevision()},frameFeeds:s.getStats(),tmuxStatus:_.stats(),watchersActive:v.size(),dirWatchesActive:v.dirWatches(),nextRestartReason:y.describeNextRestart(),handlerProbes:b.list(),clients:x.list(GM(o.date())),bundle:S,sourceDigest:C,daemon:y.serving(),doctorStores:IQ(ee)})});if(t.kind===`render`){let c=o.date(),l=GM(c),u=o.monotonic(),d=Math.round(u-r),f=[],p=++a.requestsTotal,m=V6(t,a,e.log),h=(e,t)=>x.see(e.sessionId,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:Xo(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:jte(e.hookData),frame:t},l,p);m.ok&&(h(m.req,`drawing`),s.note(m.req.sessionId,m.req,p));let _=m.ok?await E6(e,m.req,l,u+cn(m.req.deadline,r,{epochMs:c.getTime(),monoMs:u}),f).then(({resp:e,motion:t,clickShown:n,delivered:r})=>(h(m.req,t),{outcome:{kind:`ok`},resp:e,delivered:()=>{r(),n!==null&&eee(g,m.req.sessionId,n)}}),e=>(h(m.req,`failed`),{outcome:{kind:`threw`,error:e},resp:m6(e),delivered:p6})):_8(m.problems);_.outcome.kind!==`ok`&&a.requestsErrored++,l6(f,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:v,line:y}=f6(`render`,f,_.outcome,Math.round(o.monotonic()-u));return e.log(v,y),{resp:_.resp,exitAfterFlush:null,delivered:_.delivered}}if(t.kind===`click`){let a=o.monotonic(),s=[[`queued`,`${Math.round(a-r)}ms`]],c=await f8(e,t,s,()=>n()||i());l6(s,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`});let{level:l,line:u}=f6(`click`,s,c,Math.round(o.monotonic()-a));return e.log(l,u),t8(h8(c))}if(t.kind===`debug`){if(!e8(t.what))return t8({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${$6.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`?d8(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??Wx(`colorCompatibility`)):u8};return t8({ok:!0,debug:H6(t.what,n)})}throw Error(`no reply for request ${le(t)}`)}function c8(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 l8={endcaps:Wx(`endcaps`),colorCompatibility:Wx(`colorCompatibility`),wrap:Wx(`autoWrap`),padding:Wx(`padding`),width:1/0},u8=new Map;function d8(e,t){let n=new Map;for(let[r,i]of e)n.set(r,rC(i,{...l8,colorCompatibility:t}));return n}async function f8(e,t,n,r){let{verb:i,value:a}=t;if(typeof i!=`string`||typeof a!=`string`)return{kind:`bad-request`,problems:[`a click's verb and value are strings, got ${typeof i} and ${typeof a}`]};try{return await m8(e,i,a,{via:`link`,handler:qt(t.clientVersion)},n,r)}catch(e){return e instanceof Y?{kind:`bad-request`,problems:[e.message]}:e instanceof JC?{kind:`closing`,error:e}:e instanceof YC?{kind:`abandoned`,error:e}:{kind:`threw`,error:e}}}const p8={link:`verb`,"tmux-status":`linkVerb`};async function m8(e,t,n,r,i,a){let{menuIdle:o,verbCtx:s}=e;if(t===`tmux-status-click`)return l6(i,{verb:t}),g8(e,n,i,a);let c=D0.get(t);if(!c)return{kind:`bad-request`,problems:[`unknown click verb: ${t}`]};l6(i,{[p8[r.via]]:t});let l=v0(t,n),u=l?.ok?l.id:null;l===null?l6(i,{sid:`-`}):u!==null&&(l6(i,{sid:u}),o.clickArrived(u));try{await c(n,{...s,arrival:r,placeWaited:e=>l6(i,{placeWait:`${e}ms`}),gatherTook:e=>l6(i,{gather:`${e}ms`}),turnWaited:e=>l6(i,{turnWait:`${e}ms`}),clientGone:a})}finally{u!==null&&o.clickSettled(u)}return{kind:`ok`}}function h8(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 m6(e.error)}}async function g8(e,n,r,i){let{tmuxStatusLines:a}=e,o=e=>({kind:`bad-request`,problems:[e]}),s=a.linkAt(n);if(s.kind===`refused`)return o(s.reason);if(l6(r,{link:s.url}),s.url.startsWith(`cc-candybar://`)){let t=XC(()=>zs(s.url));return t.verb===`tmux-status-click`?o(`a status-line link names another status-line click`):m8(e,t.verb,t.value,{via:`tmux-status`},r,i)}return await c1(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log,a1),{kind:`ok`}}const _8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:p6});function v8(e,t){try{return F(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?I:L(e.message)}}function y8(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function b8(e){let{targets:t,intervalMs:n,stat:r,held:i,exit:a,log:o}=e,s=Fe(o),c=t.map(e=>({path:e,stamp:v8(e,r)})),l=c.filter(({stamp:e})=>e.kind!==`failed`),u=null,d=!1,f=()=>{d=!0,u&&clearInterval(u)},p=async()=>{if(!d)for(let{path:e,stamp:t}of l){let n=v8(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!y8(t,n)){let t=`binary ${n.kind===`absent`?`gone`:`changed`} (${e})`,r=await i();if(d)return;if(r){s([`info`,`${t}; the restart waits for the running update`]);return}o(`info`,`${t}; shutting down`),f(),a();return}}},m=()=>p().catch(e=>{o(`error`,`binary check failed: ${e.message}`)});return{arm(){for(let{path:e,stamp:t}of c)t.kind===`failed`&&o(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);u=setInterval(()=>void m(),n),u.unref()},checkNow:m,close:f}}function x8(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var S8=class{timer=null;state=`released`;last=null;constructor(e,t=Date.now){this.tick=e,this.now=t}landed(e,t=this.now()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.now());this.timer=setTimeout(()=>{this.timer=null,this.tick()},e),this.timer.unref?.()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};const C8=`pass`,w8={okMs:5*6e4,failedMs:45e3};function T8(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function E8(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function D8(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function O8(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:o.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>Yc(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${Xc(i[t])}`).join(`|`)}`,targets:{dirs:r},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function k8(e){return e.find(e=>e.kind===`ok`)?.value.branch}function A8(e){e.missed=!0,bX(e,`unread`)}function j8(e,t){return e.missed&&e.reading.get().kind===`pending`&&yX(e,t.size>0?L([...t].join(`; `)):I),`unkeyed`}function M8(e,t){let n=CX(e);return t===null||n.kind!==`ok`?n:F({...n.value,pullRequest:CX(t)})}function N8(e){return t=>L(`${e} threw: ${String(t)}`)}var P8=class{repos=new Map;resolutions=new Map;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;watchers;ownsWatchers;logger;constructor(e){this.inner=e.inner,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Ie;let t=e.ledger??new yN(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 OT({logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=L(`resolver threw: ${String(e)}`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`not-a-repo`)return DX(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>M8(a,o)}}asked(e,t,n,r){let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`not-a-repo`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n={root:e,refresh:new _N,watch:this.followWatch(e,null).watch,period:new S8(()=>{n.refresh.share(C8,()=>this.refreshPass(n))}),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,n),n}followWatch(e,t){let n=this.inner.resolveGitDir(e),r=O8(e,n,this.inner.resolveCommonGitDir(n)),i=this.watchers.follow(t,r,()=>this.changed(e));return i.move===`rebound`&&this.logger(`info`,`git watch bound root=${e} dirs=${r.targets.dirs.map(e=>e.path).join(`,`)} deaf=${i.watch.handle.deaf.length}`),i}changedPass(e,t){e.asked.add(t),e.refresh.run(C8,()=>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&&A8(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(C8,()=>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:_X(),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=D8(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(E8(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}async pass(e){if(this.repos.get(e.root)!==e)return;let t=Date.now(),n=[...e.asked];e.asked.clear();let r=this.followWatch(e.root,e.watch);e.watch=r.watch;let i=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?i.push(t):t.missed=!0;let a=e.pr,[o,s]=await Promise.all([Promise.all(i.map(t=>this.inner.getGitInfo(e.root,t.options).catch(N8(`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,yX(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of VY(n.value))c.add(e)});let l=k8(o),u=a===null||i.length===0?`-`:l===void 0?j8(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}`,T8(n),c.size===0?F(null):L([...c].join(`; `)),Date.now()-t)}prSource(e){let t={period:new S8(()=>{this.readPr(e,t,`period`)}),seen:new Map,holders:0,missed:!0,key:``,remote:I,reading:_X(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(N8(`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?(A8(t),`owed`):(bX(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,yX(t,a.outcome),t.period.landed(x8(w8,a.outcome),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=Date.now(),o=(i.kind===`ok`?this.inner.resolvePullRequest(e.root,i.value).catch(N8(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:I)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${R(r)}`,n,i,Date.now()-a);let o=Date.now();t.seen.delete(r),t.seen.set(r,{outcome:i,at:o});for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==r||t.missed||(yX(t,i),t.period.landed(x8(w8,i),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=L(`git state dropped: ${e.root}`);for(let n of e.values.values())xX(n,t);e.pr!==null&&xX(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watch.handle.release(),e.period.dispose(),e.pr?.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},F8=class{static CACHE_DIR=ht();static USAGE_CACHE_DIR=o.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=o.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=o.join(this.LOCKS_DIR,e);if(!f.existsSync(t))return!1;try{let n=f.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return k(`Invalid PID in lock file ${e}, removing stale lock`),f.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(k(`Removing stale lock file ${e} for dead process ${r}`),f.unlinkSync(t),!1):(k(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return k(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=o.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await f.promises.writeFile(n,i,{flag:`wx`}),k(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await xe(50);else throw e}return k(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=o.join(this.LOCKS_DIR,e);try{await f.promises.unlink(t),k(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&k(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([f.promises.mkdir(this.CACHE_DIR,{recursive:!0}),f.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),f.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){k(`Failed to create cache directories:`,e)}}static createProjectHash(e){return w(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=o.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){k(`Cache for ${e} is locked, waiting...`),await xe(75);continue}try{let r=await f.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(k(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(k(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return k(`No shared ${e} usage cache found`),null;k(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await xe(75)}}return k(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){k(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=o.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await f.promises.writeFile(r,i,`utf-8`),k(`[CACHE-SET] ${e} disk cache stored`)}catch(t){k(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const I8={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var L8=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await F8.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await F8.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=be({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){k(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){k(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(k(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),k(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(k(`Invalid pricing data structure`),e(null))}catch(t){k(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{k(`Response error:`,t),e(null)})});r.on(`error`,t=>{k(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{k(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return k(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return k(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),k(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(k(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(I8).length} models`),this.executionCache=I8,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(I8).length} models`),I8)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return k(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),k(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}},R8=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}},z8=class{entries=new Map;refreshes;constructor(e){this.spec=e,this.refreshes=e.ledger.declare({name:e.name,scope:e.scope,refresh:e.every===null?[`first`,`change`,`supersede`]:[`first`,`period`,`change`,`supersede`]})}declare(e,t){let n=this.spec.keyOf(t),r=this.touched(n)??this.firstRead(this.created(n,t));return e.take(`${this.spec.name}:${n}`,()=>this.hold(r)),{current:()=>CX(r)}}supersede(e){let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,bX(n,`superseded`),n.flight=null,n.changed=!1,this.evict();let r=!1;return()=>{r||(r=!0,n.superseding--,this.entries.get(n.key)===n&&this.refresh(n,`supersede`))}}changed(e){for(let t of this.entries.values())t.holders>0&&e(t.input)&&this.refresh(t,`change`)}isHeld(e){for(let t of this.entries.values())if(t.holders>0&&e(t.input))return!0;return!1}stats(){let e=0;for(let t of this.entries.values())t.holders>0&&e++;let{refreshes:t,failures:n,lastMs:r}=this.refreshes.record();return{entries:this.entries.size,held:e,refreshes:t,failures:n,lastMs:r}}close(){for(let e of[...this.entries.values()])this.drop(e)}touched(e){let t=this.entries.get(e);if(t!==void 0)return this.entries.delete(e),this.entries.set(e,t),t}created(e,t){let n={key:e,input:t,reading:_X(),holders:0,flight:null,changed:!1,superseding:0,revisit:B8(this.spec.every,{period:()=>this.refresh(n,`period`),holdReturned:()=>this.refresh(n,`change`)})};return this.entries.set(e,n),n}firstRead(e){return this.refresh(e,`first`),e}refresh(e,t){if(e.superseding>0)return;if(e.flight!==null){e.changed||=t===`change`;return}let n={};e.flight=n;let r=Date.now();H8(()=>this.spec.read(e.input)).then(i=>{let a=e.flight===n;try{this.refreshes.recorded(`${this.spec.fields(e.input)} stored=${a?`Y`:`N`}`,t,i,Date.now()-r)}finally{a&&this.store(e,i)}}).catch(t=>{this.spec.logger(`error`,`${this.spec.name} refresh threw (${this.spec.fields(e.input)}): ${String(t)}`)})}store(e,t){e.flight=null;try{yX(e,t)}finally{e.revisit.landed(t),e.changed&&(e.changed=!1,this.refresh(e,`change`))}}hold(e){return e.holders++,e.revisit.hold(!0),this.evict(),()=>{e.holders--,e.revisit.hold(e.holders>0)}}evict(){for(let e of[...this.entries.values()]){if(this.entries.size<=this.spec.maxEntries)return;e.holders===0&&e.superseding===0&&this.drop(e)}}drop(e){this.entries.delete(e.key),e.flight=null,e.revisit.dispose(),xX(e,L(`${this.spec.name} entry dropped`))}};function B8(e,t){if(e===null)return new V8(t.holdReturned);let n=new S8(t.period);return{landed:t=>n.landed(x8(e,t)),hold:e=>n.hold(e),dispose:()=>n.dispose()}}var V8=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 H8(e){let t=e=>L(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function U8(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const W8={okMs:60*1e3,failedMs:10*1e3},G8={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},K8={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function q8(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function J8(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function Y8(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const X8={entries:0,cost:0,breakdown:Y8(),days:new Map};async function Z8(e,t){let n=q8(new Date(J8())),r=e.entries,i=e.cost,a={...e.breakdown},o=new Map;for(let[t,r]of e.days)t>=n&&o.set(t,{...r});for(let e of t){let t=e.message?.usage;if(!t)continue;r++;let s=e.costUSD??await L8.calculateCostForEntry(e.raw);i+=s,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0;let c=q8(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...G8};l.cost+=s,l.input+=t.input_tokens||0,l.output+=t.output_tokens||0,l.cacheCreation+=t.cache_creation_input_tokens||0,l.cacheRead+=t.cache_read_input_tokens||0,o.set(c,l)}return{entries:r,cost:i,breakdown:a,days:o}}function Q8(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function $8(e){let t=0,n=0,r=Y8(),i=new Map;for(let{value:a}of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...G8};Q8(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:K8,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}function e5(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function t5(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!e5(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...G8};Q8(r,t),n.set(e,r)}return n}async function n5(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 r5(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function i5(e,t){(0,X.runInAction)(()=>e.set(t))}var a5=class{sessions=X.observable.map(void 0,{deep:!1});flight=new R8;scans;daySets=new Map;speedFlight=new R8;requestFlight=new R8;staleAgeMs;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;sweepTimer=null;constructor(e={}){this.log=e.logger??Ie,this.ledger=e.ledger??new yN(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new z8({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${R(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??W8,maxEntries:8,logger:this.log,ledger:this.ledger});let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps}}scanStats(){return this.scans.stats()}getUsageInfo(e,t){return this.request(e,t?.transcript_path).usage(t)}request(e,t){let n=null,r=()=>{if(n!==null)return n;let r=Mo(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(r5(t.kind===`ok`?t.value.sessionInfo:K8,e))},speed:t=>this.observed(e,r,t),today:async e=>{await OX(e),await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return ko;let r=n.failure.get();return r===null?F(r5(n.record?.sessionInfo??K8,t)):L(r)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=Date.now(),a=await this.ingest(e,t,r,n);return this.renderTally.hits+=r.hits,this.renderTally.misses+=r.misses,r.misses>0&&this.usage.recorded(`sid=${R(e)}`,`request`,a,Date.now()-i),i5(this.hold(e).failure,a.kind===`failed`?a.reason:null),a})}refreshToday(e,t){return this.request(t?.session_id??``,t?.transcript_path).today(e)}declareToday(e,t){let n=EZ(t),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?F({roots:i.roots,sums:i.sums.read()}):e}}}todayAt(e,t,n){let r=this.sessions.get(t?.session_id??``),i=r?.failure.get()??null;if(i!==null)return L(i);let a=q8(KM(n)),o={...G8},s=e.sums.get(a);s!==void 0&&Q8(o,s);let c=e5(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&Q8(o,c),s===void 0&&c===void 0?I:F({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:a})}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return I;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return i5(this.hold(e).speed,t),t;let r=U8(t.kind===`ok`?t.value.sessionInfo.tokenBreakdown:null,n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=F({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return i5(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??ko:I}async ingest(e,t,n,r){if(!e)return I;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,F(i);if(!t)return i?F(i):I;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,sessionInfo:s.value.sessionInfo,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),F(c)):l===void 0?F(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,X.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[],failure: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=>u(e,`projects`)+d),i={roots:r,sums:new BT(`today over ${e.join(`,`)}`,()=>t5(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await kZ(e,c(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of RZ(r.longLines))this.log(`info`,e);let i=new Map,a=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),o=await zZ(e,r,X8,Z8);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{folded:s,longLines:c}=o.value;for(let e of RZ(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...$8(i),mainStamp:a})}async scan(e){try{let t=J8(),n=await DZ(e),r=[];for(let e of n){let n=await OZ(Io(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=u(e,i),a=await OZ(Lo(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:No(a)})}}let i=[],a={hits:0,misses:0};return await n5(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,a,e.stamp);t.kind===`failed`&&(i.push(t.reason),this.log(`warn`,`usageStore scan: ${t.reason}`))}),this.log(`info`,`usageStore scan dirs=${R(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?L(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`):F({sessions:r.length,read:a.misses})}catch(e){return L(`usage scan: ${e instanceof Error?e.message:String(e)}`)}}sweepStale(){let e=Date.now(),t=q8(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.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.scans.close(),(0,X.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},o5=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)}})}},s5=class{sessions;constructor(e,t,n,r=Ie,i=256){this.empty=e,this.step=t,this.refreshes=n,this.log=r,this.sessions=new o5(i)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=Mo(t);if(n?.folded&&i!==``&&n.folded.cursor.stamp===i){let{folded:t,answer:r}=n;return r.kind===`ok`&&r.value===t.value?(this.sessions.touch(e),r):this.store(e,t,{kind:`ok`,value:t.value})}let a=Date.now(),o=await zZ(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${R(e)}`,`request`,o,Date.now()-a),o.kind===`failed`)return this.store(e,r,o);if(o.kind===`absent`)return this.store(e,r,{kind:`ok`,value:r?.value??this.empty});let{folded:s,longLines:c}=o.value;for(let e of RZ(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??ko}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function c5(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 l5=class{fold;constructor(e={}){let t=e.logger??Ie;this.fold=new s5(void 0,c5,(e.ledger??new yN(t)).declare({name:`context`,scope:`session`,refresh:[`request`]}),t)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return k(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);k(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){return this.contextFrom(await this.fold.read(e,t),n)}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t?F(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,u5(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,u5(e))}contextFrom(e,t){if(e.kind===`failed`)return L(`context transcript: ${e.reason}`);let n=e.value;return n===void 0?(k(`No main chain entries with usage data found`),I):(k(`Most recent main chain context: ${n} tokens (limit: ${t})`),F({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function u5(e){return e.context_window?.context_window_size??2e5}const d5={messageCount:0,nonPrompts:0,recent:[]},f5=new Set([`turn`,`interrupt`,`claude-code`]);function p5(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!f5.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function m5(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 h5=class{fold;constructor(e={}){let t=e.logger??Ie;this.fold=new s5(d5,p5,(e.ledger??new yN(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),t)}async getMetricsInfo(e,t){k(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?g5(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:g5(e,n,r)}};function g5(e,t,n){return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`):F({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:m5(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 _5={command:null,todos:[],pending:[],done:[]};function v5(e,t){let n=e.findIndex(e=>e.name===t);return n<0?[...e,{name:t,count:1}]:e.map((e,t)=>t===n?{name:e.name,count:e.count+1}:e)}function y5(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 b5(e,t){if(t.isSidechain)return e;let n=y5(e,t),r=t.activity;if(r===void 0)return n;let i=n.pending,a=n.done;r.started!==void 0&&(i=[...i,...r.started]);for(let e of r.finished??[]){let t=i.findIndex(t=>t.id===e);t<0||(a=v5(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function x5(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>v5(e,t.name),[]),done:e.done}}var S5=class{fold;constructor(e={}){let t=e.logger??Ie;this.fold=new s5(_5,b5,(e.ledger??new yN(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),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}`):F(x5(t.value))}const w5=3e4;var T5=class{names;constructor(e){let t=e.logger??Ie;this.names=new z8({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${R(e.pane)} socket=${R(e.socket)}`,read:t=>E5(e.launcher,t),every:{okMs:w5,failedMs:w5},maxEntries:64,logger:t,ledger:e.ledger??new yN(t)})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function E5(e,t){let n=await _c(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return L(n.reason);let r=n.stdout.trim();return r?F(r):I}const D5=6e4,O5={okMs:D5,failedMs:D5};function k5(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function A5(e,t){try{let e=t();return Promise.resolve(e===``?I:F(e))}catch(t){return Promise.resolve(L(`host.${e}: ${String(t)}`))}}var j5=class{name;user;constructor(e={}){let t=e.logger??Ie,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:O5,maxEntries:1,logger:t,ledger:e.ledger??new yN(t)};this.name=new z8({...n,name:`host.name`,read:()=>A5(`name`,()=>k5(D.hostname()))}),this.user=new z8({...n,name:`host.user`,read:()=>A5(`user`,()=>D.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()}},M5=class{known=new o5(64);refreshes;constructor(e=Ie,t=new yN(e)){this.refreshes=t.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=N5(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=Date.now(),i=EL(e);return this.refreshes.recorded(`path=${R(e)} stamp=${R(t)}`,`request`,i,Date.now()-r),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??ko}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}};function N5(e){try{let t=f.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:No(t)}catch(e){return`unread:${e.code??`error`}`}}const P5=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function F5(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 I5=class{known=new o5(256);refreshes;constructor(e=Ie,t=new yN(e)){this.refreshes=t.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=Mo(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??ko}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}async read(e,t,n){let r=Date.now(),i=await L5(t);return this.refreshes.recorded(`sid=${R(e)} stamp=${R(n)}`,`request`,i,Date.now()-r),i}};async function L5(e){let t=await R5(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function R5(e){for(let t of[65536,1048576]){let n=await Ko(e,t);if(n.kind!==`ok`)return n;let r=z5(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function z5(e,t){let n=e.toString(`utf8`).split(`
|
|
485
|
+
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!P5.test(t))continue;let r=F5(t);if(r!=null)return r}return null}var B5=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)}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)})}};const V5=e=>qU(e),H5=e=>o.join(e.storage.folder,V5(e.sessionId)),U5=e=>JSON.stringify([e.folder,e.generation]),W5=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var G5=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;identityOf;fileEvents;unsubscribe;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??Kc,this.fileEvents=e.fileEvents,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new z8({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${R(H5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new yN(e.logger)})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{f.mkdirSync(e,{recursive:!0}),n=this.identityOf(e)}catch(e){t.unusable=`could not be created or read: ${e.message}`}return(t.lost||t.identity!==null&&(n===`gone`||!qc(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${R(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(U5(e))??this.opened(e);t.holders++;let n=!1;return()=>{n||(n=!0,t.holders--,t.holders===0&&this.closed(t))}}declare(e,t,n){return this.sessions.declare(e,{storage:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({storage:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost}}close(){this.unsubscribe(),this.sessions.close();for(let e of[...this.watched.values()])this.closed(e)}recorded(e){let t={generation:0,identity:null,lost:!1,unusable:null};return this.folders.set(e,t),t}opened(e){let t=this.folders.get(e.folder);if(t===void 0)throw Error(`plugin storage: no key was asked for ${e.folder}`);let n=e.generation===t.generation?t.unusable:null,r=n===null?this.identityOf(e.folder):`gone`;e.generation===t.generation&&(t.identity=r===`gone`?null:r);let i={key:e,folder:t,identity:r,holders:0,handle:this.watchers.acquire(`plugin-storage:${U5(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),sweep:setInterval(()=>void this.sweep(e),864e5),health:{kind:`watching`}};i.sweep.unref(),this.watched.set(U5(e),i),n!==null&&this.faulted(i,`unusable`,n);for(let e of i.handle.deaf)this.faulted(i,`refused`,e.reason);return this.sweep(e),i}closed(e){let t=U5(e.key);this.watched.delete(t),e.health={kind:`closed`},clearInterval(e.sweep),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>W5(e.storage,n);switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.has(o.join(n.folder,o.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(H5(e)));return}case`failed`:this.judged(e,()=>this.faulted(e,`error`,t.reason));return}}judged(e,t){let{health:n}=e;if(n.kind!==`watching`)return;let{key:r,folder:i}=e,a;try{a=this.identityOf(r.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let o=e.identity;if(a!==`gone`&&o!==`gone`&&qc(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${R(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>W5(e.storage,r)))}faulted(e,t,n){let{key:r,folder:i}=e;e.health.kind===`watching`&&(e.health={kind:`faulted`,reason:n},this.faultCounts[t]++,r.generation===i.generation&&(i.lost=!0),this.logger(`warn`,`plugin storage fault folder=${R(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>W5(e.storage,r)))}noticed(e){switch(e.kind){case`period`:for(let e of[...this.watched.values()])this.judged(e,()=>{});return;case`moved`:case`caught-up`:this.sessions.changed(()=>!0);return}}standing(e){let t=this.watched.get(U5(e));if(t===void 0)return null;let{health:n}=t;switch(n.kind){case`faulted`:return`cannot refresh: ${e.folder} ${n.reason}; reload the config or restart the daemon`;case`watching`:case`lost`:{let t=il(this.fileEvents.delivery());return t===null?null:`cannot refresh: ${e.folder}: ${t}`}case`closed`:return null}}async read(e){let t=this.standing(e.storage);if(t!==null)return L(t);let n=H5(e),r;try{r=await f.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?I:L(`${n}: ${t.message}`)}if(r.trim()===``)return I;let i=gN(r);return i.kind===`failed`?L(`${n}: ${i.reason}`):i}async sweep(e){let t=Date.now(),n=t-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${R(e.folder)} scanned=${r} removed=${i} took=${Date.now()-t}ms`;try{let t=await f.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=o.join(e.folder,a.name);try{let{mtimeMs:r}=await f.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&V5(t.sessionId)===a.name);if(r>=n||o)continue;await f.promises.unlink(t),i++}catch(e){if(e.code!==`ENOENT`)throw e}}this.logger(`info`,a())}catch(e){this.logger(`warn`,`${a()} outcome=failed reason=${JSON.stringify(e.message)}`)}}};function K5(e){let{launcher:t,logger:n,ledger:r}=e;return{hostService:new j5({logger:n,ledger:r}),gitProvider:new P8({inner:new hX(t),watchers:e.watchers,logger:n,ledger:r}),usageStore:new a5({logger:n,ledger:r}),contextProvider:new l5({logger:n,ledger:r}),metricsProvider:new h5({logger:n,ledger:r}),activityProvider:new S5({logger:n,ledger:r}),tmuxService:new T5({launcher:t,logger:n,ledger:r}),autoCompact:new M5(n,r),cacheExpiry:new I5(n,r),managedStorage:new G5({watchers:e.watchers,fileEvents:e.fileEvents,logger:n,ledger:r}),faults:new B5,log:e.logger}}function*q5(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*J5(e){for(let t of Object.values(e.segments)){for(let e of[t.template,t.bg,t.fg,t.when])e!==void 0&&(yield e);yield*Object.values(t.partials??{})}for(let t of Tw(e.presets)){for(let n of nb(Ow(e,t).node))n.when!==void 0&&(yield n.when);let n=jw(e,t);for(let e of yy){let t=n[e];by(t)&&(yield t)}}for(let[,t]of q5(e))for(let[,e]of db(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of Hw(t))yield e}function Y5(e,t,n){let r=jU(t),i=new Set,a=new Set,o=new Set;for(let e of J5(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of dT(e,t.helpers))a.add(n);for(let n of tte(e,t.helpers))o.add(n)}for(let[,e]of q5(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 Tw(t.presets))for(let n of nb(Ow(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=>!Li(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(q5(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 X5(e){return w(`sha256`).update(JSON.stringify(e)).digest(`hex`)}var Z5=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 Q5(e){return Math.floor(Math.max(e/4,e*Hr-67108864))}const $5={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function e7(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[KU(Kw(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[Kw(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>qw(e)(t)&&t!==KU(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${EF(e,`<default>`)}: projections=${[...FU(n).keys()].join(`,`)||`-`} instantSegments=${W3(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 t7=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},n7=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${t7(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function r7(e,t,n){let r=e=>R(e.join(`,`)||`-`);return`config loaded projectDir=${R(e.projectDir)} cwd=${R(e.cwd)} cause=${R(n7(t))} state=${n} files=${R(EF(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 i7(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function a7(e,t,n){return e+`\0`+t+`\0`+(n??``)}function o7(e,t){return new Set(Tw(e.presets).filter(n=>Ow(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function s7(e){let{loaded:t,dropped:n,unreached:r}=e.state.plugins,i=[...new Set([...e.state.plugins.roots,o.join(e.projectDir,lG)])];return xT({named:[...TG(e.projectDir,e.cwd,e.configFile),...i,...t.map(e=>e.path),...[...n,...r].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))],whole:i})}function c7(e){return e.filter(Boolean).join(`
|
|
486
|
+
`)||null}const l7=e=>e instanceof Error?e.message:String(e);function u7(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function d7(e){let{loaded:t,chain:n}=e;return X5({cwd:e.cwd,chain:{layers:n.layers,home:n.home,repo:n.repo},loaded:{layers:t.layers.map(e=>({path:e.path,raw:e.raw,config:e.config,plugins:u7(e.plugins),source:null,warnings:null})),base:t.base,installed:{...u7(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 f7(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 p7(e,t,n){let r=[];try{let i=WG(t.layers,gK,{warned:e=>r.push(...e)},{repo:t.repo,cwd:e}),a={cwd:e,chain:t,loaded:i,sources:f7(i.config,n)};return{kind:`resolved`,...a,key:d7(a),warnings:r}}catch(e){return e instanceof Cb&&r.push(...e.warnings),{kind:`failed`,cause:e,warnings:r}}}function m7(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??gK,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new XT,m=new RN(t.launcher,p,o.globals.default_empty_value??``,t.sessionState,null,t.ledger,t.fileEvents,t.watchers),h;try{h=R3(o,m,n,t.compile??L3(t.signer),y7),f.push(...h.loadWarnings);let r=m.view();f.push(...V3(o,r,n,b7)),r.dispose(),sq(o),uB(o);for(let n of new Set(e.sources.values()))m.own(t.storage.watch(n))}catch(e){return m.dispose(),e instanceof Cb&&f.push(...e.warnings),{kind:`failed`,cause:e,warnings:f}}return{kind:`built`,state:{config:o,dropped:c,compileKey:h.compileKey,loadKey:e.key,buildWarnings:f,store:p,registry:m,compiled:h.compiled,neededInputPaths:UX(o),authoredRoots:o7(l,u),fileHeldSettings:qK(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>Y5(e.raw,i.placed,d)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{checkout:s.checkout,roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering},sources:e.sources}}}function h7(e,t,n,r){let i={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:Math.round(performance.now()-e.started)},a=t=>c7([...e.advisories,...n,...t]);switch(r.kind){case`built`:case`kept`:return{...i,kind:r.kind,warning:a(r.state.buildWarnings),state:r.state,error:null};case`failed`:return{...i,kind:`failed`,warning:a(r.warnings),state:null,error:l7(r.cause),cause:r.cause}}}function g7(e,t,n,r,i=null){let a=p7(t,n,r.storage);if(a.kind===`failed`)return h7(e,n,[],a);let o=i?.loadKey===a.key?{kind:`kept`,state:i}:m7(a,r);return h7(e,n,a.warnings,o)}function _7(e,t,n,r,i=null){let a=performance.now(),o=kG(kq().read(),e,t,n),{repos:s}=o,c={layers:o.kind===`chain`?o.layers:[],home:o.home,repo:s.plugins};return g7({repos:s,advisories:[IG(e,t),PG(o),SG(s)],started:a},t,c,r,i)}function v7(e,t,n){let r=p7(e,{layers:[],home:``,repo:t},n.storage),i=r.kind===`failed`?r:m7(r,n);if(i.kind===`failed`)throw Error(`bundled default failed to load: ${l7(i.cause)}`,{cause:i.cause});return i.state}const y7=new Set([`directory`]),b7=new Set([`view`]);function Ite(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new Z5;V3(e.config,l,t,b7);let d=()=>wK(e.config,e=>r.get(c,e)),f=(t,n)=>{try{let r=e.neededInputPaths(n),{result:{lanes:a,faults:o},acquired:l,released:d}=u.declare(()=>i(u,t,r,e.sources));for(let e of o)s(`error`,`session view declaration threw sid=${JSON.stringify(c)} ${e}`);return l+d>0&&s(`info`,`session view declared sid=${JSON.stringify(c)} acquired=${l} released=${d} held=${u.size}`),a}catch(t){return s(`error`,`session view declaration threw sid=${JSON.stringify(c)}: ${String(t)}`),eZ(L(`view declaration threw: ${String(t)}`),[...e.sources.keys()])}},p=(e,t)=>({facts:e,preset:t,lanes:f(e,t)}),m=X.observable.box(p(n,d()),{deep:!1}),h=(e,t)=>{let n=m.get();if(e===n.facts&&t===n.preset)return;let r=p(e,t);(0,X.runInAction)(()=>m.set(r))},g=(0,X.reaction)(d,e=>h(m.get().facts,e),{fireImmediately:!0}),_=a({sessionId:c,state:e,store:l.variableStore,declared:()=>m.get()});d3(e.compiled,l.variableStore,l,_);let v=(0,X.reaction)(()=>{let{sources:t,...n}=m.get().lanes;return[_.payload(),_.selections(),l.published(),e.registry.published(),...[...Object.values(n),...t.values()].map(e=>e.current())]},()=>o(c),{equals:X.compareShallow,fireImmediately:!0,onError:e=>s(`error`,`session view change threw sid=${JSON.stringify(c)}: ${String(e)}`)});return{sessionId:c,state:e,store:l.variableStore,registry:l,holds:u,source:_,requested:e=>h(e,d()),facts:()=>m.get().facts,lanes:()=>m.get().lanes,lastRenderCellsBySegment:new Map,retire:v,dispose:()=>(g(),v(),u.close(),l.dispose())}}var Lte=class{entries=new Map;answersWatch;sweep=null;closed=!1;holds=new Map;views=new Map;copies=new Map;viewHolds=new Map;pins=new Map;openFailures=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Ie,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},f.mkdirSync(Dq(),{recursive:!0});let{dir:n,name:r}=yT(Oq());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)??U3(t,this.deps.signer)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760+this.views.size*2621440}getOrCreate(e,t,n){let r=a7(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.load(e,t,n,null);a.state!==null&&this.log(`info`,e7(a.layers,a.state,a.ms));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,repos:a.repos,lastError:a.error,lastWarning:a.warning,state:a.state??v7(t,a.repos.plugins,this.deps),watch:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${Lr(this.accountedBytes())}/${Lr(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o,[],{kind:`open`},a.kind),o}hold(e,t,n){let r=this.getOrCreate(e,t,n);return this.holdState(r,r.state)}holdState(e,t){let n=this.holdOf(t);n.holders++,this.armSweep();let r=!1;return{entry:e,state:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache hold released twice`);r=!0,n.holders--,this.reclaim(t,n)}}}holdSession(e,t,n,r){let i=this.hold(e,t,n),a,o;try{a=this.viewOf(i.entry,i.state,r,`request`),o=this.leaseOf(a)}catch(e){throw i[Symbol.dispose](),e}return o.read=!0,this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}follow(e,t,n,r){try{var i=jo();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(a7(t,n,r));if(a!==void 0&&s?.state===a.state)return;let c=i.u(this.hold(t,n,r));this.viewOf(c.entry,c.state,o,`click`)}catch(e){i.e=e}finally{i.d()}}pin(e){this.pins.set(e,(this.pins.get(e)??0)+1);let t=!1;return()=>{if(t)throw Error(`render-cache pin released twice`);t=!0;let n=(this.pins.get(e)??0)-1;n>0?this.pins.set(e,n):this.pins.delete(e)}}viewOf(e,t,n,r){let{sessionId:i}=n,a=this.views.get(i);if(a?.state===t)return this.views.delete(i),this.views.set(i,a),a.requested(n),a;this.views.delete(i);let o=a!==void 0&&this.leaseOf(a).read,s;try{s=this.opened(e,t,n,o,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),s}opened(e,t,n,r,i){let{sessionId:a}=n,o;try{o=Ite(t,e.cwd,n,{sessionState:this.deps.sessionState,declare:this.deps.declare,source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(a,{error:e,facts:n}),e}return this.openFailures.delete(a),this.views.set(a,o),this.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}leaseOf(e){let t=this.viewHolds.get(e);if(t===void 0)throw Error(`render-cache view never served`);return t}retireView(e,t){this.views.get(e.sessionId)===e&&this.views.delete(e.sessionId),this.views.has(e.sessionId)||this.copies.delete(e.sessionId),e.retire();let n=this.leaseOf(e);n.retired={reason:t,held:n.holders},this.reclaimView(e,n)}reclaimView(e,t){t.retired===null||t.holders>0||(this.viewHolds.delete(e),this.log(`info`,`session view closed sid=${JSON.stringify(e.sessionId)} reason=${t.retired.reason} released=${e.dispose()} held=${t.retired.held} views=${this.views.size}`))}armSweep(){this.sweep===null&&(this.sweep=setInterval(()=>this.releaseIdle(),15e4),this.sweep.unref?.())}releaseIdle(){for(let[e,t]of this.viewHolds)t.retired!==null||this.pins.has(e.sessionId)||(t.read?t.read=!1:this.retireView(e,`idle`));for(let e of this.openFailures.keys())this.pins.has(e)||this.openFailures.delete(e);this.entries.size===0&&this.sweep!==null&&(clearInterval(this.sweep),this.sweep=null)}close(){if(this.closed)return;this.closed=!0,this.sweep!==null&&clearInterval(this.sweep),this.sweep=null,this.answersWatch.release();let e=this.entries.size;for(let[e,t]of this.entries)this.drop(e,t,`close`);this.log(`info`,`render-cache closed entries=${e} deferred=${this.stats.retired}`)}load(e,t,n,r){if(this.closed)throw Error(`render cache used after close`);return _7(e,t,n,this.deps,r)}drop(e,t,n){t.watch?.held.handle.release(),this.entries.delete(e),this.retire(t.state,n,null)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;let n=0;for(let e of this.viewHolds.values())e.retired!==null&&n++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,views:this.views.size,pinned:this.pins.size,retiredViews:n,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes(),n=new Set([...this.pins.keys()].flatMap(e=>{let t=this.views.get(e);return t===void 0?[]:[t.state]}));for(let[r,i]of this.entries){if(t())return;i===e||n.has(i.state)||this.drop(r,i,`evict`)}t()||this.log(`warn`,`render-cache over budget entries=${this.entries.size} views=${this.views.size} pinned=${n.size} accounted=${Lr(this.accountedBytes())}/${Lr(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`,i7(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}sessionsOn(e){return[...this.views.values()].filter(t=>t.state===e.state).map(e=>e.sessionId)}reload(e,t,n,r){this.reloadInto(this.getOrCreate(e,t,n),r)}reloadInto(e,t){let n=this.sessionsOn(e),r=e.state,i=this.load(e.projectDir,e.cwd,e.configFile,r);e.lastWarning=i.warning,e.lastError=i.error,i.state!==null&&this.log(`info`,e7(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=s7(e),{targets:r,unresolved:i}=n,a=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${n.key}`,{watch:o,move:s}=this.deps.watchers.follow(e.watch?.held??null,{...n,key:a},t=>this.reloadInto(e,{kind:`config-watch`,heard:t}));if(e.watch={derived:{...n,key:a},held:o},s!==`kept`){this.log(`info`,`config watch bound projectDir=${e.projectDir} cwd=${e.cwd} dirs=${r.dirs.map(e=>e.path).join(`,`)} deaf=${o.handle.deaf.length}`);for(let{path:t,reason:n}of i)this.log(`warn`,`config watch unresolved projectDir=${e.projectDir} path=${t} reason=${n}`)}}get size(){return this.entries.size}latestView(){return[...this.views.values()].at(-1)??null}delivered(e,t,n){if(!this.views.has(e))return;let r=this.copies.get(e)??new Map;this.copies.set(e,r.set(t,n))}drawnCopy(e,t,n){return this.copies.get(e)?.get(t)?.get(n)}stopDrawing(e,t){this.copies.get(e)?.delete(t)}};const Rte=e=>!qJ(e)&&!mL(e)&&e!==`update.dismissed`&&e!==Vi;var zte=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))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:HJ(e,Rte,(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 Y(`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)})}};function Bte(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>TK(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return uZ({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...JK(n.config,n.fileHeldSettings,a),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})});return{payload:()=>s.read(),effective:()=>o.read(),selections:()=>o.read()}}}const x7=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,S7=`#{session_id} #{client_control_mode} #{pane_id}`;function C7(e){let t=new Set;for(let n of e.split(`
|
|
487
|
+
`)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function w7(e,t){let n=new Set;for(let r of e.split(`
|
|
488
|
+
`)){let[e,i,a,o,s,c]=r.trim().split(` `);e===void 0||e===``||i===void 0||Number(a)>0&&(o===`1`||t.has(i))&&(s!==`1`||c===`1`)&&n.add(e)}return n}function Vte(e,t){let n=new Map;for(let t of e.split(`
|
|
489
489
|
`)){let[e,r]=t.trim().split(` `);e!==void 0&&e!==``&&r!==void 0&&n.set(e,r)}let r=new Map;for(let e of t.split(`
|
|
490
|
-
`)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var
|
|
491
|
-
`).map(e=>e.split(` `)[0]??``),a={};for(let e of
|
|
492
|
-
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=K7(i,a,this.deps.owner);o.kind===`ours`?t.layouts.set(n,{prior:o.prior,rows:[],status:o.status}):this.leave(e,t,n,o.why)}let r=(await this.ask(e,[H7(`@cc-candybar-binding-prior`)]))?.[0]??``;if(r!==``)try{let e=JSON.parse(r);e.owner===this.deps.owner&&(t.binding={kind:`adopted`,prior:e.prior})}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${k7} does not read (${String(t)}), left as it is`)}(t.layouts.size>0||t.binding.kind===`adopted`)&&this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)||`-`} binding=${t.binding.kind}`)}leave(e,t,n,r){t.left.set(n,r),this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} session ${n} left as it is: ${r}`)}async install(e,t,n){let r=await this.ask(e,tne(n));if(r===null||this.closed)return null;let i=nne(n,r,this.deps.owner);if(i.kind===`theirs`)return this.leave(e,t,n,i.why),null;let a={prior:i.prior,rows:[],status:i.kind===`ours`?i.status:i.prior.base};return t.layouts.set(n,a),i.kind===`lay-out`&&await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} session ${n} base=${i.prior.base} own=${[i.prior.status===null?[]:[`status`],i.prior.formats===null?[]:[`status-format`]].flat().join(`,`)||`-`}`),a}async draw(e,t,n,r){let i=n.prior.base+r.length,a=[];if(r.forEach((e,r)=>{n.rows[r]!==e&&a.push([`set-option`,`-t`,t,M7(r),e])}),i!==n.status){let e=Qte(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,O7,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,ene(a)]]))&&(n.rows=r,n.status=i)}async restore(e,t,n){let r=t.layouts.get(n);if(r===void 0)return;t.layouts.delete(n);let i=await this.ask(e,q7(n));if(i===null)return;let a=J7(n,r.prior,i);await this.write(e,a.commands),this.saidRestored(e,n,a.kept)}saidRestored(e,t,n){this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} restored session ${t} kept=${n.join(`,`)||`-`}`)}async installBinding(e,t){let n=t.binding;if(n.kind===`ours`||n.kind===`left`)return;let r=await this.ask(e,Y7);if(r===null||this.closed)return;let i=X7(r[0]??``);if(n.kind===`none`&&Q7(i)){t.binding={kind:`left`,why:`another cc-candybar daemon's status-line clicks are bound to MouseDown1Status; left as it is, so this daemon's are off`},this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.binding.why}`);return}let a=n.kind===`adopted`&&Q7(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...A7,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${L7(`${this.deps.handler} ${ine(e)}`)}`,...a===null?[]:[a.command]],[`set-option`,`-g`,`@cc-candybar-binding-prior`,JSON.stringify(o)]])){t.binding=n;return}this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} bound MouseDown1Status (was ${a===null?`unbound`:JSON.stringify(a.line)})`)}async restoreBinding(e,t){let n=t.binding;if(t.binding={kind:`none`},n.kind!==`ours`&&n.kind!==`adopted`)return;let r=await this.ask(e,Y7);if(r===null)return;let i=$7(n.prior,r[0]??``);for(let t of i.steps)await this.write(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.said}`)}writeBindingRestoreSync(e,t,n,r){let i=$7(n,r);for(let n of i.steps)this.writeSync(e,t,[n.command],n.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(t)} ${i.said}`)}counted(e,t){let n=this.serverOf(e);return t.kind===`ok`?(n.lastFailure=null,t):(this.failedWrites++,n.lastFailure!==t.reason&&this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.reason}`),n.lastFailure=t.reason,t)}async run(e,t,n){return this.counted(e,await this.deps.edge.run(e,t,n))}async ask(e,t){let n=await this.run(e,z7(t));return n.kind===`ok`?B7(n.stdout,t.length):null}askSync(e,t,n){let r=this.counted(t,e(t,z7(n)));return r.kind===`ok`?B7(r.stdout,n.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,I7(t),n)).kind===`ok`)}writeSync(e,t,n,r){n.length!==0&&(this.writes++,this.counted(t,e(t,I7(n),r)))}};function one(e){try{return wa(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),e9=e=>({arity:e,keep:!1}),sne={"--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":e9(`none`),"--background":e9(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":e9(`optional`),"-c":e9(`none`),"--continue":e9(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":e9(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":e9(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":e9(`none`),"--forward-subagent-text":$(`none`),"--from-pr":e9(`optional`),"-h":e9(`none`),"--help":e9(`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":e9(`none`),"--print":e9(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":e9(`optional`),"--resume":e9(`optional`),"--safe-mode":$(`none`),"--session-id":e9(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":e9(`optional`),"--tmux":e9(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":e9(`none`),"--version":e9(`none`),"-w":e9(`optional`),"--worktree":e9(`optional`)},cne={resume:`--resume`,fresh:`--session-id`};function lne(e){return[cne[e.kind],e.sessionId]}const t9=e=>e.startsWith(`-`)&&e!==`-`;function n9(e,t){let n=r9(t);return n===null?{dir:e??t,args:[]}:e!==null&&une(e,n.top)?{dir:e,args:[]}:{dir:e===null||r9(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const une=(e,t)=>e===t||e.startsWith(t+o.sep);function dne(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!t9(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=sne[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=>!t9(e)):o.arity===`variadic`?fne(n.slice(r),e=>!t9(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 r9(e){let t=e.split(o.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(o.sep),repo:t.slice(0,n-1).join(o.sep)||o.sep}}function fne(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const i9=`candybar-band@cc-candybar`,pne=o.join(`bin`,`cc-candybar-native`),a9=`@cc-candybar-bar-pane`,mne=yL(`/reload-plugins`),o9=e=>({kind:`done`,said:e});function s9(e){let t=q$(e.hints.tmux);if(t.kind===`refused`)throw new Y(t.reason);return t.hint}const hne={band:{on:async(e,t,n)=>{let r=nt(t.bundle);if(r===null)throw new Y(`${ax.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=o.join(r,pne);if(!n.fileExists(i))throw new Y(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${i9} from ${r}`,finished:gne(e,r,n)}},off:async()=>o9(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:async(e,t,n)=>{let r=s9(e),i=He(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new Y(`${ax.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:yne(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:async()=>o9(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>{let r=s9(e),i=await n.barPanes(r);return i.length>0?o9(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):o9(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:async(e,t,n)=>{let r=q$(e.hints.tmux);if(r.kind===`refused`)return o9(`no bar pane to close: ${r.reason}`);let i=r.hint,a=await n.barPanes(i);for(let e of a)await n.closePane(i,e);return o9(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:async e=>o9(`the daemon draws ${s9(e).pane}'s bar in its status line`),off:async()=>o9(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function gne(e,t,n){let r={sessionId:e.sessionId,projectDir:e.origin.projectDir,claudeConfigDir:e.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,i9],r);let i=await J$(n.claudeInput,e.hints.tmux,mne);if(i.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${i.reason} — or type /reload-plugins yourself`);return`installed ${i9} from ${t} and typed /reload-plugins into ${i.pane}`}const _ne=new Set([Jo,SF]);function vne(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function yne(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,Ue(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}) — ${ax.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);if((await r.paneClaude(t)).pid!==i.pid)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}), so it was not restarted under the attach launcher`);let o=wne(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${ax.statusline.label} off and on again`);let s=bne(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=dne(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=vne(i.env),u=l.get(`PATH`),d=r.launcherNode(u);if(d.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${d.why}`);let f=r.onPath(`claude`,u)===i.executable?`claude`:i.executable,p=[...l].filter(([e])=>_ne.has(e)),m=(e,t)=>Ke(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...lne(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${15e3/1e3} s of SIGTERM, so it was not restarted under the attach launcher`);let h=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),g=xne(e,r.presence(e.transcript)),_=g.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:g,v;try{v=await r.paneDir(t,i.parent)}catch(e){throw h(`the directory it was started in could not be read (${e.message})`,m(n9(null,i.cwd),_))}let y=m(n9(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{await r.typeShellLine(t,y)}catch(e){throw h(`the line could not be typed into its pane (${e.message})`,y)}if(!await r.followed(e.sessionId,`statusline`,3e4))throw Error(`Claude Code in ${t.pane} did not come back attached within ${3e4/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${Sne[g.kind](e.sessionId)}, and its statusline follows lane B`}function bne(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 xne(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const Sne={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},Cne={"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 wne(e){let t=H$(e);return t.kind===`ready`?G$(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:U$(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:Cne[t.kind]}var Tne=class{owed=new Map;setups=new qC;constructor(e){this.deps=e}clicked(e,t,n,r){let i=ox.filter(e=>n[e]!==r[e]),a=this.take(e);for(let e of i)a.has(e)||a.set(e,n[e]);let o=e=>i.includes(e)?`click`:`owed`;if(t!==null){this.settle(t,a,r,o);return}for(let[e,t]of a)t===r[e]&&a.delete(e);if(i.length>0){let t=[...a.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}a.size>0&&this.owed.set(e,a);for(let[e,t]of this.owed){if(this.owed.size<=1024)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t){this.settle(e,this.take(e.sessionId),t,()=>`owed`)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r){for(let[i,a]of t)n[i]===a?this.deps.log(`info`,`lane: ${i} ${a?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(i)} (session=${e.sessionId})`):this.start(e,i,n[i],r(i))}start(e,t,n,r){this.deps.defer(()=>void this.setups.run(e.sessionId,()=>this.sync(e,t,n,r)))}async sync(e,t,n,r){let i=`by=${r} (session=${e.sessionId})`,a=r=>{let a=`lane: ${t} ${n?`on`:`off`}: ${r instanceof Error?r.message:String(r)}`;this.deps.log(`warn`,`${a} ${i}`),Ec(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=await hne[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){a(e);return}this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`underway`&&await o.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${i}`),a)}};function c9(e,t,n){for(let r of(t??``).split(o.delimiter)){if(!o.isAbsolute(r))continue;let t=o.join(r,e);if(n(t))return t}return null}function l9(e,t){try{return f.accessSync(e,t),f.statSync(e).isFile()}catch{return!1}}function Ene(e){try{return f.realpathSync(e)}catch{return o.resolve(e)}}function Dne(e,t,n){let r=c9(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:o.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 u9=2e3;async function d9(e,t,n,r){let i=await _c(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function f9(e,t){if(t.ok)return t.stdout;let n=t.error??[t.reason,t.stderr.trim(),t.stdout.trim()].filter(e=>e!==``).join(`: `);throw Error(`${e} failed (${n})`)}function One(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 kne=`#{pane_id} #{${a9}}`;function Ane(e,t){return e.split(`
|
|
493
|
-
`).
|
|
494
|
-
`);async function Pne(e,t){if(process.platform===`linux`)return{executable:await f.promises.readlink(`/proc/${t}/exe`),argv:(await f.promises.readFile(`/proc/${t}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await f.promises.readFile(`/proc/${t}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let n=f9(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,Nne,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function p9(e,t,n){return f9(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function m9(e,t){let n=await _c(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 p9(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function Fne(e,t){let{panePid:n,cwd:r,foreground:i}=await m9(e,t),a=await p9(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await Pne(e,i),s=NY(a).get(i)?.ppid;if(s===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);return{pid:i,executable:await f.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:s,fromShell:i!==n,attached:Mne(a,i,n)}}function Ine(e,t,n){let r=e=>xe(e,void 0,{signal:n});return{claudeInput:$$(e),barPanes:async t=>Ane(await d9(e,t,[`list-panes`,`-a`,`-F`,kne]),t.pane),openBarPane:async(t,n,r)=>{let i=(await d9(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();return await d9(e,t,[`set-option`,`-p`,`-t`,i,a9,t.pane]),i},closePane:async(t,n)=>void await d9(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void f9(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],env:bY(process.env,n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>f.existsSync(e),presence:mG,paneClaude:t=>Fne(e,t),paneDir:async(t,n)=>{let i=Date.now()+u9;for(;;){let a=await m9(e,t);if(a.foreground===n){if(a.cwd===``)throw Error(`tmux read no directory for pane ${t.pane}`);return a.cwd}if(Date.now()>i)throw Error(`the shell in pane ${t.pane} (pid ${n}) did not take its terminal back within ${u9/1e3} s`);await r(100)}},launcherNode:e=>Dne(e,e=>l9(e,f.constants.X_OK),Ene),onPath:(e,t)=>{let n=c9(e,t,e=>l9(e,f.constants.X_OK));return n===null?null:f.realpathSync(n)},followed:async(e,n,i)=>{let a=Date.now()+i;for(;!t(e).has(n);){if(Date.now()>a)return!1;await r(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`?One(i.stdout):null;return a===null?(f9(`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=Date.now()+t;for(;ac(e);){if(Date.now()>n)return!1;await r(100)}return!0},typeShellLine:async(t,n)=>void await d9(e,t,Z$(t.pane,`cc-candybar-lane`,[]),n)}}const Lne=[`request`,`feed`],h9=new WeakMap;let Rne=0;const g9=e=>{let t=h9.get(e);if(t!==void 0)return t;let n=Rne++;return h9.set(e,n),n};var zne=class{records=new Map;constructor(e=512){this.maxRecords=e}of(e,t){return this.records.get(_9(e,t))?.warnings??[]}ofSession(e,t,n){let r=g9(n.config),i=[];for(let n of Lne){let a=this.records.get(_9(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=_9(e,t);this.records.delete(a),this.records.set(a,{generation:g9(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 _9=(e,t)=>`${t}\0${e}`;var Bne=class{queue=new qC;sessions=new qC;gathers=new qC;open=!0;inFlight=null;holder=null;queued=0;gathersInFlight=0;constructor(e){this.deps=e}take(e,{waited:t,gone:n},r){let i=this.deps.monotonic();return this.queued++,this.queue.run(`journals`,async()=>{if(this.queued--,this.refuseClosed(e),n())throw new YC(e);let a=this.deps.monotonic();t(Math.round(a-i)),this.holder={verb:e,since:a};try{return await r({holds:t=>{let n={verb:e,commit:t};return this.inFlight=n,()=>this.commit(n)},landed:t=>t.finally(()=>this.refuseClosed(e))})}finally{this.holder=null}})}click(e,t,{placed:n,waited:r,gone:i,gathered:a},o,s){let c=this.deps.monotonic(),l=async()=>{if(n(Math.round(this.deps.monotonic()-c)),this.refuseClosed(e),i())throw new YC(e);let t=this.deps.monotonic(),l=await o();a(Math.round(this.deps.monotonic()-t));let u=i();return this.take(e,{waited:r,gone:()=>!u&&i()},e=>s(l,e))};return t===null?l():this.sessions.run(t,l)}async gathering(e){this.gathersInFlight++;try{return await this.gathers.run(`gathers`,e)}finally{this.gathersInFlight--}}getStats(){let{holder:e,queued:t}=this;return{holder:e?.verb??null,heldMs:e===null?0:Math.round(this.deps.monotonic()-e.since),queued:t,gathers:this.gathersInFlight}}close(){this.open=!1,this.inFlight!==null&&(this.deps.log(`warn`,`journal: ${this.inFlight.verb} cut off by close, committing what landed`),this.commit(this.inFlight))}refuseClosed(e){if(!this.open)throw new JC(e)}commit(e){return this.inFlight===e?(this.inFlight=null,e.commit(),!0):!1}},Vne=class{sessions=new Map;pending=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}clickArrived(e){this.pending.set(e,(this.pending.get(e)??0)+1),this.sessions.has(e)&&this.settle(e)}clickSettled(e){let t=this.pending.get(e)-1;t===0?this.pending.delete(e):this.pending.set(e,t),this.sessions.has(e)&&this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown&&!this.pending.has(e)?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;let t=0;for(let e of this.pending.values())t+=e;return{sessions:this.sessions.size,armed:e,pending:t}}dispose(){this.disposed=!0;for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null,closing:!1};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=256)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown&&!t.closing&&!this.disposed&&!this.pending.has(e)?zee(t.since,t.timeoutS):null;if(t.timer?.at===n||(this.disarm(t),n===null))return;let r=setTimeout(()=>this.fire(e),Math.max(0,(n-this.deps.now())*1e3));r.unref(),t.timer={at:n,handle:r}}disarm(e){e.timer!==null&&clearTimeout(e.timer.handle),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now(),r={idleS:n-t.since,timeoutS:t.timeoutS,stillIdle:()=>this.sessions.get(e)===t&&!this.pending.has(e),closed:()=>{t.since=n,t.shown=!1}};t.closing=!0,this.deps.close(e,r).catch(t=>{r.closed(),this.deps.failed(e,t)}).finally(()=>{t.closing=!1,this.sessions.get(e)===t&&this.settle(e)})}};const Hne={date:()=>new Date,monotonic:()=>performance.now(),after:TX};let v9=null;function Une(e){if(v9!==null&&!v9.aborted)throw Error(`a daemon is already live in this process`);let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a}=e,o=()=>GM(i.date()),s=new AbortController,c=!1,l=(e,t)=>pr(e,c?`after close: ${t}`:t),u=new p$,d=Kn({stats:u.launchStats,signal:s.signal,observeLifeline:e=>{l(e===null?`info`:`warn`,e===null?`launch lifeline running again`:`launch lifeline ${e}; the next launch starts another`),se.wakeWhere(`data`,()=>!0)}}),p=e.storage(l),m=new WJ(p.session),h=new ZJ(m,l,p.history),g=Kr(Qr(u.startedAt.getTime(),a,{launcher:d,log:l},{limitBytes:n})),_=new O$,v=new Nte,y=FQ(mt()),b=new OT({counters:u,logger:l}),x=new yN(l),S=new nl({watchers:b,logger:l}),C=G5({launcher:d,watchers:b,fileEvents:S,logger:l,ledger:x}),{gitProvider:ee,usageStore:te,tmuxService:w,hostService:ne,managedStorage:T}=C,re=new Bte,E=new Hee,D=new Vne({now:o,close:(e,t)=>D0(e,t,ve),failed:(e,t)=>l(t instanceof JC?`info`:`error`,`menu-idle: close failed (session=${e}): ${le(t)}`)}),ie=Sc(),O=new Ac({supersede:(e,t)=>T.supersede(e,t),launch:d.launch,state:m,log:l,now:o}),ae=new Tne({edge:Ine(d,e=>se.following(e),s.signal),host:{bundle:t.path,node:t.node,socket:_t(),preload:Ds(t.path)},state:m,log:l,now:o,defer:e=>void pe(e)}),oe=new ane({edge:{run:(e,t,n)=>_c(d,{socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>se.subscribe(e,t),sessionInPane:(e,t)=>se.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${ze(_t())}`,...[...t.node,t.path].map(ze),`url-handle`].join(` `),owner:_t(),log:l}),se=new a6({render:(e,t,n)=>h6(ye,e,t,n),watch:(e,t)=>(0,X.reaction)(()=>m.revision(e),t),lanes:e=>_6(ye,e),pin:e=>{let t=fe.pin(e);return()=>{fe.stopDrawing(e,`feed`),t()}},shown:e=>ce.shown(e.hints.tmux),watching:()=>ce.follow(),refreshes:()=>x.totals(),periods:$3,now:()=>i.monotonic(),instant:o,log:l}),ce=new Ute({listPanes:e=>_c(d,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,b7]),listClients:e=>_c(d,{socket:e},`frames.visibility`,[`list-clients`,`-F`,x7]),sockets:()=>new Set(se.watched().flatMap(({req:e})=>ue(e))),onAnswer:(e,t)=>oe.answered(e,t),onChange:e=>se.wakeWhere(`visibility`,t=>ue(t).some(t=>e.has(t))),intervalMs:1e3,log:l});function ue({hints:{tmux:e}}){return e==null?[]:[e.socket]}let de=new zne,fe=new Rte({launcher:d,sessionState:m,watchers:b,log:l,storage:T,signer:ie,ledger:x,fileEvents:S,declare:(e,t,n,r)=>nZ(C,e,t,n,r),source:Vte({providers:C,sessionState:m,history:e=>h.depth(e),navigation:(e,t)=>re.depth(e,m,sq(t))})},{budgetBytes:()=>Z5(n),observers:{onReload:(e,t,n,r)=>{l(`info`,n7(e,n,r));for(let e of t)se.wake(e,`reload`)},onViewChanged:e=>se.wake(e,`data`)}});S.subscribe(e=>{switch(e.kind){case`period`:b.judge();return;case`caught-up`:fe.reloadEvery({kind:`events-resumed`,since:e.since}),se.wakeWhere(`data`,()=>!0);return;case`moved`:se.wakeWhere(`data`,()=>!0);return}});let me=60*1e3,he=y8({targets:t.targets,intervalMs:me,stat:f.statSync,held:()=>ge.running(),exit:()=>a(0),log:l}),ge=wq({launcher:d,entryUrl:t.entryUrl,digest:t.digest,actsDir:AC(mt(),t.path),intervalMs:me,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:fetch,onApplied:()=>he.checkNow(),log:l}),_e=new Bne({log:l,monotonic:()=>i.monotonic()}),ve={sessionState:m,journalTurns:_e,clickLanded:e=>D.clicked(e,o()),log:l,launcher:d,now:o,applyUpdate:()=>ge.act(),doctor:qQ(d,e=>{let t=[e.projectDir,e.cwd,e.target.path];fe.reload(...t,{kind:`doctor`});let n=fe.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:y,probes:_,clients:v,bundle:t.path,serving:()=>g.serving(),claudeInput:$$(d),history:h,navigation:re,configFor:e=>fe.getOrCreate(e.projectDir,e.cwd,e.target.path).state.config,reloadConfig:e=>fe.reload(e.projectDir,e.cwd,e.target.path,{kind:`write`}),sourcesFor:e=>fe.getOrCreate(e.projectDir,e.cwd,e.target.path).state.sources,links:ie,runs:O,lanes:{of:(e,t)=>v6(ye,e,t),clicked:(e,t,n)=>O6(ye,e,t,n)},views:{follow:(e,t)=>fe.follow(e,t.projectDir,t.cwd,t.target.path)},diagnosticCopy:(e,t,n)=>fe.drawnCopy(e,t,n)},ye={launcher:d,log:l,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:y,stats:u,handlerProbes:_,renderSightings:v,watcherRegistry:b,refreshLedger:x,fileEvents:S,payloadProviders:C,sessionState:m,effectSessions:E,menuIdle:D,journalTurns:_e,linkSigner:ie,runs:O,laneSetups:ae,tmuxStatusLines:oe,frameFeeds:se,renderWarnings:de,renderCache:fe,updateWatch:ge,limits:g,verbCtx:ve};return v9=s.signal,{stats:u,launcher:d,log:l,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(s.signal.throwIfAborted(),a8(ye,e,t,n,r)),reply:async(e,t,n,r)=>(s.signal.throwIfAborted(),o8(ye,e,t,n,r)),subscribe:(e,t)=>(s.signal.throwIfAborted(),se.subscribe(e,t)),reloadConfig:e=>{s.signal.throwIfAborted(),ve.reloadConfig(e)},arm(){s.signal.throwIfAborted(),S.start(kt()),he.arm(),ge.arm(),g.arm()},close(e){let t=[[`journalTurns close`,()=>_e.close()],[`tmuxStatusLines restore`,()=>oe.restoreAll(e)],[`launches abort`,()=>s.abort(Error(`the daemon closed`))],[`frameFeeds close`,()=>se.close()],[`menuIdle dispose`,()=>D.dispose()],[`updateWatch close`,()=>ge.close()],[`binaryWatch close`,()=>he.close()],[`limits disarm`,()=>g.disarm()],[`renderCache close`,()=>fe.close()],[`gitService close`,()=>ee.close()],[`usageStore close`,()=>te.close()],[`tmuxService close`,()=>w.close()],[`hostService close`,()=>ne.close()],[`runs close`,()=>O.close()],[`managedStorage close`,()=>T.close()],[`fileEvents close`,()=>S.close()],[`watcherRegistry close`,()=>b.closeAll()],[`sessionState close`,()=>m.close()]];for(let[e,n]of t)try{n()}catch(t){l(`warn`,`${e} failed: ${t.message}`)}return c=!0,d.settled()}}}const Wne=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function y9(e){if(e===void 0)return;let t=H.parse(e);if(t.isDefault)return;let n=t.fixedValue;if(n!==void 0)return n.hex;let r=t.type===V.STANDARD&&t.number!==void 0?Wne[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const Gne={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 Kne({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=y9(t),o=y9(n),s={};for(let e of r){let t=Gne[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 qne(e){return{ok:!0,band:e.rows.map(e=>BS(e).map(Kne))}}function Jne(e){return kS(qne,e)}const Yne={band:e=>JSON.stringify(Jne(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:T7(e)})};function b9(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}function Xne(e,t){t.allowHalfOpen=!1;let n=e.clock.monotonic();e.stats.inFlight++;let r=!1,i=!0,a=()=>{i&&(i=!1,e.stats.inFlight--)},o=(n,i,a)=>{if(r){i!==null&&e.log(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}r=!0,c();let o=i===null?void 0:()=>e.exit(i);try{t.end(Yt(n),e=>{e??a(),o?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),o?.()}},s=!1,c=e.clock.after(200,()=>{s=!0,e.stats.requestsTimedOut++,o({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,f6)}),l=j(r=>{e.handle(r,()=>s,n,()=>t.destroyed).then(e=>e.kind===`reply`?o(e.resp,e.exitAfterFlush,e.delivered):u(e.sessionId,e.lane)).catch(t=>{e.log(`error`,`handler threw: ${le(t)}`),o(p6(t),null,f6)})},t=>{e.log(`warn`,`frame parse failed: ${t.message}`),o({ok:!1,error:t.message,code:`BAD_REQUEST`,daemonV:3},null,f6)}),u=(n,i)=>{if(r||t.destroyed)return;c(),a(),t.off(`data`,l);let o=b9(t),s=e.subscribe(n,{lane:i,frame:(e,t)=>o(Xt(Yne[i](e,t))),refused:e=>t.end(Yt(e)),drawing:()=>!0});r=!0,t.on(`close`,s)};t.on(`data`,l),t.on(`error`,t=>{e.log(`warn`,`socket error: ${t.message}`)}),t.on(`close`,()=>{c(),a()})}function Zne(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 Qne=class{timer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t=500,n=Ie){this.filePath=e,this.debounceMs=t,this.logger=n,this.writingPath=`${e}.writing`}load(){let e;try{e=f.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 Zne(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,this.schedule()}schedule(){this.timer!==null||this.writing||(this.timer=setTimeout(()=>{this.timer=null,this.write()},this.debounceMs),this.timer.unref())}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=performance.now(),r=JSON.stringify(e),i=this.writingPath;this.writing=!0;let a=performance.now()-n;try{await f.promises.mkdir(o.dirname(this.filePath),{recursive:!0});let s=await f.promises.open(i,`w`,384);try{await s.writeFile(r),await s.chmod(384),await s.datasync()}finally{await s.close()}let c=!1;if(t===this.generation)try{await f.promises.rename(i,this.filePath),c=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){c||await f.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${c} took=${Math.round(performance.now()-n)}ms held=${Math.round(a)}ms`);return}this.saved(r,e,n,a),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending,t=performance.now();try{f.mkdirSync(o.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);f.writeFileSync(n,r,{mode:384}),f.chmodSync(n,384),f.rmSync(this.writingPath,{force:!0}),f.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,performance.now()-t),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${Math.round(performance.now()-n)}ms held=${Math.round(r)}ms`)}};function $ne(e){return{session:new Qne(Ct(),500,e),history:vY(wt(),e)}}let x9=null,S9=null,C9=null;function ere(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:it(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function tre(){t.on(`uncaughtException`,e=>{pr(`error`,`uncaughtException: ${e.stack||e.message}`),D9(1)}),t.on(`unhandledRejection`,e=>{pr(`error`,`unhandledRejection: ${String(e)}`),D9(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{pr(`info`,`received ${e}, shutting down`),D9(0)});nre().catch(w9)}function w9(e){pr(`error`,`refusing to boot: ${le(e)}`),D9(1)}async function nre(){let e=Rr(t.env);x9=await tc(t.pid,e=>$s(e,Xn.launch));let n=await dc(pc(x9));if(!n.decision.allow){pr(`warn`,`fork-bomb breaker: ${n.decision.reason}; refusing to boot`),D9(1);return}S9=n.registryPath,f.mkdirSync(gt(),{recursive:!0}),bt(_t());let r=Une({bundle:ere(),storage:$ne,memoryLimitBytes:e,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:Hne,exit:D9});C9=r,ic({anchor:rc(t.env),isAlive:ac,onOrphaned:e=>{pr(`info`,`parent watchdog: ${e}; shutting down`),D9(0)}}),T9(r,ae.createServer(e=>Xne(r,e)),_t(),!1)}function T9(e,n,r,i){n.removeAllListeners(`error`),n.removeAllListeners(`listening`),n.once(`error`,a=>{if(a.code!==`EADDRINUSE`){pr(`error`,`server error: ${a.message}`),D9(1);return}if(i){pr(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}rre(e,n,r).catch(w9)}),n.listen(r,()=>ire(e,r))}async function rre(e,n,r){let i=await Gs(Ks(xt(r)),(t,n)=>ec(t,n,{readStartTime:t=>$s(t,e.launcher.launch),pidAlive:ac}));if(i.kind===`attach-and-exit`){pr(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}pr(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{f.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){pr(`error`,`cannot unlink stale socket ${r}: ${e.message}`),D9(1);return}}T9(e,n,r,!0)}function ire(e,n){let r=Ys(n);if(r.kind!==`present`){pr(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),D9(0);return}ore(n);try{f.chmodSync(n,384)}catch(e){pr(`warn`,`chmod socket failed: ${e.message}`)}pr(`info`,`daemon up: pid=${t.pid} v=3 sock=${n} heapCap=${Lr(he.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Lr(e.memoryLimitBytes)}MB`),si(),e.arm(),are(n,r.identity)}function are(e,n){Qs({bound:n,myPid:t.pid,readIdentity:()=>Ys(e),readLease:()=>Ks(xt(e)),shutdown:e=>D9(e),log:pr}).arm()}function ore(e){let n=qs(xt(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:x9});n!==null&&pr(`warn`,`lease write failed: ${n}`)}const sre=e=>(t,n,r)=>gc(e,{socket:t},`tmux-status`,n,r);let E9=!1;function D9(e){E9||(E9=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500),C9?.close(sre(Yn)),Js(St(),t.pid),S9!==null&&fc(S9,t.pid,lc,e=>f.unlinkSync(e)),t.exit(e))}const cre={connectMs:200,budgetMs:500};async function lre(e,t){return ure(e,await dre(e),t.includes(`--json`))}function ure(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
|
|
495
|
-
`:
|
|
496
|
-
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${
|
|
490
|
+
`)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var Hte=class{servers=new Map;loop={kind:`idle`};constructor(e){this.deps=e}follow(){switch(this.loop.kind){case`idle`:this.deps.log(`info`,`visibility following`),this.ask();break;case`asking`:this.loop.following=!0;break;case`due`:break}return()=>this.stop()}stop(){switch(this.loop.kind){case`due`:clearTimeout(this.loop.timer),this.end();return;case`asking`:this.loop.following=!1;return;case`idle`:return}}ask(){let e={kind:`asking`,following:!0};this.loop=e,Promise.resolve().then(()=>this.refresh(this.deps.sockets())).catch(e=>this.deps.log(`error`,`visibility refresh threw: ${le(e)}`)).then(()=>{if(e.following){this.loop={kind:`due`,timer:setTimeout(()=>this.ask(),this.deps.intervalMs).unref()};return}this.end()})}end(){this.deps.log(`info`,`visibility stopped forgot=${this.servers.size}`),this.loop={kind:`idle`},this.servers.clear()}shown(e){if(e==null)return!0;let t=this.servers.get(e.socket);return t?.kind!==`asked`||t.shown.has(e.pane)}async refresh(e){for(let t of this.servers.keys())e.has(t)||this.servers.delete(t);let t=await Promise.all([...e].map(async e=>{let[t,n]=await Promise.all([this.deps.listPanes(e),this.deps.listClients(e)]);return[e,t.kind===`ok`?n.kind===`ok`?{kind:`asked`,shown:w7(t.stdout,C7(n.stdout)),status:Vte(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),!Ute(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 Ute(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 Wte(e){return`ccb`+w(`sha256`).update(e).digest(`hex`).slice(0,12)}const Gte=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function T7(e){if(e===void 0)return`terminal`;let t=H.parse(e);if(t.isDefault)return`terminal`;switch(t.type){case V.STANDARD:{let e=t.number===void 0?void 0:Gte[t.number];if(e!==void 0)return e;break}case V.EIGHT_BIT:if(t.number!==void 0)return`colour${t.number}`;break;case V.TRUECOLOR:{let e=t.fixedValue;if(e!==void 0)return e.hex;break}case V.DEFAULT:case V.WINDOWS:break}throw Error(`frames: no tmux colour for ${t.name}`)}const Kte={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 qte(e){return e.replaceAll(`#`,`##`)}function Jte({fg:e,bg:t,attrs:n=[]}){let r=n.map(e=>{let t=Kte[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${T7(e)}`,`bg=${T7(t)}`,...r].join(`,`)}]`}function Yte(e){let t={},n=e=>{let n=Jte(e)+qte(e.text);if(e.link===void 0)return n;let r=Wte(e.link);return t[r]=e.link,`#[range=user|${r}]${n}#[norange]`};return{rows:e.rows.map(e=>BS(e).map(n).join(``)),links:t}}function E7(e){return kS(Yte,e)}const D7=ax.tmuxStatus.rows,O7=`@cc-candybar-status-prior`,k7=`@cc-candybar-status-wrote`,A7=`@cc-candybar-binding-prior`,j7=[`-T`,`root`,`MouseDown1Status`],M7=Array.from({length:D7},(e,t)=>t),N7=e=>`@cc-candybar-row-${e}`,Xte=e=>`#[fill=terminal]#{${N7(e)}}`,P7=e=>`status-format[${e}]`;function Zte(e){return e===0?`off`:e===1?`on`:String(e)}function F7(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 Qte(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 I7(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function L7(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function R7(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function $te(e){return e.map(e=>e.map(R7).join(` `)).join(` ; `)}const z7=`ccb:separator`;function B7(e){return L7(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,z7],e]))}function V7(e,t){let n=e.split(`${z7}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const H7=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],U7=e=>[`show-options`,`-g`,`-q`,`-v`,e],W7=e=>[[`show-options`,`-t`,e],H7(e,`status`),...M7.map(t=>H7(e,P7(t)))];function G7(e){let[t=``,n=``,...r]=e,i=t.split(`
|
|
491
|
+
`).map(e=>e.split(` `)[0]??``),a={};for(let e of M7)i.includes(P7(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 K7(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,P7(Number(t)),I7(n)])]}const ene=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...W7(e),...M7.map(e=>U7(P7(e))),H7(e,O7),H7(e,k7)];function q7(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:F7(t)}catch(e){return{kind:`theirs`,why:`${O7} does not read (${String(e)})`}}return r.owner===n?{kind:`ours`,prior:r,status:i}:{kind:`theirs`,why:`the daemon at ${JSON.stringify(r.owner)} draws it`}}function tne(e,t,n){let[r=``,...i]=t,a=G7(i.slice(0,2+D7)),o=i.slice(2+D7,2+2*D7),[s=``,c=``]=i.slice(2+2*D7);if(s!==``)return q7(s,c,n);let l=F7(r),u={};for(let e=0;e<l;e++){let t=a.formats===null?o[e]:a.formats[e];t!==void 0&&t!==``&&(u[e]=t)}let d={...u,...Object.fromEntries(Array.from({length:D7-l},(e,t)=>[l+t,Xte(t)]))},f={owner:n,base:l,status:a.status,formats:a.formats,wrote:d};return{kind:`lay-out`,prior:f,commands:[[`set-option`,`-t`,e,O7,JSON.stringify(f)],...K7(e,d)]}}const J7=e=>[...W7(e),H7(e,k7)];function Y7(e,t,n){let r=G7(n.slice(0,2+D7)),i=n[2+D7]??``,a=[],o=[];if(Qte(r.formats,t.wrote))a.push(...K7(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,P7(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,I7(t.status)]):o.push(`status`)),a.push(...M7.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,N7(t)]),[`set-option`,`-q`,`-u`,`-t`,e,O7],[`set-option`,`-q`,`-u`,`-t`,e,k7]),{commands:a,kept:o}}const nne=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,X7=[[`list-keys`,`-T`,`root`]];function Z7(e){let t=nne.exec(e);return t===null?null:{line:t[0],command:t[1]}}const Q7=`cc-candybar://tmux-status-click/`,rne=e=>`${Q7}${Ca([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,$7=e=>e?.command.includes(Q7)??!1;function e9(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,A7]};return $7(Z7(t))?{steps:[e===null?{command:[`unbind-key`,...j7]}:{command:[`source-file`,`-`],stdin:`${e.line}\n`},n],said:`restored MouseDown1Status to ${e===null?`unbound`:JSON.stringify(e.line)}`}:{steps:[n],said:`left MouseDown1Status as it is: bound again since`}}var ine=class{held=new Map;servers=new Map;closed=!1;writes=0;failedWrites=0;constructor(e){this.deps=e}observe(e,t,n){if(this.closed)return;let r=this.held.get(e),i=n&&t!=null?t:null;if(r!==void 0&&(i===null||r.socket!==i.socket||r.pane!==i.pane)&&this.release(r,`switched off or moved`),i===null||this.held.has(e))return;let a={sessionId:e,socket:i.socket,pane:i.pane,unsubscribe:null,frame:null};this.held.set(e,a),this.serverOf(i.socket),this.deps.log(`info`,`tmux-status: holding sid=${JSON.stringify(e)} pane=${i.pane} socket=${JSON.stringify(i.socket)}`),a.unsubscribe=this.deps.subscribe(e,{lane:`tmuxStatus`,frame:e=>{a.frame=E7(e),this.reconcile(a.socket)},refused:t=>{this.held.get(e)===a&&this.release(a,`refused: ${t.error}`)},drawing:()=>this.draws(a)})}answered(e,t){if(this.closed)return;let n=this.serverOf(e);n.view=t;for(let n of[...this.held.values()])if(n.socket===e)if(!t.sessionOf.has(n.pane))this.release(n,`pane gone`);else{let t=this.deps.sessionInPane(e,n.pane);t!==null&&t!==n.sessionId&&this.release(n,`pane taken by sid=${JSON.stringify(t)}`)}this.reconcile(e)}draws(e){let t=this.servers.get(e.socket),n=t?.view?.sessionOf.get(e.pane);return n!==void 0&&t.layouts.has(n)&&t.view.shownBy.get(n)===e.pane}restoreAll(e){this.closed=!0;for(let e of this.held.values())e.unsubscribe?.();this.held.clear();for(let[t,n]of this.servers){for(let[r,i]of[...n.layouts]){n.layouts.delete(r);let a=this.askSync(e,t,J7(r));if(a===null)continue;let o=Y7(r,i.prior,a);this.writeSync(e,t,o.commands),this.saidRestored(t,r,o.kept)}let r=n.binding;if(n.binding={kind:`none`},r.kind===`ours`||r.kind===`adopted`){let n=this.askSync(e,t,X7);if(n===null)continue;this.writeBindingRestoreSync(e,t,r.prior,n[0]??``)}}}linkAt(e){let t=ane(e),[n,r,i,...a]=t??[];if(t===null||n===void 0||r===void 0||i===void 0||a.length>0)return{kind:`refused`,reason:`tmux-status-click needs <socket>/<pane>/<range>, got ${JSON.stringify(e)}`};let o=[...this.held.values()].find(e=>e.socket===n&&e.pane===`%${r}`)?.frame?.links[i];return o===void 0?{kind:`refused`,reason:`pane %${r}'s status line draws no link ${i} now`}:{kind:`link`,url:o}}stats(){return{sessions:this.held.size,layouts:[...this.servers.values()].reduce((e,t)=>e+t.layouts.size,0),writes:this.writes,failedWrites:this.failedWrites}}async settled(){for(let e of this.servers.values())await e.running}serverOf(e){let t=this.servers.get(e);if(t!==void 0)return t;let n={view:null,adopted:!1,layouts:new Map,left:new Map,binding:{kind:`none`},running:null,again:!1,lastFailure:null};return this.servers.set(e,n),n}release(e,t){e.unsubscribe?.(),this.held.delete(e.sessionId),this.deps.log(`info`,`tmux-status: released sid=${JSON.stringify(e.sessionId)} pane=${e.pane} — ${t}`),this.reconcile(e.socket)}reconcile(e){let t=this.servers.get(e);if(!(t===void 0||this.closed)){if(t.running!==null){t.again=!0;return}t.running=(async()=>{try{do t.again=!1,await this.step(e,t);while(t.again&&!this.closed)}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} reconcile threw: ${String(t)}`)}finally{t.running=null}})()}}async step(e,t){let n=t.view;if(n===null)return;t.adopted||(t.adopted=!0,await this.adopt(e,t));let r=new Map;for(let t of this.held.values()){if(t.socket!==e)continue;let i=n.sessionOf.get(t.pane);i!==void 0&&r.set(i,[...r.get(i)??[],t])}for(let i of new Set([...t.layouts.keys(),...t.left.keys(),...r.keys()])){if(this.closed)return;let a=r.get(i)??[],o=t.layouts.get(i);if(a.length===0){t.left.delete(i),o!==void 0&&await this.restore(e,t,i);continue}if(t.left.has(i))continue;let s=o??await this.install(e,t,i);if(s===null)continue;let c=a.find(e=>e.pane===n.shownBy.get(i))?.frame?.rows.slice(0,D7-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#{${O7}}\t#{${k7}}`]);if(n.kind===`ok`)for(let r of n.stdout.split(`
|
|
492
|
+
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=q7(i,a,this.deps.owner);o.kind===`ours`?t.layouts.set(n,{prior:o.prior,rows:[],status:o.status}):this.leave(e,t,n,o.why)}let r=(await this.ask(e,[U7(`@cc-candybar-binding-prior`)]))?.[0]??``;if(r!==``)try{let e=JSON.parse(r);e.owner===this.deps.owner&&(t.binding={kind:`adopted`,prior:e.prior})}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${A7} does not read (${String(t)}), left as it is`)}(t.layouts.size>0||t.binding.kind===`adopted`)&&this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)||`-`} binding=${t.binding.kind}`)}leave(e,t,n,r){t.left.set(n,r),this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} session ${n} left as it is: ${r}`)}async install(e,t,n){let r=await this.ask(e,ene(n));if(r===null||this.closed)return null;let i=tne(n,r,this.deps.owner);if(i.kind===`theirs`)return this.leave(e,t,n,i.why),null;let a={prior:i.prior,rows:[],status:i.kind===`ours`?i.status:i.prior.base};return t.layouts.set(n,a),i.kind===`lay-out`&&await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} session ${n} base=${i.prior.base} own=${[i.prior.status===null?[]:[`status`],i.prior.formats===null?[]:[`status-format`]].flat().join(`,`)||`-`}`),a}async draw(e,t,n,r){let i=n.prior.base+r.length,a=[];if(r.forEach((e,r)=>{n.rows[r]!==e&&a.push([`set-option`,`-t`,t,N7(r),e])}),i!==n.status){let e=Zte(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,k7,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,$te(a)]]))&&(n.rows=r,n.status=i)}async restore(e,t,n){let r=t.layouts.get(n);if(r===void 0)return;t.layouts.delete(n);let i=await this.ask(e,J7(n));if(i===null)return;let a=Y7(n,r.prior,i);await this.write(e,a.commands),this.saidRestored(e,n,a.kept)}saidRestored(e,t,n){this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} restored session ${t} kept=${n.join(`,`)||`-`}`)}async installBinding(e,t){let n=t.binding;if(n.kind===`ours`||n.kind===`left`)return;let r=await this.ask(e,X7);if(r===null||this.closed)return;let i=Z7(r[0]??``);if(n.kind===`none`&&$7(i)){t.binding={kind:`left`,why:`another cc-candybar daemon's status-line clicks are bound to MouseDown1Status; left as it is, so this daemon's are off`},this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.binding.why}`);return}let a=n.kind===`adopted`&&$7(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...j7,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${R7(`${this.deps.handler} ${rne(e)}`)}`,...a===null?[]:[a.command]],[`set-option`,`-g`,`@cc-candybar-binding-prior`,JSON.stringify(o)]])){t.binding=n;return}this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} bound MouseDown1Status (was ${a===null?`unbound`:JSON.stringify(a.line)})`)}async restoreBinding(e,t){let n=t.binding;if(t.binding={kind:`none`},n.kind!==`ours`&&n.kind!==`adopted`)return;let r=await this.ask(e,X7);if(r===null)return;let i=e9(n.prior,r[0]??``);for(let t of i.steps)await this.write(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.said}`)}writeBindingRestoreSync(e,t,n,r){let i=e9(n,r);for(let n of i.steps)this.writeSync(e,t,[n.command],n.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(t)} ${i.said}`)}counted(e,t){let n=this.serverOf(e);return t.kind===`ok`?(n.lastFailure=null,t):(this.failedWrites++,n.lastFailure!==t.reason&&this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.reason}`),n.lastFailure=t.reason,t)}async run(e,t,n){return this.counted(e,await this.deps.edge.run(e,t,n))}async ask(e,t){let n=await this.run(e,B7(t));return n.kind===`ok`?V7(n.stdout,t.length):null}askSync(e,t,n){let r=this.counted(t,e(t,B7(n)));return r.kind===`ok`?V7(r.stdout,n.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,L7(t),n)).kind===`ok`)}writeSync(e,t,n,r){n.length!==0&&(this.writes++,this.counted(t,e(t,L7(n),r)))}};function ane(e){try{return wa(e)}catch(e){if(e instanceof URIError)return null;throw e}}const $=e=>({arity:e,keep:!0}),t9=e=>({arity:e,keep:!1}),one={"--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":t9(`none`),"--background":t9(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":t9(`optional`),"-c":t9(`none`),"--continue":t9(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":t9(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":t9(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":t9(`none`),"--forward-subagent-text":$(`none`),"--from-pr":t9(`optional`),"-h":t9(`none`),"--help":t9(`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":t9(`none`),"--print":t9(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":t9(`optional`),"--resume":t9(`optional`),"--safe-mode":$(`none`),"--session-id":t9(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":t9(`optional`),"--tmux":t9(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":t9(`none`),"--version":t9(`none`),"-w":t9(`optional`),"--worktree":t9(`optional`)},sne={resume:`--resume`,fresh:`--session-id`};function cne(e){return[sne[e.kind],e.sessionId]}const n9=e=>e.startsWith(`-`)&&e!==`-`;function r9(e,t){let n=i9(t);return n===null?{dir:e??t,args:[]}:e!==null&&lne(e,n.top)?{dir:e,args:[]}:{dir:e===null||i9(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const lne=(e,t)=>e===t||e.startsWith(t+o.sep);function une(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!n9(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=one[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=>!n9(e)):o.arity===`variadic`?dne(n.slice(r),e=>!n9(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 i9(e){let t=e.split(o.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(o.sep),repo:t.slice(0,n-1).join(o.sep)||o.sep}}function dne(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const a9=`candybar-band@cc-candybar`,fne=o.join(`bin`,`cc-candybar-native`),pne=yL(`/reload-plugins`),o9=e=>({kind:`done`,said:e});function s9(e){let t=J$(e.hints.tmux);if(t.kind===`refused`)throw new Y(t.reason);return t.hint}const mne={band:{on:async(e,t,n)=>{let r=nt(t.bundle);if(r===null)throw new Y(`${ax.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=o.join(r,fne);if(!n.fileExists(i))throw new Y(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${a9} from ${r}`,finished:hne(e,r,n)}},off:async()=>o9(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:async(e,t,n)=>{let r=s9(e),i=He(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new Y(`${ax.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:vne(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:async()=>o9(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:async(e,t,n)=>{let r=s9(e),i=await n.barPanes(r);return i.length>0?o9(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):o9(`opened bar pane ${await n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:async(e,t,n)=>{let r=J$(e.hints.tmux);if(r.kind===`refused`)return o9(`no bar pane to close: ${r.reason}`);let i=r.hint,a=await n.barPanes(i);for(let e of a)await n.closePane(i,e);return o9(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:async e=>o9(`the daemon draws ${s9(e).pane}'s bar in its status line`),off:async()=>o9(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function hne(e,t,n){let r={sessionId:e.sessionId,projectDir:e.origin.projectDir,claudeConfigDir:e.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,a9],r);let i=await Y$(n.claudeInput,e.hints.tmux,pne);if(i.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${i.reason} — or type /reload-plugins yourself`);return`installed ${a9} from ${t} and typed /reload-plugins into ${i.pane}`}const gne=new Set([Jo,SF]);function _ne(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function vne(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,Ue(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}) — ${ax.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);if((await r.paneClaude(t)).pid!==i.pid)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}), so it was not restarted under the attach launcher`);let o=Cne(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${ax.statusline.label} off and on again`);let s=yne(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=une(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=_ne(i.env),u=l.get(`PATH`),d=r.launcherNode(u);if(d.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${d.why}`);let f=r.onPath(`claude`,u)===i.executable?`claude`:i.executable,p=[...l].filter(([e])=>gne.has(e)),m=(e,t)=>Ke(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...cne(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${15e3/1e3} s of SIGTERM, so it was not restarted under the attach launcher`);let h=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),g=bne(e,r.presence(e.transcript)),_=g.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:g,v;try{v=await r.paneDir(t,i.parent)}catch(e){throw h(`the directory it was started in could not be read (${e.message})`,m(r9(null,i.cwd),_))}let y=m(r9(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{await r.typeShellLine(t,y)}catch(e){throw h(`the line could not be typed into its pane (${e.message})`,y)}if(!await r.followed(e.sessionId,`statusline`,3e4))throw Error(`Claude Code in ${t.pane} did not come back attached within ${3e4/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${xne[g.kind](e.sessionId)}, and its statusline follows lane B`}function yne(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 bne(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const xne={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},Sne={"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 Cne(e){let t=U$(e);return t.kind===`ready`?K$(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:W$(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:Sne[t.kind]}var wne=class{owed=new Map;setups=new qC;constructor(e){this.deps=e}clicked(e,t,n,r){let i=ox.filter(e=>n[e]!==r[e]),a=this.take(e);for(let e of i)a.has(e)||a.set(e,n[e]);let o=e=>i.includes(e)?`click`:`owed`;if(t!==null){this.settle(t,a,r,o);return}for(let[e,t]of a)t===r[e]&&a.delete(e);if(i.length>0){let t=[...a.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}a.size>0&&this.owed.set(e,a);for(let[e,t]of this.owed){if(this.owed.size<=1024)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t){this.settle(e,this.take(e.sessionId),t,()=>`owed`)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r){for(let[i,a]of t)n[i]===a?this.deps.log(`info`,`lane: ${i} ${a?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(i)} (session=${e.sessionId})`):this.start(e,i,n[i],r(i))}start(e,t,n,r){this.deps.defer(()=>void this.setups.run(e.sessionId,()=>this.sync(e,t,n,r)))}async sync(e,t,n,r){let i=`by=${r} (session=${e.sessionId})`,a=r=>{let a=`lane: ${t} ${n?`on`:`off`}: ${r instanceof Error?r.message:String(r)}`;this.deps.log(`warn`,`${a} ${i}`),Ec(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=await mne[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){a(e);return}this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`underway`&&await o.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${i}`),a)}};function c9(e,t,n){for(let r of(t??``).split(o.delimiter)){if(!o.isAbsolute(r))continue;let t=o.join(r,e);if(n(t))return t}return null}function l9(e,t){try{return f.accessSync(e,t),f.statSync(e).isFile()}catch{return!1}}function Tne(e){try{return f.realpathSync(e)}catch{return o.resolve(e)}}function Ene(e,t,n){let r=c9(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:o.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 u9=2e3;async function d9(e,t,n,r){let i=await _c(e,t,`lane.tmux`,n,r);if(i.kind!==`ok`)throw Error(i.reason);return i.stdout}function f9(e,t){if(t.ok)return t.stdout;let n=t.error??[t.reason,t.stderr.trim(),t.stdout.trim()].filter(e=>e!==``).join(`: `);throw Error(`${e} failed (${n})`)}function Dne(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 One=/(?:^|\s)bar-pane\s+["'\\]*(%\d+)["']*\s*$/;function kne(e,t){return e.split(`
|
|
493
|
+
`).flatMap(e=>{let[n,...r]=e.trim().split(` `);return One.exec(r.join(` `))?.[1]===t?[n]:[]})}const Ane=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function jne(e,t,n){for(let r of PY(NY(e),t)){if(r.command.split(` `).some(e=>Ane.test(e)))return!0;if(r.pid===n)return!1}return!1}const Mne=[`import ctypes, json, struct, sys`,`libc = ctypes.CDLL(None)`,`mib = (ctypes.c_int * 3)(1, 49, int(sys.argv[1]))`,`size = ctypes.c_size_t(0)`,`if libc.sysctl(mib, 3, None, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`buf = ctypes.create_string_buffer(size.value)`,`if libc.sysctl(mib, 3, buf, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`raw = buf.raw[:size.value]`,`argc = struct.unpack_from('i', raw)[0]`,`rest = raw[4:]`,`end = rest.index(b'\\0')`,`exe = rest[:end].decode('utf-8', 'surrogateescape')`,`rest = rest[end:].lstrip(b'\\0')`,`words = [w.decode('utf-8', 'surrogateescape') for w in rest.split(b'\\0')]`,`end = words.index('', argc) if '' in words[argc:] else len(words)`,`print(json.dumps({'executable': exe, 'argv': words[:argc], 'env': words[argc:end]}))`].join(`
|
|
494
|
+
`);async function Nne(e,t){if(process.platform===`linux`)return{executable:await f.promises.readlink(`/proc/${t}/exe`),argv:(await f.promises.readFile(`/proc/${t}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await f.promises.readFile(`/proc/${t}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let n=f9(`reading process ${t}'s arguments`,await e.launch({bin:`python3`,args:[`-c`,Mne,String(t)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(n)}async function p9(e,t,n){return f9(t,await e.launch({bin:`ps`,args:n,timeoutMs:2e3,category:`lane.process`}))}async function m9(e,t){let n=await _c(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 p9(e,`asking pane ${t.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,r])).trim();return{panePid:Number(r),cwd:i,foreground:Number(a)}}async function Pne(e,t){let{panePid:n,cwd:r,foreground:i}=await m9(e,t),a=await p9(e,`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),o=await Nne(e,i),s=NY(a).get(i)?.ppid;if(s===void 0)throw Error(`pane ${t.pane}'s foreground job ${i} is gone`);return{pid:i,executable:await f.promises.realpath(o.executable),argv:o.argv,env:o.env,cwd:r,parent:s,fromShell:i!==n,attached:jne(a,i,n)}}function Fne(e,t,n){let r=e=>xe(e,void 0,{signal:n});return{claudeInput:e1(e),barPanes:async t=>kne(await d9(e,t,[`list-panes`,`-a`,`-F`,`#{pane_id} #{pane_start_command}`]),t.pane),openBarPane:async(t,n,r)=>(await d9(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 d9(e,t,[`kill-pane`,`-t`,n]),claude:async(t,n)=>void f9(`claude ${t.join(` `)}`,await e.launch({bin:`claude`,args:[...t],env:bY(process.env,n),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>f.existsSync(e),presence:mG,paneClaude:t=>Pne(e,t),paneDir:async(t,n)=>{let i=Date.now()+u9;for(;;){let a=await m9(e,t);if(a.foreground===n){if(a.cwd===``)throw Error(`tmux read no directory for pane ${t.pane}`);return a.cwd}if(Date.now()>i)throw Error(`the shell in pane ${t.pane} (pid ${n}) did not take its terminal back within ${u9/1e3} s`);await r(100)}},launcherNode:e=>Ene(e,e=>l9(e,f.constants.X_OK),Tne),onPath:(e,t)=>{let n=c9(e,t,e=>l9(e,f.constants.X_OK));return n===null?null:f.realpathSync(n)},followed:async(e,n,i)=>{let a=Date.now()+i;for(;!t(e).has(n);){if(Date.now()>a)return!1;await r(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`?Dne(i.stdout):null;return a===null?(f9(`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=Date.now()+t;for(;ac(e);){if(Date.now()>n)return!1;await r(100)}return!0},typeShellLine:async(t,n)=>void await d9(e,t,Q$(t.pane,`cc-candybar-lane`,[]),n)}}const Ine=[`request`,`feed`],h9=new WeakMap;let Lne=0;const g9=e=>{let t=h9.get(e);if(t!==void 0)return t;let n=Lne++;return h9.set(e,n),n};var Rne=class{records=new Map;constructor(e=512){this.maxRecords=e}of(e,t){return this.records.get(_9(e,t))?.warnings??[]}ofSession(e,t,n){let r=g9(n.config),i=[];for(let n of Ine){let a=this.records.get(_9(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=_9(e,t);this.records.delete(a),this.records.set(a,{generation:g9(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 _9=(e,t)=>`${t}\0${e}`;var zne=class{queue=new qC;sessions=new qC;gathers=new qC;open=!0;inFlight=null;holder=null;queued=0;gathersInFlight=0;constructor(e){this.deps=e}take(e,{waited:t,gone:n},r){let i=this.deps.monotonic();return this.queued++,this.queue.run(`journals`,async()=>{if(this.queued--,this.refuseClosed(e),n())throw new YC(e);let a=this.deps.monotonic();t(Math.round(a-i)),this.holder={verb:e,since:a};try{return await r({holds:t=>{let n={verb:e,commit:t};return this.inFlight=n,()=>this.commit(n)},landed:t=>t.finally(()=>this.refuseClosed(e))})}finally{this.holder=null}})}click(e,t,{placed:n,waited:r,gone:i,gathered:a},o,s){let c=this.deps.monotonic(),l=async()=>{if(n(Math.round(this.deps.monotonic()-c)),this.refuseClosed(e),i())throw new YC(e);let t=this.deps.monotonic(),l=await o();a(Math.round(this.deps.monotonic()-t));let u=i();return this.take(e,{waited:r,gone:()=>!u&&i()},e=>s(l,e))};return t===null?l():this.sessions.run(t,l)}async gathering(e){this.gathersInFlight++;try{return await this.gathers.run(`gathers`,e)}finally{this.gathersInFlight--}}getStats(){let{holder:e,queued:t}=this;return{holder:e?.verb??null,heldMs:e===null?0:Math.round(this.deps.monotonic()-e.since),queued:t,gathers:this.gathersInFlight}}close(){this.open=!1,this.inFlight!==null&&(this.deps.log(`warn`,`journal: ${this.inFlight.verb} cut off by close, committing what landed`),this.commit(this.inFlight))}refuseClosed(e){if(!this.open)throw new JC(e)}commit(e){return this.inFlight===e?(this.inFlight=null,e.commit(),!0):!1}},Bne=class{sessions=new Map;pending=new Map;disposed=!1;constructor(e){this.deps=e}clicked(e,t){let n=this.record(e,t);n.since=t,this.settle(e)}clickArrived(e){this.pending.set(e,(this.pending.get(e)??0)+1),this.sessions.has(e)&&this.settle(e)}clickSettled(e){let t=this.pending.get(e)-1;t===0?this.pending.delete(e):this.pending.set(e,t),this.sessions.has(e)&&this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown&&!this.pending.has(e)?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;let t=0;for(let e of this.pending.values())t+=e;return{sessions:this.sessions.size,armed:e,pending:t}}dispose(){this.disposed=!0;for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null,closing:!1};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=256)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown&&!t.closing&&!this.disposed&&!this.pending.has(e)?zee(t.since,t.timeoutS):null;if(t.timer?.at===n||(this.disarm(t),n===null))return;let r=setTimeout(()=>this.fire(e),Math.max(0,(n-this.deps.now())*1e3));r.unref(),t.timer={at:n,handle:r}}disarm(e){e.timer!==null&&clearTimeout(e.timer.handle),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now(),r={idleS:n-t.since,timeoutS:t.timeoutS,stillIdle:()=>this.sessions.get(e)===t&&!this.pending.has(e),closed:()=>{t.since=n,t.shown=!1}};t.closing=!0,this.deps.close(e,r).catch(t=>{r.closed(),this.deps.failed(e,t)}).finally(()=>{t.closing=!1,this.sessions.get(e)===t&&this.settle(e)})}};const Vne={date:()=>new Date,monotonic:()=>performance.now(),after:TX};let v9=null;function Hne(e){if(v9!==null&&!v9.aborted)throw Error(`a daemon is already live in this process`);let{bundle:t,memoryLimitBytes:n,registryUrl:r,clock:i,exit:a}=e,o=()=>GM(i.date()),s=new AbortController,c=!1,l=(e,t)=>pr(e,c?`after close: ${t}`:t),u=new p$,d=Kn({stats:u.launchStats,signal:s.signal,observeLifeline:e=>{l(e===null?`info`:`warn`,e===null?`launch lifeline running again`:`launch lifeline ${e}; the next launch starts another`),se.wakeWhere(`data`,()=>!0)}}),p=e.storage(l),m=new WJ(p.session),h=new ZJ(m,l,p.history),g=Kr(Qr(u.startedAt.getTime(),a,{launcher:d,log:l},{limitBytes:n})),_=new k$,v=new Nte,y=FQ(mt()),b=new OT({counters:u,logger:l}),x=new yN(l),S=new nl({watchers:b,logger:l}),C=K5({launcher:d,watchers:b,fileEvents:S,logger:l,ledger:x}),{gitProvider:ee,usageStore:te,tmuxService:w,hostService:ne,managedStorage:T}=C,re=new zte,E=new Uee,D=new Bne({now:o,close:(e,t)=>O0(e,t,ve),failed:(e,t)=>l(t instanceof JC?`info`:`error`,`menu-idle: close failed (session=${e}): ${le(t)}`)}),ie=Sc(),O=new Ac({supersede:(e,t)=>T.supersede(e,t),launch:d.launch,state:m,log:l,now:o}),ae=new wne({edge:Fne(d,e=>se.following(e),s.signal),host:{bundle:t.path,node:t.node,socket:_t(),preload:Ds(t.path)},state:m,log:l,now:o,defer:e=>void pe(e)}),oe=new ine({edge:{run:(e,t,n)=>_c(d,{socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>se.subscribe(e,t),sessionInPane:(e,t)=>se.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${ze(_t())}`,...[...t.node,t.path].map(ze),`url-handle`].join(` `),owner:_t(),log:l}),se=new o6({render:(e,t,n)=>g6(ye,e,t,n),watch:(e,t)=>(0,X.reaction)(()=>m.revision(e),t),lanes:e=>v6(ye,e),pin:e=>{let t=fe.pin(e);return()=>{fe.stopDrawing(e,`feed`),t()}},shown:e=>ce.shown(e.hints.tmux),watching:()=>ce.follow(),refreshes:()=>x.totals(),periods:e6,now:()=>i.monotonic(),instant:o,log:l}),ce=new Hte({listPanes:e=>_c(d,{socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,x7]),listClients:e=>_c(d,{socket:e},`frames.visibility`,[`list-clients`,`-F`,S7]),sockets:()=>new Set(se.watched().flatMap(({req:e})=>ue(e))),onAnswer:(e,t)=>oe.answered(e,t),onChange:e=>se.wakeWhere(`visibility`,t=>ue(t).some(t=>e.has(t))),intervalMs:1e3,log:l});function ue({hints:{tmux:e}}){return e==null?[]:[e.socket]}let de=new Rne,fe=new Lte({launcher:d,sessionState:m,watchers:b,log:l,storage:T,signer:ie,ledger:x,fileEvents:S,declare:(e,t,n,r)=>nZ(C,e,t,n,r),source:Bte({providers:C,sessionState:m,history:e=>h.depth(e),navigation:(e,t)=>re.depth(e,m,sq(t))})},{budgetBytes:()=>Q5(n),observers:{onReload:(e,t,n,r)=>{l(`info`,r7(e,n,r));for(let e of t)se.wake(e,`reload`)},onViewChanged:e=>se.wake(e,`data`)}});S.subscribe(e=>{switch(e.kind){case`period`:b.judge();return;case`caught-up`:fe.reloadEvery({kind:`events-resumed`,since:e.since}),se.wakeWhere(`data`,()=>!0);return;case`moved`:se.wakeWhere(`data`,()=>!0);return}});let me=60*1e3,he=b8({targets:t.targets,intervalMs:me,stat:f.statSync,held:()=>ge.running(),exit:()=>a(0),log:l}),ge=wq({launcher:d,entryUrl:t.entryUrl,digest:t.digest,actsDir:AC(mt(),t.path),intervalMs:me,releaseIntervalMs:216e5,registryUrl:r,fetchImpl:fetch,onApplied:()=>he.checkNow(),log:l}),_e=new zne({log:l,monotonic:()=>i.monotonic()}),ve={sessionState:m,journalTurns:_e,clickLanded:e=>D.clicked(e,o()),log:l,launcher:d,now:o,applyUpdate:()=>ge.act(),doctor:qQ(d,e=>{let t=[e.projectDir,e.cwd,e.target.path];fe.reload(...t,{kind:`doctor`});let n=fe.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:y,probes:_,clients:v,bundle:t.path,serving:()=>g.serving(),claudeInput:e1(d),history:h,navigation:re,configFor:e=>fe.getOrCreate(e.projectDir,e.cwd,e.target.path).state.config,reloadConfig:e=>fe.reload(e.projectDir,e.cwd,e.target.path,{kind:`write`}),sourcesFor:e=>fe.getOrCreate(e.projectDir,e.cwd,e.target.path).state.sources,links:ie,runs:O,lanes:{of:(e,t)=>y6(ye,e,t),clicked:(e,t,n)=>k6(ye,e,t,n)},views:{follow:(e,t)=>fe.follow(e,t.projectDir,t.cwd,t.target.path)},diagnosticCopy:(e,t,n)=>fe.drawnCopy(e,t,n)},ye={launcher:d,log:l,clock:i,bundle:t.path,sourceDigest:t.digest,doctorStores:y,stats:u,handlerProbes:_,renderSightings:v,watcherRegistry:b,refreshLedger:x,fileEvents:S,payloadProviders:C,sessionState:m,effectSessions:E,menuIdle:D,journalTurns:_e,linkSigner:ie,runs:O,laneSetups:ae,tmuxStatusLines:oe,frameFeeds:se,renderWarnings:de,renderCache:fe,updateWatch:ge,limits:g,verbCtx:ve};return v9=s.signal,{stats:u,launcher:d,log:l,memoryLimitBytes:n,clock:i,exit:a,handle:async(e,t,n,r)=>(s.signal.throwIfAborted(),o8(ye,e,t,n,r)),reply:async(e,t,n,r)=>(s.signal.throwIfAborted(),s8(ye,e,t,n,r)),subscribe:(e,t)=>(s.signal.throwIfAborted(),se.subscribe(e,t)),reloadConfig:e=>{s.signal.throwIfAborted(),ve.reloadConfig(e)},arm(){s.signal.throwIfAborted(),S.start(kt()),he.arm(),ge.arm(),g.arm()},close(e){let t=[[`journalTurns close`,()=>_e.close()],[`tmuxStatusLines restore`,()=>oe.restoreAll(e)],[`launches abort`,()=>s.abort(Error(`the daemon closed`))],[`frameFeeds close`,()=>se.close()],[`menuIdle dispose`,()=>D.dispose()],[`updateWatch close`,()=>ge.close()],[`binaryWatch close`,()=>he.close()],[`limits disarm`,()=>g.disarm()],[`renderCache close`,()=>fe.close()],[`gitService close`,()=>ee.close()],[`usageStore close`,()=>te.close()],[`tmuxService close`,()=>w.close()],[`hostService close`,()=>ne.close()],[`runs close`,()=>O.close()],[`managedStorage close`,()=>T.close()],[`fileEvents close`,()=>S.close()],[`watcherRegistry close`,()=>b.closeAll()],[`sessionState close`,()=>m.close()]];for(let[e,n]of t)try{n()}catch(t){l(`warn`,`${e} failed: ${t.message}`)}return c=!0,d.settled()}}}const Une=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function y9(e){if(e===void 0)return;let t=H.parse(e);if(t.isDefault)return;let n=t.fixedValue;if(n!==void 0)return n.hex;let r=t.type===V.STANDARD&&t.number!==void 0?Une[t.number]:void 0;if(r===void 0)throw Error(`frames: no band colour for ${t.name}`);return r}const Wne={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 Gne({text:e,fg:t,bg:n,attrs:r=[],link:i}){let a=y9(t),o=y9(n),s={};for(let e of r){let t=Wne[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 Kne(e){return{ok:!0,band:e.rows.map(e=>BS(e).map(Gne))}}function qne(e){return kS(Kne,e)}const Jne={band:e=>JSON.stringify(qne(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:E7(e)})};function b9(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}function Yne(e,t){t.allowHalfOpen=!1;let n=e.clock.monotonic();e.stats.inFlight++;let r=!1,i=!0,a=()=>{i&&(i=!1,e.stats.inFlight--)},o=(n,i,a)=>{if(r){i!==null&&e.log(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}r=!0,c();let o=i===null?void 0:()=>e.exit(i);try{t.end(Yt(n),e=>{e??a(),o?.()})}catch(t){e.log(`warn`,`response write failed: ${t.message}`),o?.()}},s=!1,c=e.clock.after(200,()=>{s=!0,e.stats.requestsTimedOut++,o({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,p6)}),l=j(r=>{e.handle(r,()=>s,n,()=>t.destroyed).then(e=>e.kind===`reply`?o(e.resp,e.exitAfterFlush,e.delivered):u(e.sessionId,e.lane)).catch(t=>{e.log(`error`,`handler threw: ${le(t)}`),o(m6(t),null,p6)})},t=>{e.log(`warn`,`frame parse failed: ${t.message}`),o({ok:!1,error:t.message,code:`BAD_REQUEST`,daemonV:3},null,p6)}),u=(n,i)=>{if(r||t.destroyed)return;c(),a(),t.off(`data`,l);let o=b9(t),s=e.subscribe(n,{lane:i,frame:(e,t)=>o(Xt(Jne[i](e,t))),refused:e=>t.end(Yt(e)),drawing:()=>!0});r=!0,t.on(`close`,s)};t.on(`data`,l),t.on(`error`,t=>{e.log(`warn`,`socket error: ${t.message}`)}),t.on(`close`,()=>{c(),a()})}function Xne(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 Zne=class{timer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t=500,n=Ie){this.filePath=e,this.debounceMs=t,this.logger=n,this.writingPath=`${e}.writing`}load(){let e;try{e=f.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 Xne(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,this.schedule()}schedule(){this.timer!==null||this.writing||(this.timer=setTimeout(()=>{this.timer=null,this.write()},this.debounceMs),this.timer.unref())}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=performance.now(),r=JSON.stringify(e),i=this.writingPath;this.writing=!0;let a=performance.now()-n;try{await f.promises.mkdir(o.dirname(this.filePath),{recursive:!0});let s=await f.promises.open(i,`w`,384);try{await s.writeFile(r),await s.chmod(384),await s.datasync()}finally{await s.close()}let c=!1;if(t===this.generation)try{await f.promises.rename(i,this.filePath),c=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){c||await f.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${c} took=${Math.round(performance.now()-n)}ms held=${Math.round(a)}ms`);return}this.saved(r,e,n,a),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending,t=performance.now();try{f.mkdirSync(o.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);f.writeFileSync(n,r,{mode:384}),f.chmodSync(n,384),f.rmSync(this.writingPath,{force:!0}),f.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,performance.now()-t),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${Math.round(performance.now()-n)}ms held=${Math.round(r)}ms`)}};function Qne(e){return{session:new Zne(Ct(),500,e),history:vY(wt(),e)}}let x9=null,S9=null,C9=null;function $ne(){let e=i(import.meta.url);return{entryUrl:import.meta.url,digest:it(),path:e,node:[t.execPath,...t.execArgv],targets:[...new Set([e,...t.argv[1]?[t.argv[1]]:[]])]}}function ere(){t.on(`uncaughtException`,e=>{pr(`error`,`uncaughtException: ${e.stack||e.message}`),D9(1)}),t.on(`unhandledRejection`,e=>{pr(`error`,`unhandledRejection: ${String(e)}`),D9(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{pr(`info`,`received ${e}, shutting down`),D9(0)});tre().catch(w9)}function w9(e){pr(`error`,`refusing to boot: ${le(e)}`),D9(1)}async function tre(){let e=Rr(t.env);x9=await tc(t.pid,e=>$s(e,Xn.launch));let n=await dc(pc(x9));if(!n.decision.allow){pr(`warn`,`fork-bomb breaker: ${n.decision.reason}; refusing to boot`),D9(1);return}S9=n.registryPath,f.mkdirSync(gt(),{recursive:!0}),bt(_t());let r=Hne({bundle:$ne(),storage:Qne,memoryLimitBytes:e,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,clock:Vne,exit:D9});C9=r,ic({anchor:rc(t.env),isAlive:ac,onOrphaned:e=>{pr(`info`,`parent watchdog: ${e}; shutting down`),D9(0)}}),T9(r,ae.createServer(e=>Yne(r,e)),_t(),!1)}function T9(e,n,r,i){n.removeAllListeners(`error`),n.removeAllListeners(`listening`),n.once(`error`,a=>{if(a.code!==`EADDRINUSE`){pr(`error`,`server error: ${a.message}`),D9(1);return}if(i){pr(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}nre(e,n,r).catch(w9)}),n.listen(r,()=>rre(e,r))}async function nre(e,n,r){let i=await Gs(Ks(xt(r)),(t,n)=>ec(t,n,{readStartTime:t=>$s(t,e.launcher.launch),pidAlive:ac}));if(i.kind===`attach-and-exit`){pr(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}pr(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{f.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){pr(`error`,`cannot unlink stale socket ${r}: ${e.message}`),D9(1);return}}T9(e,n,r,!0)}function rre(e,n){let r=Ys(n);if(r.kind!==`present`){pr(`warn`,`no ownable socket at bind callback (${r.kind}); exiting`),D9(0);return}are(n);try{f.chmodSync(n,384)}catch(e){pr(`warn`,`chmod socket failed: ${e.message}`)}pr(`info`,`daemon up: pid=${t.pid} v=3 sock=${n} heapCap=${Lr(he.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Lr(e.memoryLimitBytes)}MB`),si(),e.arm(),ire(n,r.identity)}function ire(e,n){Qs({bound:n,myPid:t.pid,readIdentity:()=>Ys(e),readLease:()=>Ks(xt(e)),shutdown:e=>D9(e),log:pr}).arm()}function are(e){let n=qs(xt(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:x9});n!==null&&pr(`warn`,`lease write failed: ${n}`)}const ore=e=>(t,n,r)=>gc(e,{socket:t},`tmux-status`,n,r);let E9=!1;function D9(e){E9||(E9=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500),C9?.close(ore(Yn)),Js(St(),t.pid),S9!==null&&fc(S9,t.pid,lc,e=>f.unlinkSync(e)),t.exit(e))}const sre={connectMs:200,budgetMs:500};async function cre(e,t){return lre(e,await ure(e),t.includes(`--json`))}function lre(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
|
|
495
|
+
`:dre(t.value),stderr:``,code:0}:{stdout:``,stderr:`${e}: ${on(t)}\n`,code:1}}function ure(e){return $t(()=>({kind:`debug`,what:e}),sre,e=>`debug`in e?e.debug:void 0)}function dre(e){switch(e.what){case`vars`:return fre(e.vars);case`segments`:return pre(e.segments);case`config`:return mre(e.config);default:return e}}function fre(e){if(e.length===0)return`no variables (DSL not active)
|
|
496
|
+
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${gre(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${hre(a.value)}${e}${o}`)}return t.join(`
|
|
497
497
|
`)+`
|
|
498
|
-
`}function
|
|
498
|
+
`}function pre(e){if(e.length===0)return`no segments (DSL not active)
|
|
499
499
|
`;let t=[`segments (${e.length})`,``];for(let n of e){t.push(` ${n.name}`),n.description!==null&&t.push(` shows ${n.description}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`);for(let{id:e,lastRender:r}of n.placements)r!==null&&t.push(` last ${e}: ${r}`)}return t.join(`
|
|
500
500
|
`)+`
|
|
501
|
-
`}function
|
|
501
|
+
`}function mre(e){return e===null?`config: DSL not active
|
|
502
502
|
`:JSON.stringify(e,null,2)+`
|
|
503
|
-
`}function
|
|
503
|
+
`}function hre(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function gre(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function _re(){let e=yre();return e===null?null:f.readFileSync(e,`utf-8`)}function vre(){let e;try{e=_re()}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 yre(){let e=o.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let r=o.dirname(o.resolve(n));for(;;){let t=o.join(r,e);if(f.existsSync(t))return t;let n=o.dirname(r);if(n===r)return null;r=n}}const O9=5e3;function bre(e){return{ms:e,signal:AbortSignal.timeout(e)}}function xre(e,t){return t.length===0?[]:[`source${t.length===1?``:`s`} still running after ${e.ms} ms, drawn as pending: ${t.join(`, `)}`]}function k9({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=AX(a,o);return{drawn:Q3(n,r,i,{...Sre(t,a,e.at(-1)??null,s),today:Cre},c,a),opts:c}}function Sre(e,t,n,r){let i=`/home/tester`,a=Math.floor(r),o=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,s={current_dir:`${i}/code/cc-candybar/src`,project_dir:`${i}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:o,version:`1.15.0`,home:i,cwd:`${i}/code/cc-candybar/src`,transcript_path:`${i}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:s,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,tracking:`tracked`,stash:1,status:`dirty`,operation:`rebase`,committedAt:a-780},session:{cost:.39,tokens:241400},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:a+2*3600},weekly:{percentage:21,resetsAt:a+5*86400},cache:{expiresAt:a+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:DL(4e5,1e6),...jX(t),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:eS(()=>!0),themeDefault:t.theme.kind===`decided`?{differs:!0,theme:t.theme.name}:{differs:!1},resumeCommand:kX(s,o,void 0),configPath:n??`${i}/.config/cc-candybar/config.json5`,...sZ(Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]),()=>I)}}const Cre={cost:12.5,tokens:34e5};function wre(e,t){let n=PG(e);return n!==null&&t.push(n),e.kind===`chain`?e.layers:[]}async function Tre(e,n=t.cwd(),r=O9){let i=[],a=xF(n,e)??null,o=kG(kq().read(),n,n,a??void 0);i.push(...CG(o.repos));let s=a===null?wre(o,i):[OG(a)];if(a!==null){let e;try{e=f.statSync(a,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:a,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:a,message:`not a file`}}let c=IG(n,n);c!==null&&i.push(c);try{return{kind:`clean`,layers:s,warnings:i,rendered:await Ore(s,{repo:o.repos.plugins},n,i,r)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&s.some(e=>e.path===t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof Cb&&i.push(...e.warnings),{kind:`fatal`,layers:s,message:e instanceof Cb||e instanceof Error?e.message:String(e),warnings:i})}}async function Ere(e,t,n,r,i,a=O9){let o=e.map(e=>e.path),s=WG(e,gK,{warned:e=>r.push(...e)},{...t,cwd:n});ZG(s.dropped);let{config:c}=s,l=new XT,u=new RN(Xn,l,c.globals.default_empty_value??``,new WJ);try{let e=I3(c,u,{cwd:n,signer:Sc()});r.push(...e.loadWarnings);let t=TK(c,()=>null,()=>!1),d=bre(a);return k9({layers:o,config:c,compiled:e,store:l,registry:u},t,200,i),await u.inFlight(d.signal),{settle:d,layers:o,droppedPlugins:[...s.installed.dropped,...s.layers.flatMap(e=>e.plugins.dropped)],config:c,compiled:e,store:l,registry:u}}catch(e){throw u.dispose(),e}}async function Dre(e,t,n,r){let i=new Map,a=new Set,o=e=>{switch(e.kind){case`rule`:i.set(`${e.slot} rule`,e.message);return;case`when`:i.set(e.where,e.error);return;case`refresh`:i.set(`variable "${e.variable}"`,`cannot refresh: ${e.error}`);return;default:}},{config:s,compiled:c,store:l,registry:u,settle:d}=e,{drawn:f,opts:p}=k9(e,t,n,r);for(let e of xre(d,await u.inFlight(d.signal)))a.add(e);let{frame:m}=$3(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 Ore(e,t,n,r,i){let a=GM(new Date),o=await Ere(e,t,n,r,a,i),{config:s}=o;try{let e=Cq();try{sq(s),uB(s)}finally{e()}let t=Ew(null,s.globals.preset,s.presets),n=async(e,t)=>{let n=TK(s,t=>t===`preset`?e:null,()=>t),r;try{r=await Dre(o,n,200,a)}catch(e){r={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...r}},i=await n(t,!1),c=[i,await n(t,!0)];for(let e of Tw(s.presets))e!==t&&c.push(await n(e,!1),await n(e,!0));let l=e=>{let n=new Map;for(let t of c)for(let r of e(t)){let e=n.get(r)??new Map;e.set(t.preset,(e.get(t.preset)??new Set).add(t.customized)),n.set(r,e)}return[...n].map(([e,n])=>n.get(t)?.has(!1)?e:`${e} (under ${[...n].map(([e,n])=>[...e===t?[]:[`preset "${e}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};r.push(...l(e=>e.advisories));let u=l(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=i.rendered,f=o.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
|
|
504
504
|
`)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
|
|
505
|
-
`));return d}finally{o.registry.dispose()}}function A9(e){return e.map(e=>`warning: ${e}\n`).join(``)}function
|
|
506
|
-
`))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${lG}/`)}function
|
|
507
|
-
`));let c=a.map(e=>{let n=o.basename(e),r=o.join(t,n);return{folder:e,name:n,target:r,placed:
|
|
505
|
+
`));return d}finally{o.registry.dispose()}}function A9(e){return e.map(e=>`warning: ${e}\n`).join(``)}function kre(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${EF(e.layers.map(e=>e.path))}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${LS(e.rendered)}\n`:``),stderr:A9(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:A9(e.warnings)+`✗ ${EF(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 j9=`--render`,M9=`Usage: cc-candybar check [${j9}] [config-file]\n`;function Are(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==j9);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${M9}`}:n.length>1?{kind:`usage`,message:`check: expected at most one path\n${M9}`}:{kind:`run`,target:n[0],render:t.includes(j9)}}async function N9(e){let n=Are(e),r=t.cwd();return n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:kre(await Tre(TF(n.target,t.env,r).path,r),n.render)}const jre=/^[a-z][a-z0-9+.-]*:\/\//i,Mre=/^[^@\s/]+@[^:\s/]+:/,Nre=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function Pre(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function Fre(e,t,n){let r=bF(t,e);if(n(r))return{kind:`path`,dir:r};if(jre.test(e)||Mre.test(e))return{kind:`git`,url:e,shown:Pre(e)};let i=Nre.exec(e);if(i){let e=`https://github.com/${i[1]}.git`;return{kind:`git`,url:e,shown:e}}return{error:`"${e}" is not a directory, a GitHub repo slug (owner/repo) or a git URL`}}function Ire(e,t){let n=o.join(e,lG),r=fG(n);if(`error`in r)throw Error(`${t}: could not list ${lG}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${lG}/<name>/${UU}`);return r.folders.map(e=>o.join(n,e,UU))}function Lre(e,t,n){let r=(n,...r)=>{let i=Yn.launchSync({bin:`git`,args:r,env:n,category:`plugin.git`});if(!i.ok)throw Error(`git ${r.map(n=>n===e?t:n).join(` `)} failed (${i.reason}): ${i.stderr.trim()||i.error||``}`);return i.stdout},i={...process.env,GIT_TERMINAL_PROMPT:`0`};for(let e of r(i,`rev-parse`,`--local-env-vars`).split(`
|
|
506
|
+
`))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${lG}/`)}function Rre(e,t){switch(e.kind){case`path`:return t(e.dir);case`git`:{let n=f.mkdtempSync(o.join(D.tmpdir(),`cc-candybar-plugin-`));try{return Lre(e.url,e.shown,o.join(n,`repo`)),t(o.join(n,`repo`))}finally{f.rmSync(n,{recursive:!0,force:!0})}}}}function zre(e){let t;try{t=f.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 Bre(e,t,n,r){switch(r){case`updated`:f.renameSync(o.join(e,UU),o.join(t,UU));return;case`replaced`:f.renameSync(t,n),f.renameSync(e,t);return;case`installed`:f.renameSync(e,t);return}}function Vre(e,t,n){let r=Ire(e,n);f.mkdirSync(t,{recursive:!0});let i=f.mkdtempSync(o.join(t,`.install-`));try{let a=r.map(e=>{let t=o.join(i,o.basename(o.dirname(e)));f.mkdirSync(t);try{f.copyFileSync(e,o.join(t,UU))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),s=HG(a.map(e=>GU(o.join(e,UU),`plugins`)),gK,{root:e,git:!1});if(s.length>0)throw Error(s.map(e=>`${n}: ${o.join(lG,o.relative(i,e.path))} would not load: ${e.reason.split(i).join(o.join(n,lG))}`).join(`
|
|
507
|
+
`));let c=a.map(e=>{let n=o.basename(e),r=o.join(t,n);return{folder:e,name:n,target:r,placed:zre(r)}}),l=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)Bre(e,n,o.join(i,`.replaced-${t}`),r),l.push(t)}catch(e){throw Error(`${e.message} (placed before it: ${l.join(`, `)||`none`})`)}return c.map(({target:e,placed:t})=>({path:o.join(e,UU),placed:t}))}finally{f.rmSync(i,{recursive:!0,force:!0})}}function Hre(e){let[t,n,...r]=e;if(t!==`install`||n===void 0||r.length>0)return console.error(`Usage: cc-candybar plugin install <path | owner/repo | git URL>`),2;let i=Fre(n,process.cwd(),e=>bT(e)!==null);if(`error`in i)return console.error(`plugin install: ${i.error}`),2;try{let e=i.kind===`path`?i.dir:i.shown,t=Rre(i,t=>Vre(t,cG(),e));for(let{path:n,placed:r}of t)console.log(`${r} plugin ${o.basename(o.dirname(n))} → ${n} (from ${e})`);return 0}catch(e){return console.error(`plugin install: ${e.message}`),1}}function P9(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
|
|
508
508
|
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`busy`:return{output:`
|
|
509
|
-
`,kick:!
|
|
510
|
-
`).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:
|
|
511
|
-
`)||null),warning:n.warning,unused:r.unused,config:r.config}}function
|
|
512
|
-
`;function
|
|
513
|
-
`);return{bytes:t.map((e,t)=>`\x1b[${t+1}H[2K${e}`).join(``)+`\x1B[J`,rows:t.length}}const G9=5e3,K9=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function
|
|
514
|
-
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?
|
|
509
|
+
`,kick:!1,debug:`daemon busy (${e.message}) — not kicking`};case`permanent`:return{output:Gee(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function F9(e,t){if(e!==void 0&&/^\+?\d+$/.test(e)){let t=Number(e);if(t>0&&t<=4294967295)return t}if(t&&t>0)return t}const Ure=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function I9(e,t,n){return{termCols:F9(e.COLUMNS,n.columns),termRows:F9(e.LINES,n.rows),ssh:Ure.some(t=>(e[t]??``)!==``),tmux:Gc(e),configEnv:CF(e,t),claudeConfigDir:Yo(e,t),terminalEnv:Mt(e)}}function L9(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function Wre(e){let t=v$(e,[`bundle`,`clients`]);if(t!==null)return{kind:`failed`,reason:t};if(typeof e.bundle!=`string`)return{kind:`failed`,reason:`the running daemon (${e.version}) reported its bundle as ${JSON.stringify(e.bundle)}`};let n=L9(e);return n.every(e=>typeof e.ago==`number`&&typeof e.sessionId==`string`)?{kind:`ok`,value:{bundle:e.bundle,clients:n.map(e=>({client:Qt(e.client)??null,sessionId:e.sessionId,ago:e.ago}))}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported clients without their age or session: ${JSON.stringify(e.clients)}`}}const Gre=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},Kre=e=>{let t=e??{};if(t.kind===`unmeasured`)return!0;let n=t.charge;return t.kind===`measured`&&typeof t.rss==`number`&&typeof t.heapTotal==`number`&&typeof n?.bytes==`number`&&(n.kind===`charged`&&(n.measure===`phys_footprint`||n.measure===`rss`)||n.kind===`stand-in`&&typeof n.unread==`string`&&Number.isFinite(n.gap))};function R9(e,t){let n=e;if(n?.kind===`failed`&&typeof n.reason==`string`)return{kind:`failed`,reason:n.reason};if(n?.kind!==`ok`)return{kind:`misshapen`,reason:`is not an answer`};let r=t(n.value);return r.kind===`ok`?r:{kind:`misshapen`,reason:r.reason}}function qre(e){let t=v$(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=R9(n?.postMortems,e=>Array.isArray(e)&&e.every(Gre)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&Kre(n.memory)&&typeof n.limit==`number`&&r.kind!==`misshapen`?{kind:`ok`,value:{...n,postMortems:r}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported itself as ${JSON.stringify(e.daemon)}`}}function z9(e,t,n){let r=v$(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=L9(e);return i.every(t)?{kind:`ok`,value:i}:{kind:`failed`,reason:`the running daemon (${e.version}) reported its renders without ${n} — restart it on this build: ${JSON.stringify(e.clients)}`}}const B9=e=>Mte.includes(e.role),Jre=e=>z9(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&kte.includes(e.rateLimits),`the rate-limit windows they carried`),Yre=e=>z9(e,e=>{let t=e.transcript;return typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof t?.path==`string`&&typeof t.answered==`boolean`},`their transcripts`),Xre=e=>z9(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&B9(e)&&OF.includes(e.frame),`what they drew and from which project`),Zre=e=>z9(e,e=>typeof e.sessionId==`string`&&typeof e.ago==`number`&&B9(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function V9(e,t,n){let r=e.doctorStores?.[t],i=R9(r,n);return i.kind===`misshapen`?{kind:`failed`,reason:`the running daemon (${e.version}) reported its ${t} as ${JSON.stringify(r)}, which ${i.reason}`}:i}function Qre(e){let t=v$(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:V9(e,`marks`,SY),clicked:V9(e,`clicked`,TY),postMortemsRead:V9(e,`postMortemsRead`,AQ)}}async function $re(){let e=await _$();if(e.kind!==`ok`){let t={kind:`failed`,reason:on(e).split(`
|
|
510
|
+
`).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:Wre(e.value),rateLimits:Jre(e.value),transcripts:Yre(e.value),frames:Xre(e.value),widths:Zre(e.value),serving:qre(e.value),stores:Qre(e.value)}}const eie=` (fix: click the settings menu (${yi} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,tie=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${yi} by default) › 🧰 tools › 🩺 doctor`;function nie({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:eie}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${tie}\n`)}function rie(e){let t={launcher:Yn,sessionState:new WJ,storage:$5,signer:Sc()},n=_7(e.projectDir,e.cwd,e.target.path,t),r=n.state??v7(e.cwd,n.repos.plugins,t);return r.registry.dispose(),{layers:n.layers,error:n.error??(r.dropped.map(e=>e.message).join(`
|
|
511
|
+
`)||null),warning:n.warning,unused:r.unused,config:r.config}}function iie(e,t,n){return n.kind===`failed`?n:PQ(e,n.value.bundle,AY(t,n.value.clients).map(({client:e})=>e))}function aie(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:AY(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function oie(e,t){return t.kind===`failed`?t:{kind:`ok`,value:AY(e,t.value).map(e=>e.transcript)}}function sie(e,t){return t.kind===`failed`?t:{kind:`ok`,value:MY(e,t.value)}}function cie(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:l$(e.sessionId,AY(e,t.value))}async function lie(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=I9(r,i,a()),u=kY(r.CLAUDE_CODE_SESSION_ID);s={...await u$(e,l,{projectDir:jY(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,target:TF(o,r,i)},()=>null,c.serving,aie(u,c.rateLimits,Xo(l.claudeConfigDir)),oie(u,c.transcripts),u,sie(u,c.frames),cie(u,c.widths,l.termCols??null),c.stores),urlHandler:await P$(t),install:iie(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=GI(s);return{stdout:c.map(nie).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function uie(){if(t.stderr.isTTY)return t.stderr;let e;try{e=y(`/dev/tty`,`r+`)}catch{return{}}let n=new Se(e),{columns:r}=n;return n.destroy(),{columns:r}}const H9=`Usage: cc-candybar doctor [config-file]
|
|
512
|
+
`;function die(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`));return t.length>0?{kind:`usage`,message:`doctor: unknown option ${t.join(` `)}\n${H9}`}:n.length>1?{kind:`usage`,message:`doctor: expected at most one config file\n${H9}`}:{kind:`run`,configFile:n[0]}}async function fie(e){let n=die(e);return n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:await lie(qQ(Yn,rie),R$(Yn),$re,t.env,t.cwd(),uie,n.configFile)}function pie(e){return!e.ok&&e.code!==`RENDER_FAILED`}function mie(e,t,n,r,i){let a=null,o=e=>{a===null&&(a=e,s.destroy(),i(e))},s=ae.createConnection({path:e}),c={v:3,kind:`subscribe`,sessionId:t,lane:n};return s.once(`connect`,()=>s.write(Yt(c))),s.on(`data`,j(e=>{let t=e;pie(t)?o({kind:`refused`,resp:t}):r(t)},e=>o({kind:`failed`,error:e}))),s.on(`error`,e=>o({kind:`failed`,error:e})),s.on(`close`,()=>o({kind:`closed-there`})),{close:()=>o({kind:`closed-here`})}}function U9(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(2e3,e*2)}}function hie(e){switch(e.kind){case`failed`:return{kind:`reconnect`,reason:`stream failed (${e.error.message})`,kick:!0};case`closed-there`:return{kind:`reconnect`,reason:`daemon closed the stream`,kick:!1};case`refused`:return e.resp.code===`SWITCHED_OFF`?{kind:`off`,resp:e.resp}:e.resp.code===`TIMEOUT`?{kind:`reconnect`,reason:`the daemon was too busy to open the stream (${e.resp.error})`,kick:!1}:e.resp.code===`BAD_REQUEST`?{kind:`reconnect`,reason:`the daemon does not take subscribe (${e.resp.error}); it restarts on the new build`,kick:!1}:e.resp.code===`VERSION_MISMATCH`&&e.resp.daemonV!==void 0&&e.resp.daemonV<3?{kind:`reconnect`,reason:`the daemon is older than this client (${e.resp.error})`,kick:!0}:{kind:`exit`,reason:`the daemon refused the stream: ${e.resp.code}: ${e.resp.error}`}}}function W9(e,t,n,r){let i=null,a=null,o=!1,s=250,c=(e,t)=>{a=setTimeout(()=>{a=null,((t?r.beforeReconnect?.():void 0)??Promise.resolve()).then(()=>{o||l()})},e)},l=()=>{i=mie(e,t,n,e=>{s=U9(s,e.ok?`frame-ok`:`frame-failed`),r.frame(e)},e=>{if(e.kind===`closed-here`||o)return;let t=hie(e);switch(t.kind){case`exit`:r.exit(t.reason);return;case`off`:r.off(t.resp),c(5e3,!1);return;case`reconnect`:{r.fault(t.reason,s),t.kick&&$r();let e=s;s=U9(s,`fault`),c(e,!0);return}}})};return l(),{close:()=>{o=!0,a!==null&&clearTimeout(a),i?.close()}}}function gie(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function _ie(e,n){let{values:r,tokens:i}=ue({args:e.slice(3),options:{config:{type:`string`},lane:{type:`string`}},strict:!0,tokens:!0}),a=[e[1],...i.flatMap(e=>e.kind===`option`&&e.name===`config`?[e.rawName,e.value]:[])],o=t.cwd(),s=e=>{t.stderr.write(`cc-candybar frames: ${e}\n`)},c=mx(r.lane);c===null&&(s(`--lane needs one of ${ox.join(`, `)}`),t.exit(2)),t.stdout.on(`error`,()=>t.exit(0));let l=b9(t.stdout),u=null,d=null,f=null,p={kind:`none`},m=(e,t)=>{gie(p,e)&&t(),p=e},h=async e=>{let r=await pn(e,a,o,{...I9(t.env,o,t.stderr),client:Pt(`frames`,n)});r.kind!==`ok`&&(s(on(r)),P9(r).kick&&$r())},g=e=>{f?.close(),f=W9(_t(),e,c,{frame:e=>m({kind:`frame`},()=>l(`${JSON.stringify(e)}\n`)),off:e=>m({kind:`off`},()=>l(`${JSON.stringify(e)}\n`)),fault:(e,t)=>m({kind:`fault`,reason:e},()=>s(`${e}; reconnecting in ${t}ms`)),exit:e=>{s(e),t.exit(1)},beforeReconnect:()=>d===null?Promise.resolve():h(d)})};for await(let e of Ce({input:t.stdin})){if(e.trim()===``)continue;let t;try{t=JSON.parse(e)}catch(e){s(`stdin line is not JSON: ${e.message}`);continue}if(typeof t.session_id!=`string`||t.session_id===``){s(`stdin line carries no session_id`);continue}d=t,await h(t),t.session_id!==u&&(u=t.session_id,g(u))}t.exit(0)}function vie(e){let t=e.replace(/\n+$/,``).split(`
|
|
513
|
+
`);return{bytes:t.map((e,t)=>`\x1b[${t+1}H[2K${e}`).join(``)+`\x1B[J`,rows:t.length}}const G9=5e3,K9=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function yie(e,t,n,r){let i=e.split(`
|
|
514
|
+
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?w7(e,C7(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function q9(e,t){let[n,r]=await Promise.all([_c(Xn,e,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${t}},#{==:#{pane_id},${e.pane}}}`,`-F`,x7]),_c(Xn,e,`bar-pane.tmux`,[`list-clients`,`-F`,S7])]);return n.kind===`ok`?r.kind===`ok`?{kind:`ok`,placement:yie(n.stdout,r.stdout,t,e.pane)}:r:n}function J9(){let e=Date.now();return t=>{if(t.kind===`ok`)e=Date.now();else if(Date.now()-e>G9)throw Error(`tmux has not answered for ${G9/1e3} s: ${t.reason}`)}}function bie(e){let{positionals:t}=(()=>{try{return ue({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${K9}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(K9);return{pane:n}}async function xie(e){try{return await Sie(e),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function Sie(e){let{pane:n}=bie(e),r=Gc(t.env);if(r===null)throw Error(`cc-candybar bar-pane runs in a tmux pane`);if(!t.stdout.isTTY)throw Error(`cc-candybar bar-pane draws on its pane's terminal`);let i=await q9(r,n);if(i.kind!==`ok`)throw Error(i.reason);let a=i.placement;if(a.kind===`gone`)throw Error(`no pane ${n} on this tmux server (${r.socket})`);t.stdout.write(`\x1B[?25l\x1B[?7l`),t.on(`exit`,()=>t.stdout.write(`\x1B[?25h\x1B[?7h`));for(let[e,n]of[[`SIGINT`,130],[`SIGTERM`,143],[`SIGHUP`,129]])t.once(e,()=>t.exit(n));let o=e=>{t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),t.exit(1)},s=null,c=`waiting for pane ${n}'s bar`,l=()=>s?.said.latest??c,u=``,d=J9(),f=async()=>{if(a.kind!==`shown`)return;let e=vie(l());e.rows!==t.stdout.rows&&!a.zoomed&&d(await _c(Xn,r,`bar-pane.tmux`,[`resize-pane`,`-t`,r.pane,`-y`,String(e.rows)])),e.bytes!==u&&t.stdout.write(e.bytes),u=e.bytes},p=null,m=!1,h=()=>{m=!0,p??=(async()=>{try{for(;m;)m=!1,await f()}finally{p=null}})(),p.catch(o)};t.stdout.on(`resize`,()=>{u=``,h()});let g=e=>{if(s?.sessionId===e)return;if(s?.follower.close(),e===null){s=null;return}let t={latest:null},n=e=>{t.latest=e,h()};s={sessionId:e,said:t,follower:W9(_t(),e,`pane`,{frame:e=>n(P9(fn(e)).output),off:e=>n(e.error),fault:n,exit:e=>o(Error(e))})}},_=J9();for(;a.kind!==`gone`;){if(a.kind===`hidden`)g(null);else{let e=await mn(r.socket,n);e.kind===`ok`?(g(e.value),c=e.value===null?`waiting for pane ${n}'s statusline to render on ${_t()}`:`waiting for pane ${n}'s bar`):(e.kind===`transient`&&($r(),u=``),c=on(e))}h(),await xe(500);let e=await q9(r,n);_(e),e.kind===`ok`&&(a=e.placement)}g(null),t.stderr.write(`cc-candybar bar-pane: pane ${n} closed\n`)}const Cie=(e,t)=>new Promise((n,r)=>{let i=t=>{t?t.code===`EPIPE`?n():r(t):(e.off(`error`,i),n())};e.once(`error`,i),e.write(t,i)});async function Y9(e){let n=Pe(()=>`delivered stdout=${Buffer.byteLength(e.stdout)} stderr=${Buffer.byteLength(e.stderr)} code=${e.code}`),r=[];for(let[i,a]of[[t.stdout,e.stdout],[t.stderr,e.stderr+n]])await Cie(i,a).catch(e=>r.push(e));if(r.length>0)throw r[0];t.exit(e.code)}const X9=i(import.meta.url),Z9=e=>e.some(e=>t.argv.includes(e));function Q9(){console.log(Ete);let e=Ds(X9),t=f.existsSync(e)?``:" (nothing is there yet: run `cc-candybar install` first — in a checkout, `pnpm build`)\n";console.log(`Starting Claude Code on ${ax.statusline.label} yourself (a Bun-compiled Claude Code):\n ${Ke(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const $9={install:async e=>{await Us(e,X9,Yn),t.exit(0)},"install-url-handler":async()=>{Rs(X9,Yn),t.exit(0)},"url-handle":async e=>{await Bs(e[0])},daemon:async()=>{ere()},"daemon-stats":async e=>{await Y9(await h$(e))},frames:async()=>{await _ie(t.argv,X9)},check:async e=>{await Y9(await N9(e))},lint:async e=>{await Y9(await N9(e))},plugin:async e=>{t.exit(Hre(e))},schema:async()=>{await Y9(vre())},doctor:async e=>{await Y9(await fie(e))},"bar-pane":async e=>{t.exit(await xie(e))},...Object.fromEntries($6.map(e=>[e,async t=>{await Y9(await cre(e,t))}]))};async function wie(){let e=t.argv[2],n=e!==void 0&&!e.startsWith(`-`)?e:null;try{if(n!==null&&!Object.hasOwn($9,n)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(n)} — see --help`),t.exit(2)),Z9(hF.help)&&(Q9(),t.exit(0)),Z9(hF.version)&&(console.log(`cc-candybar ${tt}`),t.exit(0)),n!==null){await $9[n](t.argv.slice(3));return}t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
515
515
|
|
|
516
516
|
cc-candybar is designed to be used as a Claude Code statusLine command.
|
|
517
517
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -527,4 +527,4 @@ Add to ~/.claude/settings.json:
|
|
|
527
527
|
Run with --help for more options.
|
|
528
528
|
|
|
529
529
|
To test output manually:
|
|
530
|
-
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),k(`Working directory: ${t.cwd()}`),k(`Process args:`,t.argv);let e=await a(t.stdin);k(`Received hook data:`,JSON.stringify(e,null,2)),e||(console.error(`Error: No input data received from stdin`),Q9(),t.exit(1));let r=P9(await pn(e,t.argv.slice(1),t.cwd(),{...I9(t.env,t.cwd(),t.stderr),client:Pt(`node`,X9)}));r.debug!==null&&k(r.debug),r.kick&&$r(),await Y9({stdout:r.output,stderr:``,code:0})}catch(e){let t=e instanceof Error?e.message:String(e);await Y9({stdout:``,stderr:`cc-candybar ${n??`statusline`}: ${t}\n`,code:1})}}
|
|
530
|
+
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),k(`Working directory: ${t.cwd()}`),k(`Process args:`,t.argv);let e=await a(t.stdin);k(`Received hook data:`,JSON.stringify(e,null,2)),e||(console.error(`Error: No input data received from stdin`),Q9(),t.exit(1));let r=P9(await pn(e,t.argv.slice(1),t.cwd(),{...I9(t.env,t.cwd(),t.stderr),client:Pt(`node`,X9)}));r.debug!==null&&k(r.debug),r.kick&&$r(),await Y9({stdout:r.output,stderr:``,code:0})}catch(e){let t=e instanceof Error?e.message:String(e);await Y9({stdout:``,stderr:`cc-candybar ${n??`statusline`}: ${t}\n`,code:1})}}wie();export{};
|