@promptctl/cc-candybar 1.224.0 → 1.225.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/index.mjs +20 -17
- package/package.json +5 -5
- package/schema/cc-candybar.schema.json +85 -0
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import{createRequire}from"node:module";import process$1 from"node:process";import{URL as URL$1,URLSearchParams,fileURLToPath}from"node:url";import{json}from"node:stream/consumers";import os from"node:os";import fs,{closeSync,constants,existsSync,fstatSync,linkSync,mkdtempSync,openSync,readFileSync,readSync,rmSync,statSync,writeFileSync}from"node:fs";import{StringDecoder}from"node:string_decoder";import{inspect,parseArgs,types}from"node:util";import{clearImmediate,setImmediate}from"node:timers";import{spawn,spawnSync}from"node:child_process";import path,{basename,dirname,isAbsolute,join,sep}from"node:path";import crypto,{createHash,createHmac,randomBytes,randomUUID,timingSafeEqual}from"node:crypto";import net from"node:net";import v8 from"node:v8";import{open,readFile,readdir,stat}from"node:fs/promises";import{get}from"node:https";import{WriteStream}from"node:tty";import{createInterface}from"node:readline";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__commonJSMin=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),__copyProps=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=__getOwnPropNames(t),a=0,o=i.length,s;a<o;a++)s=i[a],!__hasOwnProp.call(e,s)&&s!==n&&__defProp(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=__getOwnPropDesc(t,s))||r.enumerable});return e},__toESM=(e,t,n)=>(n=e==null?{}:__create(__getProtoOf(e)),__copyProps(t||!e||!e.__esModule?__defProp(n,`default`,{value:e,enumerable:!0}):n,e));let debugEnabled=!1;const debugOn=()=>debugEnabled;function setDebug(e){debugEnabled=e}function debugText(e){return debugOn()?`[DEBUG] ${e()}\n`:``}function debug(e,...t){debugOn()&&console.error(`[DEBUG] ${e}`,...t)}function changeLogger(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const quietLogger=(e,t)=>debug(t);function spanMs(e,t){return Math.round(t-e)}function elapsedMs(e,t){return spanMs(t,e.monotonic())}const systemTimekeeper={now:()=>Date.now(),monotonic:()=>performance.now(),after:(e,t,n)=>{let r=setTimeout(t,e);return n?.unref&&r.unref(),()=>clearTimeout(r)},every:(e,t,n)=>{let r=setInterval(t,e);return n?.unref&&r.unref(),()=>clearInterval(r)},defer:e=>{let t=setImmediate(e);return()=>clearImmediate(t)}};function sleep(e,t,n){return new Promise((r,i)=>{let a=()=>Object.assign(Error(`The operation was aborted`),{name:`AbortError`,code:`ABORT_ERR`,cause:n?.reason});if(n?.aborted){i(a());return}let o=()=>{s(),i(a())},s=e.after(t,()=>{n?.removeEventListener(`abort`,o),r()});n?.addEventListener(`abort`,o,{once:!0})})}function timeoutSignal(e,t){let n=new AbortController;return e.after(t,()=>n.abort(new DOMException(`The operation was aborted due to timeout`,`TimeoutError`)),{unref:!0}),n.signal}function eventHoldAt(e,t,n,r){return n<e.at+t?`held`:r===`request`&&!e.answered?`owed`:`over`}function joinedEvent(e,t,n){return{text:e===null||e.answered?t:`${e.text}\n${t}`,at:n,answered:!1}}function answeredBy(e,t){return!e.answered&&e.at===t.at&&e.text===t.text}const instantOf=e=>e.getTime()/1e3,dateOf=e=>new Date(e*1e3),instantAt=e=>instantOf(new Date(e.now()));function spawnErrorText(e,t){return types.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!existsSync(t)?`working directory does not exist: ${t}`:e.message:String(e)}const RATE_LIMITS={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function checkRateLimit(e,t,n){let r=RATE_LIMITS[t];if(r===void 0)return{allowed:!0};let i=e.get(t);if(i===void 0)return{allowed:!0};let a=n-i;return a>=r?{allowed:!0}:{allowed:!1,minIntervalMs:r,sinceLastMs:a}}function childEnv(e,t){let n={...e.inherited};for(let[e,r]of Object.entries(t.envOverlay??{}))n[e]=r??void 0;return n}const refusedAsAborted=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function rateLimitedResult(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${Math.round(n)}ms ago`}}function track(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function admit(e,t,n){let r=refusalOf$2(e,t,n);return r===null?(e.lastStartAt.set(t,e.scope.clock.monotonic()),null):(e.scope.stats?.onRefused(t),r)}function refusalOf$2(e,t,n){if(e.scope.signal.aborted)return refusedAsAborted(e.scope.signal);if(n?.aborted)return refusedAsAborted(n);let r=checkRateLimit(e.lastStartAt,t,e.scope.clock.monotonic());return r.allowed?null:rateLimitedResult(t,r.minIntervalMs,r.sinceLastMs)}const TIMEOUT_KILL_GRACE_MS=250,GROUP_END_POLL_MIN_MS=25,GROUP_END_POLL_MAX_MS=1e3,LIFELINE_PROGRAM=`\$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 ${TIMEOUT_KILL_GRACE_MS/1e3}; kill -KILL" groups " 2>/dev/null") }`;function setFault(e,t){t!==e.fault&&(e.fault=t,e.scope.observeWarnings({kind:`lifeline`,fault:t}))}function lose(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),setFault(e,n))}const lifelineMessage=e=>`programs launched now would outlive their launcher if it died: its launch lifeline ${e}, and the next launch starts another`,pipeEventWords=e=>e===`cut`?`output cut at the ${MAX_CAPTURED_BYTES}-byte bound, so the program holding it now fails its writes`:`output failed to read`,PIPE_EVENT_LEAD=`a launched program's pipe outlived its launch: `;function pipeEvent(e,t,n){let r=e.pipeEvent,i=new Map(r===null||r.answered?[]:r.counts),a=`${t}\0${n}`;i.set(a,(i.get(a)??0)+1),e.pipeEvent={text:`${PIPE_EVENT_LEAD}${[...i].map(([e,t])=>{let[n,r]=e.split(`\0`);return`${t}× ${r} ${pipeEventWords(n)}`}).join(`; `)}`,at:e.scope.now(),answered:!1,counts:i},e.scope.observeWarnings({kind:`launch-pipes`,text:`${PIPE_EVENT_LEAD}${n} ${pipeEventWords(t)}`})}function answeredPipeEvent(e,t){let n=e.pipeEvent;n===null||!answeredBy(n,t)||(e.pipeEvent={...n,answered:!0})}function standing(e){let t=e.pipeEvent;return[...e.fault===null?[]:[{kind:`lifeline`,message:lifelineMessage(e.fault)}],...t===null?[]:[{kind:`launch-pipes`,event:{text:t.text,at:t.at,answered:t.answered}}]]}function spawnLifeline(e){let{stats:t,clock:n}=e.scope;t?.onStart(`lifeline`);let r=n.monotonic(),i;try{i=e.spawner.spawn(`awk`,[LIFELINE_PROGRAM],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(i){return t?.onEnd(`lifeline`,elapsedMs(n,r)),setFault(e,`did not start: ${spawnErrorText(i,void 0)}`),null}t?.onEnd(`lifeline`,elapsedMs(n,r));let a=i.stdin;if(a==null)return i.once(`error`,t=>setFault(e,`did not start: ${t.message}`)),null;i.once(`spawn`,()=>{e.lifeline?.process===i&&setFault(e,null)}),i.once(`error`,t=>lose(e,i,`failed: ${t.message}`)),i.once(`exit`,(t,n)=>lose(e,i,`exited ${n??t}`)),a.on(`error`,t=>lose(e,i,`pipe failed: ${t.message}`)),track(e,new Promise(e=>i.once(`close`,e))),i.unref(),a.unref();for(let t of e.liveGroups)a.write(`+ ${t}\n`);return{process:i,pipe:a}}function guard(e,t){e.liveGroups.add(t),e.lifeline??=spawnLifeline(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function unguard(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function endLifeline(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}const MAX_CAPTURED_BYTES=16*1024*1024,OUTPUT_LIMIT_ERROR=`output exceeded ${MAX_CAPTURED_BYTES} bytes`,timedOutError=e=>`timed out after ${e/1e3} s`;function capture(e,t,n,r){let{stats:i}=e.scope,a=new StringDecoder(`utf8`),o=``,s=0,c=0,l=r,u=`closed`;return n?.on(`error`,n=>{i?.onPipeError(t),l===null?pipeEvent(e,`read-error`,t):l.failed(n)}),n?.on(`data`,r=>{if(l===null){if(c+=r.length,i?.onDrainRead(t,r.length),c<=16777216)return;u=`cut`,n.destroy(),pipeEvent(e,`cut`,t);return}let d=Math.max(0,MAX_CAPTURED_BYTES-s);o+=a.write(r.subarray(0,d)),s+=r.length,s>16777216&&l.full()}),{take:()=>{if(l===null)return``;l=null;let e=o+a.end();return o=``,e},drain:()=>{n===null||n.destroyed||n.readableEnded||hold(e,t,n,()=>u)}}}function hold(e,t,n,r){let{stats:i}=e.scope;if(e.scope.signal.aborted){n.destroy();return}n.once(`close`,()=>{e.drains.delete(n),i?.onDrainClose(t,r())}),n.unref(),e.drains.add(n),i?.onDrainOpen(t)}const inputEnd=()=>`closed`;function feed(e,t){e.on(`error`,()=>{}),e.end(t)}const captured=e=>({read:(e,t,n,r)=>capture(e,t,n,r),opened:t=>{t!==null&&feed(t,e)}});function relay(e,t,n,r,i){let a=new StringDecoder(`utf8`);return n?.on(`error`,n=>{e.scope.stats?.onPipeError(t),r.failed(n)}),n?.on(`data`,e=>{let t=a.write(e);t!==``&&i(t)}),{take:()=>{let e=a.end();return e!==``&&i(e),``},drain:()=>{n===null||n.destroyed||n.readableEnded||hold(e,t,n,()=>`closed`)}}}function launchChannel(e,t){let n=null,r=null;return{get pid(){return r},write:e=>{n!==null&&!n.writableEnded&&!n.destroyed&&n.write(e)},end:()=>{n?.end()},ended:track(e,launchPiped(e,t,{read:(e,n,r,i,a)=>relay(e,n,r,i,t.heard[a]),opened:(e,t)=>{n=e,r=t,e?.on(`error`,()=>{})}}))}}function launchWaited(e,t){return launchPiped(e,t,captured(t.stdinInput))}async function launchPiped(e,t,n){let{stats:r,clock:i}=e.scope,a=admit(e,t.category,t.signal);if(a!==null)return a;let o=i.monotonic();return r?.onStart(t.category),new Promise(a=>{let{spawner:s}=e,c;try{c=s.spawn(t.bin,t.args??[],{cwd:t.cwd,env:childEnv(e.scope,t),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(e){r?.onEnd(t.category,elapsedMs(i,o)),a({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:spawnErrorText(e,t.cwd)});return}let l=c.pid;l!==void 0&&guard(e,l);let u=new Promise(e=>c.once(`exit`,e)),d=c.stdin;c.stdin=null;let f=null,p={full:()=>O(`output-limit`),failed:e=>{f??=e.message,O(`pipe-error`)}},m=n.read(e,t.category,c.stdout,p,`stdout`),h=n.read(e,t.category,c.stderr,p,`stderr`),g=()=>({stdout:m.take(),stderr:h.take()}),_=!1,v=null,y=null,b=null,x=null,S=()=>O(`aborted`),C=()=>{t.signal?.removeEventListener(`abort`,S),e.inFlight.delete(S)},w=n=>{_||(_=!0,v?.(),y?.(),b?.(),C(),l!==void 0&&unguard(e,l),r?.onEnd(t.category,elapsedMs(i,o)),c.off(`close`,A),c.off(`error`,k),m.drain(),h.drain(),d!==null&&!d.destroyed&&!d.writableFinished&&hold(e,t.category,d,inputEnd),n())},T=e=>w(()=>a(e)),E=(n,r)=>{try{s.signalGroup(n,r)}catch(n){e.unreaped.set(c,t.category),u.then(()=>e.unreaped.delete(c)),T({ok:!1,reason:`signal-refused`,...g(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},D=()=>A(c.exitCode,c.signalCode);if(l!==void 0){let e=t=>{if(!_){if(s.groupGone(l)){i.defer(D);return}b=i.after(t,()=>e(Math.min(t*2,GROUP_END_POLL_MAX_MS)))}};u.then(()=>i.defer(()=>e(GROUP_END_POLL_MIN_MS)))}let O=e=>{if(x!==null)return;if((c.exitCode!==null||c.signalCode!==null)&&l!==void 0&&s.groupGone(l)){x=e===`timeout`?null:e,i.defer(D);return}x=e,v?.(),C();let t=c.pid;t!==void 0&&(y=i.after(TIMEOUT_KILL_GRACE_MS,()=>{E(t,`SIGKILL`),u.then(()=>i.defer(D))}),E(t,`SIGTERM`))},k=e=>{T({ok:!1,reason:`spawn-error`,...g(),exitCode:null,signal:null,error:spawnErrorText(e,t.cwd)})};c.on(`error`,k);let A=(e,n)=>{if(x!==null){T({ok:!1,reason:x,...g(),exitCode:e,signal:n,...x===`timeout`?{error:timedOutError(t.timeoutMs??0)}:x===`output-limit`?{error:OUTPUT_LIMIT_ERROR}:x===`pipe-error`?{error:`a pipe failed to read: ${f}`}:{}});return}if(e===0){T({ok:!0,...g(),exitCode:e});return}T({ok:!1,reason:n?`signal`:`non-zero`,...g(),exitCode:e,signal:n})};c.on(`close`,A),t.timeoutMs&&t.timeoutMs>0&&(v=i.after(t.timeoutMs,()=>O(`timeout`))),t.signal?.addEventListener(`abort`,S,{once:!0}),e.inFlight.add(S),n.opened(d,l??null)})}function launchBlocking(e,t){let{stats:n,clock:r}=e.scope,i=admit(e,t.category);if(i!==null)return i;let a=r.monotonic();n?.onStart(t.category);try{let i=e.spawner.spawnSync(t.bin,t.args??[],{cwd:t.cwd,env:childEnv(e.scope,t),input:t.stdinInput,timeout:t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:void 0,stdio:[`pipe`,`pipe`,`pipe`],encoding:`utf8`});n?.onEnd(t.category,elapsedMs(r,a));let o=typeof i.stdout==`string`?i.stdout:``,s=typeof i.stderr==`string`?i.stderr:``,c=i.error?.code;if(i.error&&c!==`EPIPE`&&c!==`ECONNRESET`){let e=c===`ETIMEDOUT`?`timeout`:`spawn-error`;return{ok:!1,reason:e,stdout:o,stderr:s,exitCode:null,signal:i.signal??null,error:e===`timeout`?timedOutError(t.timeoutMs??0):spawnErrorText(i.error,t.cwd)}}return i.status===0?{ok:!0,stdout:o,stderr:s,exitCode:i.status}:{ok:!1,reason:i.signal?`signal`:`non-zero`,stdout:o,stderr:s,exitCode:i.status,signal:i.signal??null}}catch(e){return n?.onEnd(t.category,elapsedMs(r,a)),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:spawnErrorText(e,t.cwd)}}}function launchOrphan(e,t){let{stats:n,clock:r}=e.scope,i=admit(e,t.category);if(i!==null)return i;let a=r.monotonic();n?.onStart(t.category);let o=launchDetachedSyncInner(e,t);return n?.onEnd(t.category,elapsedMs(r,a)),o}function launchDetachedSyncInner(e,t){let n;try{n=e.spawner.spawn(t.bin,t.args??[],{cwd:t.cwd,env:childEnv(e.scope,t),detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:spawnErrorText(e,t.cwd)}}return n.once(`error`,()=>{}),n.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${t.bin}): no pid (binary not found or unexecutable)`}:(n.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}const formatJobEnd=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`,JOB_SCRIPT=`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.$$"`;function launchJob(e,t,n){let{stats:r,clock:i}=e.scope,a=admit(e,t.category);if(a!==null)return{ok:!1,reason:a.reason,error:a.error};let o=i.monotonic();r?.onStart(t.category);let s;try{s=e.spawner.spawn(`/bin/sh`,[`-c`,JOB_SCRIPT,`sh`,n.stdout,n.stderr,n.status,t.bin,...t.args??[]],{cwd:t.cwd,env:childEnv(e.scope,t),detached:!0,stdio:[`pipe`,`ignore`,`ignore`]})}catch(e){return r?.onEnd(t.category,elapsedMs(i,o)),{ok:!1,reason:`spawn-error`,error:spawnErrorText(e,t.cwd)}}r?.onEnd(t.category,elapsedMs(i,o)),s.once(`error`,()=>{});let c=s.pid,l=s.stdin;return l.on(`error`,()=>{}),c===void 0?(l.destroy(),{ok:!1,reason:`spawn-error`,error:`spawn(/bin/sh): no pid (shell not found or unexecutable)`}):(s.unref(),l.unref(),{ok:!0,pid:c,release:()=>l.end(`go
|
|
3
3
|
`),withdraw:()=>l.end()})}function readJobEnd(e){let t;try{t=readFileSync(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 endJob(e,t,n,r,i){let a=`${r}.${process.pid}`;try{writeFileSync(a,`${formatJobEnd(i)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let o=!0;try{linkSync(a,r)}catch(e){if(e.code!==`EEXIST`)throw e;o=!1}finally{rmSync(a,{force:!0})}let s=e.signalJob(n,`SIGTERM`);return s&&t.after(TIMEOUT_KILL_GRACE_MS,()=>e.signalJob(n,`SIGKILL`),{unref:!0}),{stands:o,signalled:s}}function createLauncher(e,t,n){return launcherWithState(e,t,n).launcher}function createOneShotLauncher(e,t,n){let{launcher:r,state:i}=launcherWithState(e,t,n);return{...r,launchSync:e=>launchBlocking(i,e)}}function launcherWithState(e,t,n){let r={clock:t,launch:e=>track(i,launchWaited(i,e)),launchChannel:e=>launchChannel(i,e),launchDetachedSync:e=>launchOrphan(i,e),launchJobSync:(e,t)=>launchJob(i,e,t),jobGroupAlive:e=>n.signalJob(e,0),endJob:(e,r,i)=>endJob(n,t,e,r,i),standing:()=>standing(i),answeredPipeEvent:e=>answeredPipeEvent(i,e),settled:async()=>(await Promise.all(i.ending),{unreaped:[...i.unreaped.values()]}),__lifelineForTest:()=>{let e=i.lifeline;return{pid:e?.process.pid,cut:()=>{e?.pipe.end(),e&&lose(i,e.process,`cut by a test`)}}}},i={spawner:n,scope:{stats:null,observeWarnings:e=>{let t=e.kind===`launch-pipes`?e.text:e.fault===null?null:lifelineMessage(e.fault);t!==null&&process.emitWarning(t)},signal:new AbortController().signal,now:()=>instantOf(new Date(t.now())),...e,clock:t},lastStartAt:new Map,inFlight:new Set,liveGroups:new Set,lifeline:null,fault:null,pipeEvent:null,ending:new Set,unreaped:new Map,drains:new Set};return i.scope.signal.addEventListener(`abort`,()=>{i.inFlight.forEach(e=>e()),i.drains.forEach(e=>e.destroy()),endLifeline(i)},{once:!0}),{launcher:r,state:i}}function leaderRefuses(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}const systemSpawner={spawn:(e,t,n)=>spawn(e,t,n),spawnSync:(e,t,n)=>spawnSync(e,t,n),signalGroup:(e,t)=>{try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!leaderRefuses(e)))throw t}},groupGone:e=>{try{return process.kill(-e,0),!1}catch(e){return e.code===`ESRCH`}},signalJob:(e,t)=>{try{return process.kill(-e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}},systemLauncher=(e,t)=>createLauncher(e,t,systemSpawner),systemOneShotLauncher=(e,t)=>createOneShotLauncher(e,t,systemSpawner);function processWorld(){let e={env:process.env,home:os.homedir(),tmp:os.tmpdir()},t=systemTimekeeper;return{host:e,launcher:systemOneShotLauncher({inherited:process.env},t),clock:t}}function whyFailed(e){switch(e.reason){case`non-zero`:return`exited with code ${e.exitCode}`;case`signal`:return`killed by ${e.signal??`a signal`}`;case`timeout`:case`output-limit`:case`rate-limited`:case`pipe-error`:case`spawn-error`:return e.error??e.reason;default:return e.error===void 0?e.reason:`${e.reason}: ${e.error}`}}const SAID_LINE_CHARS=200,clipped=e=>{let t=[];for(let n of e){if(t.length===SAID_LINE_CHARS)return`${t.join(``)}…`;t.push(n)}return e};function saidBy(e,t){if(e.reason===`output-limit`||e.reason===`pipe-error`)return``;let n=t.trim(),r=n.search(/[\r\n]/);if(r===-1)return clipped(n);let i=Math.max(n.lastIndexOf(`
|
|
4
|
-
`),n.lastIndexOf(`\r`))+1;return`${clipped(n.slice(0,r).trim())} … ${clipped(n.slice(i).trim())}`}function failureText(e,t=``){let n=saidBy(e,e.stderr);return`${whyFailed(e)}${t}${n===``?``:`: ${n}`}`}function launcherWarningsAt(e,t,n){return e.flatMap(e=>{if(e.kind===`lifeline`)return[e];let r=eventHoldAt(e.event,60,t,n);return r===`over`?[]:[{...e,message:e.event.text,hold:r}]})}const SHELL_SAFE=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function singleQuoted(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function shellWord(e){return SHELL_SAFE.test(e)?e:singleQuoted(e)}function claudeCommandLine(e){return`${e.dir===void 0?``:`cd ${shellWord(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${shellWord(t)} `).join(``)}${[e.program,...e.args].map(shellWord).join(` `)}`}const ATTACH_DIR=`cc-extra`;function attachLauncherOf(e){return path.join(path.dirname(e),ATTACH_DIR,`src`,`bun-attach.js`)}function moduleGraphReaderOf(e){return path.join(path.dirname(e),`bun-graph.js`)}const ATTACH_PRELOAD=`attach-preload.cjs`;function attachPreloadOf(e){return path.join(path.dirname(e),ATTACH_PRELOAD)}const PRELOAD_VARIABLE=`BUN_OPTIONS`;function attachCommandLine(e,t){return claudeCommandLine({...t,env:[...t.env,[PRELOAD_VARIABLE,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const isSourceEntry=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function entryBytes(e,t){return t.isSymbolicLink()?Buffer.from(fs.readlinkSync(e)):fs.readFileSync(e)}function sourceEntries(e,t,n=isSourceEntry){return fs.readdirSync(t).filter(n).sort().flatMap(n=>{let r=path.join(t,n),i=fs.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?sourceEntries(e,r):[[path.relative(e,r).split(path.sep).join(`/`),entryBytes(r,i)]]})}function digestOf$1(e){let t=crypto.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function sourceDigest(e){return digestOf$1(sourceEntries(e,e))}const CRATE_SOURCE=[`Cargo.toml`,`Cargo.lock`,`src`];function crateDigest(e){return digestOf$1(sourceEntries(e,e,e=>CRATE_SOURCE.includes(e)))}const PACKAGE_VERSION=`1.
|
|
4
|
+
`),n.lastIndexOf(`\r`))+1;return`${clipped(n.slice(0,r).trim())} … ${clipped(n.slice(i).trim())}`}function failureText(e,t=``){let n=saidBy(e,e.stderr);return`${whyFailed(e)}${t}${n===``?``:`: ${n}`}`}function launcherWarningsAt(e,t,n){return e.flatMap(e=>{if(e.kind===`lifeline`)return[e];let r=eventHoldAt(e.event,60,t,n);return r===`over`?[]:[{...e,message:e.event.text,hold:r}]})}const SHELL_SAFE=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function singleQuoted(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function shellWord(e){return SHELL_SAFE.test(e)?e:singleQuoted(e)}function claudeCommandLine(e){return`${e.dir===void 0?``:`cd ${shellWord(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${shellWord(t)} `).join(``)}${[e.program,...e.args].map(shellWord).join(` `)}`}const ATTACH_DIR=`cc-extra`;function attachLauncherOf(e){return path.join(path.dirname(e),ATTACH_DIR,`src`,`bun-attach.js`)}function moduleGraphReaderOf(e){return path.join(path.dirname(e),`bun-graph.js`)}const ATTACH_PRELOAD=`attach-preload.cjs`;function attachPreloadOf(e){return path.join(path.dirname(e),ATTACH_PRELOAD)}const PRELOAD_VARIABLE=`BUN_OPTIONS`;function attachCommandLine(e,t){return claudeCommandLine({...t,env:[...t.env,[PRELOAD_VARIABLE,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const isSourceEntry=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function entryBytes(e,t){return t.isSymbolicLink()?Buffer.from(fs.readlinkSync(e)):fs.readFileSync(e)}function sourceEntries(e,t,n=isSourceEntry){return fs.readdirSync(t).filter(n).sort().flatMap(n=>{let r=path.join(t,n),i=fs.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?sourceEntries(e,r):[[path.relative(e,r).split(path.sep).join(`/`),entryBytes(r,i)]]})}function digestOf$1(e){let t=crypto.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function sourceDigest(e){return digestOf$1(sourceEntries(e,e))}const CRATE_SOURCE=[`Cargo.toml`,`Cargo.lock`,`src`];function crateDigest(e){return digestOf$1(sourceEntries(e,e,e=>CRATE_SOURCE.includes(e)))}const PACKAGE_VERSION=`1.225.0`;function sourceCheckoutOf(e){let t=path.dirname(path.dirname(e));return fs.existsSync(path.join(t,`src`))?t:null}function bundleStamp(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:PACKAGE_VERSION,digest:e}}function bakedDigest(){return`203b515ee34809f7686ade79401c534738cd6b6a420eb1a19e3318aa575e99c8`}function checkoutVersion(e){let t=JSON.parse(fs.readFileSync(path.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${path.join(e,`package.json`)} has no version string`);return n}function assessBuild(e,t){try{let n=sourceCheckoutOf(fileURLToPath(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),i=sourceDigest(path.join(n,`src`));return i===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:checkoutVersion(n),digest:i},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function xdgEnv(e,t){let n=e[t];return n&&n.length>0?n:void 0}function stateDir(e){let t=xdgEnv(e.env,`XDG_STATE_HOME`)??path.join(e.home,`.local`,`state`);return path.join(t,`cc-candybar`)}function cacheDir(e){let t=xdgEnv(e.env,`XDG_CACHE_HOME`)??path.join(e.home,`.cache`);return path.join(t,`cc-candybar`)}function daemonDir(e){return stateDir(e)}function socketPath(e){return e.env.CC_CANDYBAR_SOCKET||defaultSocketPath()}function defaultSocketPath(){let e=os.userInfo().uid;return path.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function ensureOwnedPrivateDir(e){fs.mkdirSync(e,{recursive:!0,mode:448});let t=fs.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=os.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 ensureSocketParentSafe(e){ensureOwnedPrivateDir(path.dirname(e));for(let t of[e,leasePathFor(e)])try{if(fs.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function leasePathFor(e){return`${e}.lease`}function leasePath(e){return leasePathFor(socketPath(e))}function sessionStatePath(e){return path.join(stateDir(e),`session-state.json`)}function settingsHistoryPath(e){return path.join(stateDir(e),`settings-history.json`)}function daemonRegistryDir(e){let t=e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(t)return t;let n=os.userInfo().uid;return path.join(`/tmp`,`cc-candybar-${n}`,`daemons`)}function spawnLockPath(e){return path.join(stateDir(e),`spawn.lock`)}const SPAWN_COOLDOWN_FILE=`spawn.cooldown`;function spawnCooldownPath(e){return path.join(stateDir(e),SPAWN_COOLDOWN_FILE)}const SPAWN_BACKOFF_FILE=`spawn.backoff`;function spawnBackoffPath(e){return path.join(stateDir(e),SPAWN_BACKOFF_FILE)}function watchProbeDir(e){return path.join(stateDir(e),`watch-probe`)}function logPath(e){return path.join(stateDir(e),`daemon.log`)}function daemonPaths(e){return{socket:socketPath(e),lease:leasePath(e),state:stateDir(e),registry:daemonRegistryDir(e),log:logPath(e),sessionState:sessionStatePath(e),settingsHistory:settingsHistoryPath(e),watchProbe:watchProbeDir(e),spawnBackoff:spawnBackoffPath(e)}}function locations(e){let{env:t}=e,n=`/usr/local/share:/usr/share`,r=process.platform===`darwin`?`${path.join(xdgEnv(t,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${n}`:n;return{home:e.home,configHome:xdgEnv(t,`XDG_CONFIG_HOME`)??path.join(e.home,`.config`),dataHome:xdgEnv(t,`XDG_DATA_HOME`)??path.join(e.home,`.local`,`share`),dataDirs:(xdgEnv(t,`XDG_DATA_DIRS`)??r).split(`:`).filter(e=>e!==``)}}function writeAtomic(e,t,n){let r=resolvedTarget(e);fs.mkdirSync(path.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??fs.statSync(r,{throwIfNoEntry:!1})?.mode;try{fs.writeFileSync(i,t,a===void 0?{}:{mode:a}),fs.renameSync(i,r)}catch(e){throw fs.rmSync(i,{force:!0}),e}}function readConfigText(e){try{return fs.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function resolvedTarget(e){return linkChain(e).at(-1)}function linkChain(e){let{hops:t,stopped:n}=walkLinks(e);if(n!==null)throw n;return t}function walkLinks(e){let t=[e];try{for(let e=0;e<MAX_LINK_HOPS;e++){let e=linkTarget(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${MAX_LINK_HOPS} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function linkTarget(e){try{return fs.lstatSync(e).isSymbolicLink()?path.resolve(fs.realpathSync(path.dirname(e)),fs.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const MAX_LINK_HOPS=40,TERMINAL_ENV_VARS=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function detectTerminalEnv(e){return Object.fromEntries(TERMINAL_ENV_VARS.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const CLIENT_KINDS=[`native`,`node`,`frames`];function nodeClientHint(e,t){return{kind:e,bundle:t,source:null}}const RENDER_ENCODINGS=[`ansi`,`frame`],CLIENT_HINT_FIELDS=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function parseClientHints(e){let t=sanitizeTermExtent(e.termCols),n=sanitizeTermExtent(e.termRows),r=sanitizeSsh(e.ssh),i=sanitizeTmux(e.tmux),a=sanitizeAbsolutePath(e.configEnv),o=sanitizeAbsolutePath(e.claudeConfigDir),s=sanitizeTerminalEnv(e.terminalEnv),c=sanitizeClient(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 refusedHints(e,t){return CLIENT_HINT_FIELDS.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function refusedHintsError(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 REFUSAL_LINES={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function refusedArgsError(e){let t=Object.keys(REFUSAL_LINES).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[REFUSAL_LINES[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
5
5
|
`)}function sanitizeTerminalEnv(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=TERMINAL_ENV_VARS.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 sanitizeAbsolutePath(e){return typeof e==`string`&&path.isAbsolute(e)?e:void 0}function sanitizeTmux(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 MAX_TERM_EXTENT=1e4;function sanitizeTermExtent(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>MAX_TERM_EXTENT?MAX_TERM_EXTENT:t}function sanitizeSsh(e){return typeof e==`boolean`?e:void 0}const URL_FRAME_KIND=`url`,URL_FRAME_VERSION=2,EARLIER_URL_FRAME_VERSIONS=[1],URL_FRAME_VERSIONS=new Set([...EARLIER_URL_FRAME_VERSIONS,2]),awaitsVerdict=e=>typeof e==`number`&&e>=2;function classifyInbound(e){return typeof e==`object`&&e&&e.kind===`url`?{kind:`url`,frame:e}:{kind:`request`,req:e}}var ProtocolError=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}},ClientTimeoutError=class extends Error{constructor(e){super(e===`connect`?`CONNECT_TIMEOUT`:`TIMEOUT`),this.phase=e,this.name=`ClientTimeoutError`}};const FRAME_HEADER_BYTES=4,MAX_FRAME_BYTES=16*1024*1024;function encodeFrame(e){return encodeJsonFrame(JSON.stringify(e))}function encodeJsonFrame(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function makeFrameReader(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 ProtocolError(`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 ProtocolError(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function sendOne(e,t,n,r){return new Promise((i,a)=>{let o=!1,s=t=>{if(!o){o=!0,c(),e.off(`data`,l),e.off(`error`,u),e.off(`close`,d);try{t()}catch{}}},c=r.after(n-r.now(),()=>{s(()=>{e.destroy(),a(new ClientTimeoutError(`deadline`))})}),l=makeFrameReader(e=>s(()=>i(e)),e=>s(()=>a(e))),u=e=>s(()=>a(e)),d=()=>s(()=>a(Error(`socket closed before response`)));e.on(`data`,l),e.on(`error`,u),e.on(`close`,d),e.write(encodeFrame(t))})}function sanitizeClient(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=sanitizeAbsolutePath(n);return CLIENT_KINDS.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function requestOutcome(e,t,n,r){let i;try{i=await connectWithTimeout(socketPath(e.host),n.connectMs,e.clock)}catch(e){return interpretException(e)}return exchangeOutcome(i,e.clock,t,n,r)}async function exchangeOutcome(e,t,n,r,i){try{let a=t.now()+r.budgetMs,o=n(a),s=await sendOne(e,{v:3,...o},a,t);return interpretResponse(o.kind,s,i)}catch(e){return interpretException(e)}finally{e.destroy()}}function asString(e,t){return typeof e==`string`?e:t}function asProtocolVersion(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function interpretResponse(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=asString(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:asProtocolVersion(r.daemonV)};case`TIMEOUT`:return{kind:`busy`,phase:`deadline`,message:i};case`BAD_REQUEST`:return{kind:`permanent`,cause:`bad_request`,message:i};case`RENDER_FAILED`:return{kind:`permanent`,cause:`render_failed`,message:i};case`SWITCHED_OFF`:return{kind:`permanent`,cause:`switched_off`,message:i};default:return{kind:`permanent`,cause:`malformed_response`,message:`unknown error code: ${String(r.code)}`}}}function interpretException(e){if(e instanceof ProtocolError||e instanceof SyntaxError)return{kind:`permanent`,cause:`malformed_response`,message:e instanceof Error?e.message:String(e)};let t=e instanceof Error?e.message:String(e);return e instanceof ClientTimeoutError?{kind:`busy`,phase:e.phase,message:t}:t.includes(`ECONNREFUSED`)||t.includes(`ENOENT`)||t.includes(`ENOTSOCK`)?{kind:`transient`,cause:`unreachable`,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function connectWithTimeout(e,t,n){return new Promise((r,i)=>{let a=net.createConnection({path:e}),o=n.after(t,()=>{a.destroy(),i(new ClientTimeoutError(`connect`))});a.once(`connect`,()=>{o(),r(a)}),a.once(`error`,e=>{o(),i(e)})})}function describeFailure(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}`}}const REQUEST_TIMEOUT_MS=200,DRAW_RESERVE_MS=60;function parseClientDeadline(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 waitBudgetMs(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 RENDER_BUDGETS={connectMs:50,budgetMs:150},CLICK_BUDGETS={connectMs:50,budgetMs:350};function projectOutput(e){let t=e.output;return typeof t==`string`?t:void 0}function renderOutcomeOf(e){return interpretResponse(`render`,e,projectOutput)}function tryRenderViaDaemon(e,t,n,r,i,a=RENDER_BUDGETS){return requestOutcome(e,e=>({kind:`render`,hookData:t,args:n,cwd:r,deadline:e,...i}),a,projectOutput)}function trySessionInPane(e,t,n){return requestOutcome(e,()=>({kind:`pane-session`,socket:t,pane:n}),CLICK_BUDGETS,e=>`paneSession`in e?e.paneSession:void 0)}function tryClickViaDaemon(e,t){return requestOutcome(e,()=>({kind:`click`,url:t}),CLICK_BUDGETS,projectOutput)}const PROBE_TIMEOUT_MS=5e3;async function memoryReport(e){let t=[];for(let n of e){let e=await n.read();if(e.kind===`text`)return`# memory report from: ${n.name}\n${e.text}`;t.push(`# ${n.name}: unavailable — ${e.reason}`)}return[`# memory report: no probe answered`,...t.length>0?t:[`# no probe is known for this platform`]].join(`
|
|
6
6
|
`)}async function memoryReports(e){return(await Promise.all(e.map(memoryReport))).join(`
|
|
7
7
|
|
|
8
8
|
`)}const FOOTPRINT=`/usr/bin/footprint`,VMMAP=`/usr/bin/vmmap`;function platformProbes(e,t,n){return t===`darwin`?[commandProbe(e,FOOTPRINT,[`-p`,String(n)]),commandProbe(e,VMMAP,[`--summary`,String(n)])]:t===`linux`?[fileProbe(`/proc/${n}/smaps_rollup`),fileProbe(`/proc/${n}/status`)]:[]}function chargeProbe(e,t){return t===`darwin`?footprintCharge(t=>e.launch({bin:FOOTPRINT,args:t,timeoutMs:PROBE_TIMEOUT_MS,category:`limits.charge`})):async(e,t)=>({kind:`charged`,measure:`rss`,bytes:t})}function footprintCharge(e){return async(t,n)=>{let r=await e([...t.flatMap(e=>[`-p`,String(e)]),`--noCategories`,`-f`,`bytes`]);if(!r.ok)return{kind:`stand-in`,bytes:n,unread:`footprint ${failureText(r)}`};let i=physFootprintsOf(r.stdout);return i.length===t.length?{kind:`charged`,measure:`phys_footprint`,bytes:i.reduce((e,t)=>e+t,0)}:{kind:`stand-in`,bytes:n,unread:`footprint printed ${i.length} phys_footprint lines for ${t.length} processes`}}}function physFootprintsOf(e){return[...e.matchAll(/^\s*phys_footprint:\s+(\d+) B\s*$/gm)].map(e=>Number(e[1]))}function commandProbe(e,t,n){return{name:`${t} ${n.join(` `)}`,read:async()=>{let r=await e.launch({bin:t,args:[...n],timeoutMs:PROBE_TIMEOUT_MS,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:failureText(r)}}}}function fileProbe(e){return{name:e,read:async()=>{try{let t=fs.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}const BYTES_PER_MB=1024*1024,mb=e=>Math.round(e/BYTES_PER_MB);function laterIdentity(e,t){return e>t}const NEAR_LIMIT=.75;function approachingLimit(e,t){return e>t*NEAR_LIMIT}function chargeWords(e){return e.kind===`charged`?`${e.measure} ${mb(e.bytes)} MB`:`rss ${mb(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${mb(e.gap)} MB gap`} (standing in: ${e.unread})`}function measureOf(e){return e.kind===`charged`?e.measure:`rss-stand-in`}const BREACH_ARTIFACTS={memoryReport:{prefix:`memory-`,suffix:`.txt`},rendererHeapSnapshot:{prefix:`renderer-heap-`,suffix:`.heapsnapshot`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}},RSS_LIMIT_ENV=`CC_CANDYBAR_RSS_LIMIT_MB`,DEFAULT_RSS_LIMIT_MB=1024,HEAP_CAP_OVER_RSS=2;function memoryLimitMb(e){let t=e[RSS_LIMIT_ENV];if(t===void 0)return DEFAULT_RSS_LIMIT_MB;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${RSS_LIMIT_ENV} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function heapCapMb(e){return memoryLimitMb(e)*2}function memoryLimitBytes(e){return memoryLimitMb(e)*BYTES_PER_MB}const DEFAULT_CHECK_INTERVAL=60*1e3,HEAP_SNAPSHOT_KEEP=3;function readCharge(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}}function artifactFile(e,t,n){let{prefix:r,suffix:i}=BREACH_ARTIFACTS[t];return path.join(e,`${r}${n}${i}`)}function breachArtifactOf(e){for(let t of Object.keys(BREACH_ARTIFACTS)){let{prefix:n,suffix:r}=BREACH_ARTIFACTS[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function makeLimits(e){let t=e.limitBytes??1024*1048576,n=e.snapshotsKeep??HEAP_SNAPSHOT_KEEP,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 a=e.memoryBytes(),s=e.renderer(),c=[{role:`host`,pid:e.pid,sizes:a},...s===null?[]:[{role:`renderer`,pid:s.pid,sizes:s.usage}]],l=c.map(e=>e.pid),u=sum(c,e=>e.rss),d=sum(c,e=>e.heapTotal),f=readCharge(await e.memoryCharge(l,u),i),p={kind:`measured`,charge:f,rss:u,heapTotal:d,processes:c};if(i=p,e.log(`info`,`memory ${readingFields(p,t)}`),o||f.bytes<=t)return!1;r=!0,e.log(`warn`,`${chargeWords(f)} > limit ${mb(t)} MB (rss ${mb(u)} MB, v8 heap ${mb(d)} MB); recording memory then shutting down`);let m=`${new Date(e.clock.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;await attempt$2(e.log,`memory report`,async()=>{let t=artifactFile(e.snapshotDir,`memoryReport`,m),n=await e.captureMemoryReport(l);o||(e.writeMemoryReport(t,n),e.log(`info`,`memory report written: ${t}`))});let h=()=>(o&&e.log(`info`,`daemon closed during the breach: no snapshot, no exit`),o);return h()||(s!==null&&await attempt$2(e.log,`renderer heap snapshot`,async()=>{let t=artifactFile(e.snapshotDir,`rendererHeapSnapshot`,m);await s.heapSnapshot(t),e.log(`info`,`renderer heap snapshot written: ${t}`)}),h())?!1:(await attempt$2(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=artifactFile(e.snapshotDir,`heapSnapshot`,m);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),await attempt$2(e.log,`artifact rotation`,async()=>{for(let{artifacts:t}of postMortemsOf(e.listArtifacts()).slice(n))for(let n of Object.values(t))await attempt$2(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0)}function u(){return i.kind===`measured`&&approachingLimit(i.charge.bytes,t)?`${chargeWords(i.charge)} approaching limit ${mb(t)} MB (v8 heap ${mb(i.heapTotal)} MB)`:null}function d(){let n;try{n={kind:`ok`,value:postMortemsOf(e.listArtifacts())}}catch(e){n={kind:`failed`,reason:e.message}}return{pid:e.pid,memory:i,limit:t,postMortems:n}}function f(t=DEFAULT_CHECK_INTERVAL){let n=async()=>{try{if(await c())return}catch(t){e.log(`warn`,`memory check failed: ${t.message}`)}o||(s=e.clock.after(t,()=>void n(),{unref:!0}))};n()}function p(){o=!0,s?.()}return{check:c,describeNextRestart:u,serving:d,arm:f,disarm:p}}function sum(e,t){return e.reduce((e,n)=>e+(n.sizes===null?0:t(n.sizes)),0)}function readingFields({charge:e,rss:t,heapTotal:n,processes:r},i){let a=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${mb(e.gap)}MB`:``,o=r.map(e=>` ${e.role}=${e.pid}:${e.sizes===null?`unread`:`rss${mb(e.sizes.rss)}MB/heap${mb(e.sizes.heapTotal)}MB`}`).join(``);return`measure=${measureOf(e)} charge=${mb(e.bytes)}MB rss=${mb(t)}MB heap=${mb(n)}MB limit=${mb(i)}MB${a}${o}`}async function attempt$2(e,t,n){try{await n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function postMortemsOf(e){let t=new Map;for(let n of e){let e=path.basename(n),r=breachArtifactOf(e);if(r===null)continue;let{prefix:i,suffix:a}=BREACH_ARTIFACTS[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(BREACH_ARTIFACTS);return[...t].sort(([e],[t])=>laterIdentity(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function realLimitsDeps(e,t,n,r={}){let i=n.snapshotDir;return{clock:n.clock,pid:process.pid,snapshotDir:i,log:n.log,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},memoryCharge:chargeProbe(n.launcher,process.platform),captureMemoryReport:e=>memoryReports(e.map(e=>platformProbes(n.launcher,process.platform,e))),writeMemoryReport:(e,t)=>fs.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>v8.writeHeapSnapshot(e),writeLogNow:n.writeLogNow,listArtifacts:()=>{let e;try{e=fs.readdirSync(i)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>breachArtifactOf(e)!==null).map(e=>path.join(i,e))},removeFile:e=>fs.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}const KICK_CONTENDED_OVERRIDE_MS=2e3;function obtainDaemonKick(e,t={}){let{host:n,clock:r}=e;if(ensureStateDir(n)!==null)return;let i=t.spawn??(()=>spawnDaemonDetachedReal(e)),a=tryAcquireSpawnLock(n,r);if(a.kind===`contended`){let e=spawnLockAgeMs(n,r);e!==null&&e>KICK_CONTENDED_OVERRIDE_MS&&(process$1.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),cooldownGatedSpawn(n,r,i));return}if(a.kind===`error`){process$1.stderr.write(`cc-candybar: spawn-lock unavailable (${a.reason}) — spawning unlocked\n`),cooldownGatedSpawn(n,r,i);return}try{cooldownGatedSpawn(n,r,i)}finally{releaseSpawnLock()}}function cooldownGatedSpawn(e,t,n){claimSpawnCooldown(e,t)&&safeSpawn(n)}function spawnLockAgeMs(e,t){try{let n=fs.statSync(spawnLockPath(e));return t.now()-n.mtimeMs}catch{return null}}function safeSpawn(e){try{e()||process$1.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
|
|
9
|
-
`)}catch(e){process$1.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}const SPAWN_COOLDOWN_MS=3e3;function cooldownDecision(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}const SPAWN_BACKOFF_CAP_MS=6e4,SPAWN_BACKOFF_MAX_STREAK=5;function effectiveCooldownMs(e){return Math.min(SPAWN_COOLDOWN_MS*2**Math.min(Math.max(e,0),5),SPAWN_BACKOFF_CAP_MS)}function readBackoffStreak(e){try{let t=fs.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function writeBackoffStreak(e,t){try{fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(t),{mode:384})}catch(e){process$1.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function resetSpawnBackoff(e){try{fs.unlinkSync(e)}catch(e){e.code!==`ENOENT`&&process$1.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function claimSpawnCooldown(e,t){let n=spawnCooldownPath(e),r=spawnBackoffPath(e),i=readBackoffStreak(r),a=cooldownDecision(cooldownAgeMs(n,t),effectiveCooldownMs(i));return a.kind===`deny`?!1:(a.kind===`allow-future-garbage`&&process$1.stderr.write(`cc-candybar: spawn.cooldown mtime is ${a.futureMs}ms in the future — ignoring and spawning\n`),recordSpawnAttempt(n,t),writeBackoffStreak(r,Math.min(i+1,5)),!0)}function cooldownAgeMs(e,t){try{return t.now()-fs.statSync(e).mtimeMs}catch{return null}}function recordSpawnAttempt(e,t){try{fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,`${process$1.pid} ${t.now()}\n`,{mode:384})}catch(e){process$1.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}const STALE_LOCK_MS=1e4;let heldLock=null;function tryAcquireSpawnLock(e,t){let n=spawnLockPath(e);for(let e=0;e<2;e++){try{let e=fs.openSync(n,`wx`,384);try{fs.writeSync(e,JSON.stringify({pid:process$1.pid,ts:t.now()}))}catch{}return heldLock={fd:e,path:n},{kind:`held`}}catch(e){let t=e.code;if(t!==`EEXIST`)return{kind:`error`,reason:`openSync(${n}): ${t??e.message}`}}if(!isLockStale(n,t))return{kind:`contended`};try{fs.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function isLockStale(e,t){try{let n=fs.statSync(e);return t.now()-n.mtimeMs>STALE_LOCK_MS}catch{return!0}}function releaseSpawnLock(){if(!heldLock)return;let{fd:e,path:t}=heldLock;heldLock=null;try{fs.closeSync(e)}catch{}try{fs.unlinkSync(t)}catch{}}function ensureStateDir(e){try{return fs.mkdirSync(daemonDir(e),{recursive:!0}),null}catch(t){return`mkdir ${daemonDir(e)}: ${t.message}`}}function daemonArgs(e,t){return[`--max-old-space-size=${heapCapMb(t)}`,e,`daemon`]}function spawnDaemonDetachedReal({host:e,launcher:t}){let n=process$1.execPath,r=process$1.argv[1];return r?t.launchDetachedSync({bin:n,args:daemonArgs(r,e.env),category:`daemon-spawn`}).ok:!1}const DISCLOSURE_CLOSED=`closed`,DISCLOSURE_OPEN=`open`,DISCLOSURE_CLOSE_ROLE=`warning`,DOOR_CLOSE_ROLE=`error`,DOOR_GLYPH=`🍫`;function cycleDisplayIssue(e,t,n){if(t===0)return`${e} needs a display (the clickable text)`;if(t!==1&&t!==n)return`${e} cycles ${n} members; bind one display per member (${n}) or one static display, got ${t}`}function pickCycleDisplay(e,t,n,r){let i=cycleDisplayIssue(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function escapeTemplateLiteral(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function disclosureNode(e,t,n,r,i){return{kind:`segment`,name:e,opens:{ref:t,body:n,placement:r},...i!==void 0&&{when:i}}}function disclosureGate(e,...t){return`{{ and ${[e,...t].map(disclosureTerm).join(` `)} }}`}function disclosureTerm(e){return`(eq .${e.variable} "${escapeTemplateLiteral(e.member)}")`}function disclosureTrigger(e,t,n){return`{{ ${disclosureTriggerCall(e,templateLiteral(t),templateLiteral(n))} }}`}function disclosureTriggerCall(e,t,n){return`action "${e}" ${t} ${n}`}function templateLiteral(e){return`"${escapeTemplateLiteral(e)}"`}function disclosureStateVar(e,t){return{kind:`state`,key:e,default:t}}function disclosureCycleAction(e,t){return{set:e,cycle:[DISCLOSURE_CLOSED,t]}}function disclosureOfAction(e){if(!(`set`in e&&`cycle`in e))return;let[t,n,...r]=e.cycle;return t===`closed`&&n!==void 0&&r.length===0?{key:e.set,member:n}:void 0}const GROUP_NS=`groups.`,MENU_NS=`menus.`,MENU_PAGE_NS=`menupages.`,EDIT_NS=`edit.`,SETTINGS_NS=`candybar.`,RESERVED_NAMESPACES=[GROUP_NS,MENU_NS,MENU_PAGE_NS,EDIT_NS,SETTINGS_NS];function isReservedName(e){return RESERVED_NAMESPACES.some(t=>e.startsWith(t))}const SETTINGS_ANCHOR=`${SETTINGS_NS}menu`,SETTINGS_OPEN=DISCLOSURE_OPEN,SETTINGS_REF={variable:SETTINGS_ANCHOR,key:SETTINGS_ANCHOR,member:SETTINGS_OPEN},DIAGNOSTICS_VIEWING=`${SETTINGS_NS}diagnostics`;var BadVerbArgs=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}},DaemonClosing=class extends Error{constructor(e){super(`the daemon closed: ${e} refused`),this.name=`DaemonClosing`}},ClickAbandoned=class extends Error{constructor(e){super(`the client left: ${e} not run`),this.name=`ClickAbandoned`}},RendererDown=class extends Error{constructor(e){super(e),this.name=`RendererDown`}};const KINDS=[[BadVerbArgs,`bad-request`],[DaemonClosing,`closing`],[ClickAbandoned,`abandoned`],[RendererDown,`down`]];var CrossedFailure=class extends Error{constructor(e){super(e.message),this.failure=e,this.name=`CrossedFailure`}};function failureOf(e){return e instanceof CrossedFailure?e.failure:{kind:KINDS.find(([t])=>e instanceof t)?.[1]??`threw`,message:e instanceof Error?e.message:inspect(e),detail:inspect(e)}}function badRequest(...e){let t=e.join(`; `);return{kind:`bad-request`,message:t,detail:t}}function decodeWire(e){try{return e()}catch(e){throw e instanceof URIError?new BadVerbArgs(`malformed wire encoding: ${e.message}`):e}}const SESSION_ID_MAX_BYTES=250;function parseSessionId(e){let t=typeof e==`string`?e===``?`is empty`:e===`.`||e===`..`?`is ${JSON.stringify(e)}, which names a folder, not a session`:/[/\\\0]/.test(e)?`contains a path separator or NUL: ${JSON.stringify(e)}`:Buffer.byteLength(e,`utf8`)>250?`is longer than 250 bytes`:null:`is not a string: ${JSON.stringify(e)??String(e)}`;return t===null?{ok:!0,id:e}:{ok:!1,problem:t}}function sessionKeyed(e,t){let n=new Map;for(let[r,i]of Object.entries(e)){let e=parseSessionId(r);e.ok?n.set(e.id,i):t(r,e.problem)}return n}function sessionIdOf(e){let t=parseSessionId(e);if(!t.ok)throw Error(`session id ${t.problem}`);return t.id}const URL_SCHEME$1=`cc-candybar`,isBarLink=e=>e.startsWith(`${URL_SCHEME$1}://`),APP_NAME=`CCCandybarURLHandler`,VERB_DISPATCH=`dispatch`,VERB_SET_STATE=`set-state`,VERB_STEP_STATE=`step-state`,VERB_COPY=`copy`,VERB_OPEN_VSCODE=`open-vscode`,VERB_SET_CONFIG=`set-config`,VERB_STEP_CONFIG=`step-config`,VERB_SAVE=`save`,VERB_SAVE_PRESET=`save-preset`,VERB_SAVE_THEME_DEFAULT=`save-theme-default`,VERB_DELETE_PRESET=`delete-preset`,VERB_RESET_CONFIG=`reset-config`,VERB_APPLY_LAYOUT_OP=`apply-layout-op`,VERB_UNDO=`undo`,VERB_REDO=`redo`,VERB_BACK=`back`,VERB_REWIND=`rewind`,VERB_APPLY_UPDATE=`apply-update`,VERB_DOCTOR_RUN=`doctor-run`,VERB_DOCTOR_FIX=`doctor-fix`,VERB_DOCTOR_MARK=`doctor-mark`,VERB_DOCTOR_PROBE=`doctor-probe`,VERB_SLASH=`slash`,VERB_RUN=`run`,VERB_REPO_CONFIG=`repo-config`,VERB_COPY_DIAGNOSTIC=`copy-diagnostic`,VERB_TMUX_STATUS_CLICK=`tmux-status-click`,STATUS_LINE_CLICK_PREFIX=`${URL_SCHEME$1}://${VERB_TMUX_STATUS_CLICK}/`,DOCTOR_PROBE_PREFIX=`${URL_SCHEME$1}://${VERB_DOCTOR_PROBE}/`,sayStep=(e,t)=>`step ${e} ${t.startsWith(`-`)?`down`:`up`} by ${t.replace(`-`,``)}`,withoutNs=(e,t)=>e.startsWith(t)?e.slice(t.length):e;function sayWrite(e,t){if(e===DIAGNOSTICS_VIEWING)return`${t===`0`?`close`:`open`} diagnostics`;let n=`set ${e} to ${t}`;if(!isReservedName(e))return n;let r=withoutNs(withoutNs(e,MENU_PAGE_NS),MENU_NS);return e.startsWith(`menupages.`)?`turn ${r} to page ${Number(t)+1}`:t===`closed`?`close ${r}`:t===`open`?`open ${r}`:e.startsWith(`menus.`)?`open ${t}`:n}const COPIED_LENGTH=60,ELISION=`...`;function saidCopy(e){let t=[...e],n=Math.floor((COPIED_LENGTH-3)/2);return t.length<=COPIED_LENGTH?e:`${t.slice(0,n).join(``)}${ELISION}${t.slice(-n).join(``)}`}const SAYS={[VERB_SET_STATE]:([,...e])=>e.flatMap((t,n)=>n%2==0?[sayWrite(t,e[n+1])]:[]),[VERB_STEP_STATE]:([,e,t])=>[sayStep(e,t)],[VERB_COPY]:([e])=>[`copy ${saidCopy(e)}`],[VERB_OPEN_VSCODE]:([e])=>[`open ${e} in vs code`],[VERB_SET_CONFIG]:([,e,t])=>[`save ${e} as ${t}`],[VERB_STEP_CONFIG]:([,e,t])=>[`save ${sayStep(e,t)}`],[VERB_SAVE]:()=>[`save settings`],[VERB_SAVE_PRESET]:()=>[`save as a new preset`],[VERB_SAVE_THEME_DEFAULT]:()=>[`save this look for the theme`],[VERB_DELETE_PRESET]:([,e])=>[`delete preset ${e}`],[VERB_RESET_CONFIG]:([,...e])=>e.map(e=>`reset ${e}`),[VERB_APPLY_LAYOUT_OP]:([,e,t])=>[`edit ${t} in ${e}`],[VERB_UNDO]:()=>[`undo`],[VERB_REDO]:()=>[`redo`],[VERB_BACK]:()=>[`go back`],[VERB_REWIND]:()=>[`cancel edits`],[VERB_APPLY_UPDATE]:()=>[`update cc-candybar`],[VERB_DOCTOR_RUN]:()=>[`run doctor`],[VERB_DOCTOR_FIX]:([,e])=>[`fix ${e}`],[VERB_DOCTOR_MARK]:([,e,t])=>[`mark ${e} ${t}`],[VERB_SLASH]:([,e])=>[`type ${e}`],run:([,e])=>[`run ${e}`],[VERB_REPO_CONFIG]:([,e,t])=>[`mark config in ${e} ${t}`],[VERB_COPY_DIAGNOSTIC]:()=>[`copy diagnostic`]},spell=e=>encodeURIComponent(e).replaceAll(`%20`,`+`).replaceAll(`%2F`,`/`).replaceAll(`%3A`,`:`);function clickDoes(e){let t=e=>e.verb===`set-state`||e.verb===`step-state`,[n=`nothing`,...r]=[...e.filter(e=>!t(e)),...e.filter(t)].flatMap(e=>SAYS[e.verb](e.args));return r.length>0?`${n} and ${r.length} more`:n}function encodeSegments(e){return e.map(encodeURIComponent).join(`/`)}function decodeSegments(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function decodeFirstSegment(e){return decodeURIComponent(e.split(`/`,1)[0])}function effectsUrl(e,t=clickDoes(e)){let n=e.map(e=>`e=${encodeURIComponent(`${e.verb}/${encodeSegments(e.args)}`)}`);return`${URL_SCHEME$1}://${VERB_DISPATCH}/${[`does=${spell(t)}`,...n].join(`&`)}`}function parseEffects(e){return new URLSearchParams(e).getAll(`e`).map(splitVerb)}const BATCHED_VERBS=new Set([VERB_SET_STATE,VERB_RESET_CONFIG]);function batchAdjacentWrites(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&joinWrites(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function joinWrites(e,t){if(e.verb!==t.verb||!BATCHED_VERBS.has(e.verb))return;let[n,r]=[splitVerb(e.value),splitVerb(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function splitVerb(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}function parseHandlerUrl(e){let t=`${URL_SCHEME$1}://`;if(!e.startsWith(t))return{ok:!1,problem:`expected a ${t} link, got: ${e}`};let n=e.slice(t.length),r=n.indexOf(`/`);if(r===-1)return{ok:!0,verb:VERB_COPY,value:n};let i=n.slice(0,r);try{return{ok:!0,verb:decodeURIComponent(i),value:n.slice(r+1)}}catch{return{ok:!1,problem:`the link's verb is malformed: ${i}`}}}const SESSION_FIRST_VERBS=new Set([VERB_SET_STATE,VERB_STEP_STATE,VERB_SET_CONFIG,VERB_STEP_CONFIG,VERB_RESET_CONFIG,VERB_SAVE,VERB_SAVE_PRESET,VERB_SAVE_THEME_DEFAULT,VERB_DELETE_PRESET,VERB_APPLY_LAYOUT_OP,VERB_UNDO,VERB_REDO,VERB_BACK,VERB_REWIND,VERB_APPLY_UPDATE,VERB_DOCTOR_RUN,VERB_DOCTOR_FIX,VERB_DOCTOR_MARK,VERB_SLASH,`run`,VERB_REPO_CONFIG,VERB_COPY_DIAGNOSTIC]);function clickSessionOf(e,t){return sessionOfEffects(e===`dispatch`?parseEffects(t):[{verb:e,value:t}])}function sessionOfEffects(e){let t=e.find(e=>SESSION_FIRST_VERBS.has(e.verb)),n=t===void 0?``:decodeWire(()=>decodeFirstSegment(t.value));return n===``?null:parseSessionId(n)}const CLAUDE_CONFIG_DIR_ENV=`CLAUDE_CONFIG_DIR`;function detectClaudeConfigDir(e,t){let n=(e.CLAUDE_CONFIG_DIR??``).split(`,`)[0].trim();return n===``?void 0:path.resolve(t,n)}function claudeConfigDir(e,t){return e??path.join(t,`.claude`)}function claudeSettingsPath(e){return path.join(e,`settings.json`)}function claudeManagedSettingsDir(e){switch(e){case`darwin`:return`/Library/Application Support/ClaudeCode`;case`win32`:return`C:\\Program Files\\ClaudeCode`;default:return`/etc/claude-code`}}const claudeManagedSettingsDirIn=e=>e.CC_CANDYBAR_CLAUDE_MANAGED_DIR??claudeManagedSettingsDir(process.platform),projectLocalSettingsFile=e=>path.join(e,`.claude`,`settings.local.json`),isJsonObject=e=>typeof e==`object`&&!!e&&!Array.isArray(e);var require_unicode=__commonJSMin(((e,t)=>{t.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,t.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,t.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/})),require_util=__commonJSMin(((e,t)=>{let n=require_unicode();t.exports={isSpaceSeparator(e){return typeof e==`string`&&n.Space_Separator.test(e)},isIdStartChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`$`||e===`_`||n.ID_Start.test(e))},isIdContinueChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`$`||e===`_`||e===``||e===``||n.ID_Continue.test(e))},isDigit(e){return typeof e==`string`&&/[0-9]/.test(e)},isHexDigit(e){return typeof e==`string`&&/[0-9A-Fa-f]/.test(e)}}})),require_parse=__commonJSMin(((e,t)=>{let n=require_util(),r,i,a,o,s,c,l,u,d;t.exports=function(e,t){r=String(e),i=`start`,a=[],o=0,s=1,c=0,l=void 0,u=void 0,d=void 0;do l=v(),D[i]();while(l.type!==`eof`);return typeof t==`function`?f({"":d},``,t):d};function f(e,t,n){let r=e[t];if(typeof r==`object`&&r)if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=String(e),i=f(r,t,n);i===void 0?delete r[t]:Object.defineProperty(r,t,{value:i,writable:!0,enumerable:!0,configurable:!0})}else for(let e in r){let t=f(r,e,n);t===void 0?delete r[e]:Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}return n.call(e,t,r)}let p,m,h,g,_;function v(){for(p=`default`,m=``,h=!1,g=1;;){_=y();let e=x[p]();if(e)return e}}function y(){if(r[o])return String.fromCodePoint(r.codePointAt(o))}function b(){let e=y();return e===`
|
|
9
|
+
`)}catch(e){process$1.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}const SPAWN_COOLDOWN_MS=3e3;function cooldownDecision(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}const SPAWN_BACKOFF_CAP_MS=6e4,SPAWN_BACKOFF_MAX_STREAK=5;function effectiveCooldownMs(e){return Math.min(SPAWN_COOLDOWN_MS*2**Math.min(Math.max(e,0),5),SPAWN_BACKOFF_CAP_MS)}function readBackoffStreak(e){try{let t=fs.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function writeBackoffStreak(e,t){try{fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,String(t),{mode:384})}catch(e){process$1.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function resetSpawnBackoff(e){try{fs.unlinkSync(e)}catch(e){e.code!==`ENOENT`&&process$1.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function claimSpawnCooldown(e,t){let n=spawnCooldownPath(e),r=spawnBackoffPath(e),i=readBackoffStreak(r),a=cooldownDecision(cooldownAgeMs(n,t),effectiveCooldownMs(i));return a.kind===`deny`?!1:(a.kind===`allow-future-garbage`&&process$1.stderr.write(`cc-candybar: spawn.cooldown mtime is ${a.futureMs}ms in the future — ignoring and spawning\n`),recordSpawnAttempt(n,t),writeBackoffStreak(r,Math.min(i+1,5)),!0)}function cooldownAgeMs(e,t){try{return t.now()-fs.statSync(e).mtimeMs}catch{return null}}function recordSpawnAttempt(e,t){try{fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,`${process$1.pid} ${t.now()}\n`,{mode:384})}catch(e){process$1.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}const STALE_LOCK_MS=1e4;let heldLock=null;function tryAcquireSpawnLock(e,t){let n=spawnLockPath(e);for(let e=0;e<2;e++){try{let e=fs.openSync(n,`wx`,384);try{fs.writeSync(e,JSON.stringify({pid:process$1.pid,ts:t.now()}))}catch{}return heldLock={fd:e,path:n},{kind:`held`}}catch(e){let t=e.code;if(t!==`EEXIST`)return{kind:`error`,reason:`openSync(${n}): ${t??e.message}`}}if(!isLockStale(n,t))return{kind:`contended`};try{fs.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function isLockStale(e,t){try{let n=fs.statSync(e);return t.now()-n.mtimeMs>STALE_LOCK_MS}catch{return!0}}function releaseSpawnLock(){if(!heldLock)return;let{fd:e,path:t}=heldLock;heldLock=null;try{fs.closeSync(e)}catch{}try{fs.unlinkSync(t)}catch{}}function ensureStateDir(e){try{return fs.mkdirSync(daemonDir(e),{recursive:!0}),null}catch(t){return`mkdir ${daemonDir(e)}: ${t.message}`}}function daemonArgs(e,t){return[`--max-old-space-size=${heapCapMb(t)}`,e,`daemon`]}function spawnDaemonDetachedReal({host:e,launcher:t}){let n=process$1.execPath,r=process$1.argv[1];return r?t.launchDetachedSync({bin:n,args:daemonArgs(r,e.env),category:`daemon-spawn`}).ok:!1}const DISCLOSURE_CLOSED=`closed`,DISCLOSURE_OPEN=`open`,DISCLOSURE_CLOSE_ROLE=`warning`,DOOR_CLOSE_ROLE=`error`,DOOR_GLYPH=`🍫`;function cycleDisplayIssue(e,t,n){if(t===0)return`${e} needs a display (the clickable text)`;if(t!==1&&t!==n)return`${e} cycles ${n} members; bind one display per member (${n}) or one static display, got ${t}`}function pickCycleDisplay(e,t,n,r){let i=cycleDisplayIssue(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function escapeTemplateLiteral(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function disclosureNode(e,t,n,r,i){return{kind:`segment`,name:e,opens:{ref:t,body:n,placement:r},...i!==void 0&&{when:i}}}function disclosureGate(e,...t){return`{{ and ${[e,...t].map(disclosureTerm).join(` `)} }}`}function disclosureTerm(e){return`(eq .${e.variable} "${escapeTemplateLiteral(e.member)}")`}function disclosureTrigger(e,t,n){return`{{ ${disclosureTriggerCall(e,templateLiteral(t),templateLiteral(n))} }}`}function disclosureTriggerCall(e,t,n){return`action "${e}" ${t} ${n}`}function templateLiteral(e){return`"${escapeTemplateLiteral(e)}"`}function disclosureStateVar(e,t){return{kind:`state`,key:e,default:t}}function disclosureCycleAction(e,t){return{set:e,cycle:[DISCLOSURE_CLOSED,t]}}function disclosureOfAction(e){if(!(`set`in e&&`cycle`in e))return;let[t,n,...r]=e.cycle;return t===`closed`&&n!==void 0&&r.length===0?{key:e.set,member:n}:void 0}const GROUP_NS=`groups.`,MENU_NS=`menus.`,MENU_PAGE_NS=`menupages.`,EDIT_NS=`edit.`,SETTINGS_NS=`candybar.`,RESERVED_NAMESPACES=[GROUP_NS,MENU_NS,MENU_PAGE_NS,EDIT_NS,SETTINGS_NS];function isReservedName(e){return RESERVED_NAMESPACES.some(t=>e.startsWith(t))}const SETTINGS_ANCHOR=`${SETTINGS_NS}menu`,SETTINGS_OPEN=DISCLOSURE_OPEN,SETTINGS_REF={variable:SETTINGS_ANCHOR,key:SETTINGS_ANCHOR,member:SETTINGS_OPEN},DIAGNOSTICS_VIEWING=`${SETTINGS_NS}diagnostics`;var BadVerbArgs=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}},DaemonClosing=class extends Error{constructor(e){super(`the daemon closed: ${e} refused`),this.name=`DaemonClosing`}},ClickAbandoned=class extends Error{constructor(e){super(`the client left: ${e} not run`),this.name=`ClickAbandoned`}},RendererDown=class extends Error{constructor(e){super(e),this.name=`RendererDown`}};const KINDS=[[BadVerbArgs,`bad-request`],[DaemonClosing,`closing`],[ClickAbandoned,`abandoned`],[RendererDown,`down`]];var CrossedFailure=class extends Error{constructor(e){super(e.message),this.failure=e,this.name=`CrossedFailure`}};function failureOf(e){return e instanceof CrossedFailure?e.failure:{kind:KINDS.find(([t])=>e instanceof t)?.[1]??`threw`,message:e instanceof Error?e.message:inspect(e),detail:inspect(e)}}function badRequest(...e){let t=e.join(`; `);return{kind:`bad-request`,message:t,detail:t}}function decodeWire(e){try{return e()}catch(e){throw e instanceof URIError?new BadVerbArgs(`malformed wire encoding: ${e.message}`):e}}const SESSION_ID_MAX_BYTES=250;function parseSessionId(e){let t=typeof e==`string`?e===``?`is empty`:e===`.`||e===`..`?`is ${JSON.stringify(e)}, which names a folder, not a session`:/[/\\\0]/.test(e)?`contains a path separator or NUL: ${JSON.stringify(e)}`:Buffer.byteLength(e,`utf8`)>250?`is longer than 250 bytes`:null:`is not a string: ${JSON.stringify(e)??String(e)}`;return t===null?{ok:!0,id:e}:{ok:!1,problem:t}}function sessionKeyed(e,t){let n=new Map;for(let[r,i]of Object.entries(e)){let e=parseSessionId(r);e.ok?n.set(e.id,i):t(r,e.problem)}return n}function sessionIdOf(e){let t=parseSessionId(e);if(!t.ok)throw Error(`session id ${t.problem}`);return t.id}const URL_SCHEME$1=`cc-candybar`,isBarLink=e=>e.startsWith(`${URL_SCHEME$1}://`),APP_NAME=`CCCandybarURLHandler`,VERB_DISPATCH=`dispatch`,VERB_SET_STATE=`set-state`,VERB_STEP_STATE=`step-state`,VERB_COPY=`copy`,VERB_OPEN_VSCODE=`open-vscode`,VERB_SET_CONFIG=`set-config`,VERB_STEP_CONFIG=`step-config`,VERB_SAVE=`save`,VERB_SAVE_PRESET=`save-preset`,VERB_SAVE_THEME_DEFAULT=`save-theme-default`,VERB_DELETE_PRESET=`delete-preset`,VERB_RESET_CONFIG=`reset-config`,VERB_APPLY_LAYOUT_OP=`apply-layout-op`,VERB_UNDO=`undo`,VERB_REDO=`redo`,VERB_BACK=`back`,VERB_REWIND=`rewind`,VERB_APPLY_UPDATE=`apply-update`,VERB_DOCTOR_RUN=`doctor-run`,VERB_DOCTOR_FIX=`doctor-fix`,VERB_DOCTOR_MARK=`doctor-mark`,VERB_DOCTOR_PROBE=`doctor-probe`,VERB_SLASH=`slash`,VERB_RUN=`run`,VERB_REPO_CONFIG=`repo-config`,VERB_COPY_DIAGNOSTIC=`copy-diagnostic`,VERB_TMUX_STATUS_CLICK=`tmux-status-click`,STATUS_LINE_CLICK_PREFIX=`${URL_SCHEME$1}://${VERB_TMUX_STATUS_CLICK}/`,DOCTOR_PROBE_PREFIX=`${URL_SCHEME$1}://${VERB_DOCTOR_PROBE}/`,sayStep=(e,t)=>`step ${e} ${t.startsWith(`-`)?`down`:`up`} by ${t.replace(`-`,``)}`,withoutNs=(e,t)=>e.startsWith(t)?e.slice(t.length):e;function sayWrite(e,t){if(e===DIAGNOSTICS_VIEWING)return`${t===`0`?`close`:`open`} diagnostics`;let n=`set ${e} to ${t}`;if(!isReservedName(e))return n;let r=withoutNs(withoutNs(e,MENU_PAGE_NS),MENU_NS);return e.startsWith(`menupages.`)?`turn ${r} to page ${Number(t)+1}`:t===`closed`?`close ${r}`:t===`open`?`open ${r}`:e.startsWith(`menus.`)?`open ${t}`:n}const COPIED_LENGTH=60,ELISION=`...`;function saidCopy(e){let t=[...e],n=Math.floor((COPIED_LENGTH-3)/2);return t.length<=COPIED_LENGTH?e:`${t.slice(0,n).join(``)}${ELISION}${t.slice(-n).join(``)}`}const SAYS={[VERB_SET_STATE]:([,...e])=>e.flatMap((t,n)=>n%2==0?[sayWrite(t,e[n+1])]:[]),[VERB_STEP_STATE]:([,e,t])=>[sayStep(e,t)],[VERB_COPY]:([e])=>[`copy ${saidCopy(e)}`],[VERB_OPEN_VSCODE]:([e])=>[`open ${e} in vs code`],[VERB_SET_CONFIG]:([,e,t,n])=>[`save ${t} as ${n} in ${e} config`],[VERB_STEP_CONFIG]:([,e,t,n])=>[`save ${sayStep(t,n)} in ${e} config`],[VERB_SAVE]:([,e])=>[`save settings to ${e} config`],[VERB_SAVE_PRESET]:([,e])=>[`save as a new preset in ${e} config`],[VERB_SAVE_THEME_DEFAULT]:([,e])=>[`save this look for the theme in ${e} config`],[VERB_DELETE_PRESET]:([,e,t])=>[`delete preset ${t} from ${e} config`],[VERB_RESET_CONFIG]:([,e,...t])=>t.map(t=>`reset ${t} in ${e} config`),[VERB_APPLY_LAYOUT_OP]:([,e,t,n])=>[`edit ${n} in ${t} of ${e} config`],[VERB_UNDO]:()=>[`undo`],[VERB_REDO]:()=>[`redo`],[VERB_BACK]:()=>[`go back`],[VERB_REWIND]:()=>[`cancel edits`],[VERB_APPLY_UPDATE]:()=>[`update cc-candybar`],[VERB_DOCTOR_RUN]:()=>[`run doctor`],[VERB_DOCTOR_FIX]:([,e])=>[`fix ${e}`],[VERB_DOCTOR_MARK]:([,e,t])=>[`mark ${e} ${t}`],[VERB_SLASH]:([,e])=>[`type ${e}`],run:([,e])=>[`run ${e}`],[VERB_REPO_CONFIG]:([,e,t])=>[`mark config in ${e} ${t}`],[VERB_COPY_DIAGNOSTIC]:()=>[`copy diagnostic`]},spell=e=>encodeURIComponent(e).replaceAll(`%20`,`+`).replaceAll(`%2F`,`/`).replaceAll(`%3A`,`:`);function clickDoes(e){let t=e=>e.verb===`set-state`||e.verb===`step-state`,[n=`nothing`,...r]=[...e.filter(e=>!t(e)),...e.filter(t)].flatMap(e=>SAYS[e.verb](e.args));return r.length>0?`${n} and ${r.length} more`:n}function encodeSegments(e){return e.map(encodeURIComponent).join(`/`)}function decodeSegments(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function decodeFirstSegment(e){return decodeURIComponent(e.split(`/`,1)[0])}function effectsUrl(e,t=clickDoes(e)){let n=e.map(e=>`e=${encodeURIComponent(`${e.verb}/${encodeSegments(e.args)}`)}`);return`${URL_SCHEME$1}://${VERB_DISPATCH}/${[`does=${spell(t)}`,...n].join(`&`)}`}function parseEffects(e){return new URLSearchParams(e).getAll(`e`).map(splitVerb)}const BATCHED_VERBS=new Map([[VERB_SET_STATE,1],[VERB_RESET_CONFIG,2]]);function batchAdjacentWrites(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&joinWrites(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function joinWrites(e,t){let n=BATCHED_VERBS.get(e.verb);if(e.verb!==t.verb||n===void 0)return;let[r,i]=[e.value.split(`/`),t.value.split(`/`)];return r.slice(0,n).join(`/`)===i.slice(0,n).join(`/`)?{verb:e.verb,value:[...r,...i.slice(n)].join(`/`)}:void 0}function splitVerb(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}function parseHandlerUrl(e){let t=`${URL_SCHEME$1}://`;if(!e.startsWith(t))return{ok:!1,problem:`expected a ${t} link, got: ${e}`};let n=e.slice(t.length),r=n.indexOf(`/`);if(r===-1)return{ok:!0,verb:VERB_COPY,value:n};let i=n.slice(0,r);try{return{ok:!0,verb:decodeURIComponent(i),value:n.slice(r+1)}}catch{return{ok:!1,problem:`the link's verb is malformed: ${i}`}}}const SESSION_FIRST_VERBS=new Set([VERB_SET_STATE,VERB_STEP_STATE,VERB_SET_CONFIG,VERB_STEP_CONFIG,VERB_RESET_CONFIG,VERB_SAVE,VERB_SAVE_PRESET,VERB_SAVE_THEME_DEFAULT,VERB_DELETE_PRESET,VERB_APPLY_LAYOUT_OP,VERB_UNDO,VERB_REDO,VERB_BACK,VERB_REWIND,VERB_APPLY_UPDATE,VERB_DOCTOR_RUN,VERB_DOCTOR_FIX,VERB_DOCTOR_MARK,VERB_SLASH,`run`,VERB_REPO_CONFIG,VERB_COPY_DIAGNOSTIC]);function clickSessionOf(e,t){return sessionOfEffects(e===`dispatch`?parseEffects(t):[{verb:e,value:t}])}function sessionOfEffects(e){let t=e.find(e=>SESSION_FIRST_VERBS.has(e.verb)),n=t===void 0?``:decodeWire(()=>decodeFirstSegment(t.value));return n===``?null:parseSessionId(n)}const CLAUDE_CONFIG_DIR_ENV=`CLAUDE_CONFIG_DIR`;function detectClaudeConfigDir(e,t){let n=(e.CLAUDE_CONFIG_DIR??``).split(`,`)[0].trim();return n===``?void 0:path.resolve(t,n)}function claudeConfigDir(e,t){return e??path.join(t,`.claude`)}function claudeSettingsPath(e){return path.join(e,`settings.json`)}function claudeManagedSettingsDir(e){switch(e){case`darwin`:return`/Library/Application Support/ClaudeCode`;case`win32`:return`C:\\Program Files\\ClaudeCode`;default:return`/etc/claude-code`}}const claudeManagedSettingsDirIn=e=>e.CC_CANDYBAR_CLAUDE_MANAGED_DIR??claudeManagedSettingsDir(process.platform),projectLocalSettingsFile=e=>path.join(e,`.claude`,`settings.local.json`),isJsonObject=e=>typeof e==`object`&&!!e&&!Array.isArray(e);var require_unicode=__commonJSMin(((e,t)=>{t.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,t.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,t.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/})),require_util=__commonJSMin(((e,t)=>{let n=require_unicode();t.exports={isSpaceSeparator(e){return typeof e==`string`&&n.Space_Separator.test(e)},isIdStartChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`$`||e===`_`||n.ID_Start.test(e))},isIdContinueChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`$`||e===`_`||e===``||e===``||n.ID_Continue.test(e))},isDigit(e){return typeof e==`string`&&/[0-9]/.test(e)},isHexDigit(e){return typeof e==`string`&&/[0-9A-Fa-f]/.test(e)}}})),require_parse=__commonJSMin(((e,t)=>{let n=require_util(),r,i,a,o,s,c,l,u,d;t.exports=function(e,t){r=String(e),i=`start`,a=[],o=0,s=1,c=0,l=void 0,u=void 0,d=void 0;do l=v(),D[i]();while(l.type!==`eof`);return typeof t==`function`?f({"":d},``,t):d};function f(e,t,n){let r=e[t];if(typeof r==`object`&&r)if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=String(e),i=f(r,t,n);i===void 0?delete r[t]:Object.defineProperty(r,t,{value:i,writable:!0,enumerable:!0,configurable:!0})}else for(let e in r){let t=f(r,e,n);t===void 0?delete r[e]:Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}return n.call(e,t,r)}let p,m,h,g,_;function v(){for(p=`default`,m=``,h=!1,g=1;;){_=y();let e=x[p]();if(e)return e}}function y(){if(r[o])return String.fromCodePoint(r.codePointAt(o))}function b(){let e=y();return e===`
|
|
10
10
|
`?(s++,c=0):e?c+=e.length:c++,e&&(o+=e.length),e}let x={default(){switch(_){case` `:case`\v`:case`\f`:case` `:case`\xA0`:case``:case`
|
|
11
11
|
`:case`\r`:case`\u2028`:case`\u2029`:b();return;case`/`:b(),p=`comment`;return;case void 0:return b(),S(`eof`)}if(n.isSpaceSeparator(_)){b();return}return x[i]()},comment(){switch(_){case`*`:b(),p=`multiLineComment`;return;case`/`:b(),p=`singleLineComment`;return}throw A(b())},multiLineComment(){switch(_){case`*`:b(),p=`multiLineCommentAsterisk`;return;case void 0:throw A(b())}b()},multiLineCommentAsterisk(){switch(_){case`*`:b();return;case`/`:b(),p=`default`;return;case void 0:throw A(b())}b(),p=`multiLineComment`},singleLineComment(){switch(_){case`
|
|
12
12
|
`:case`\r`:case`\u2028`:case`\u2029`:b(),p=`default`;return;case void 0:return b(),S(`eof`)}b()},value(){switch(_){case`{`:case`[`:return S(`punctuator`,b());case`n`:return b(),C(`ull`),S(`null`,null);case`t`:return b(),C(`rue`),S(`boolean`,!0);case`f`:return b(),C(`alse`),S(`boolean`,!1);case`-`:case`+`:b()===`-`&&(g=-1),p=`sign`;return;case`.`:m=b(),p=`decimalPointLeading`;return;case`0`:m=b(),p=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:m=b(),p=`decimalInteger`;return;case`I`:return b(),C(`nfinity`),S(`numeric`,1/0);case`N`:return b(),C(`aN`),S(`numeric`,NaN);case`"`:case`'`:h=b()===`"`,m=``,p=`string`;return}throw A(b())},identifierNameStartEscape(){if(_!==`u`)throw A(b());b();let e=E();switch(e){case`$`:case`_`:break;default:if(!n.isIdStartChar(e))throw M();break}m+=e,p=`identifierName`},identifierName(){switch(_){case`$`:case`_`:case``:case``:m+=b();return;case`\\`:b(),p=`identifierNameEscape`;return}if(n.isIdContinueChar(_)){m+=b();return}return S(`identifier`,m)},identifierNameEscape(){if(_!==`u`)throw A(b());b();let e=E();switch(e){case`$`:case`_`:case``:case``:break;default:if(!n.isIdContinueChar(e))throw M();break}m+=e,p=`identifierName`},sign(){switch(_){case`.`:m=b(),p=`decimalPointLeading`;return;case`0`:m=b(),p=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:m=b(),p=`decimalInteger`;return;case`I`:return b(),C(`nfinity`),S(`numeric`,g*(1/0));case`N`:return b(),C(`aN`),S(`numeric`,NaN)}throw A(b())},zero(){switch(_){case`.`:m+=b(),p=`decimalPoint`;return;case`e`:case`E`:m+=b(),p=`decimalExponent`;return;case`x`:case`X`:m+=b(),p=`hexadecimal`;return}return S(`numeric`,g*0)},decimalInteger(){switch(_){case`.`:m+=b(),p=`decimalPoint`;return;case`e`:case`E`:m+=b(),p=`decimalExponent`;return}if(n.isDigit(_)){m+=b();return}return S(`numeric`,g*Number(m))},decimalPointLeading(){if(n.isDigit(_)){m+=b(),p=`decimalFraction`;return}throw A(b())},decimalPoint(){switch(_){case`e`:case`E`:m+=b(),p=`decimalExponent`;return}if(n.isDigit(_)){m+=b(),p=`decimalFraction`;return}return S(`numeric`,g*Number(m))},decimalFraction(){switch(_){case`e`:case`E`:m+=b(),p=`decimalExponent`;return}if(n.isDigit(_)){m+=b();return}return S(`numeric`,g*Number(m))},decimalExponent(){switch(_){case`+`:case`-`:m+=b(),p=`decimalExponentSign`;return}if(n.isDigit(_)){m+=b(),p=`decimalExponentInteger`;return}throw A(b())},decimalExponentSign(){if(n.isDigit(_)){m+=b(),p=`decimalExponentInteger`;return}throw A(b())},decimalExponentInteger(){if(n.isDigit(_)){m+=b();return}return S(`numeric`,g*Number(m))},hexadecimal(){if(n.isHexDigit(_)){m+=b(),p=`hexadecimalInteger`;return}throw A(b())},hexadecimalInteger(){if(n.isHexDigit(_)){m+=b();return}return S(`numeric`,g*Number(m))},string(){switch(_){case`\\`:b(),m+=w();return;case`"`:if(h)return b(),S(`string`,m);m+=b();return;case`'`:if(!h)return b(),S(`string`,m);m+=b();return;case`
|
|
@@ -55,8 +55,8 @@ import{createRequire}from"node:module";import process$1 from"node:process";impor
|
|
|
55
55
|
`?void 0:{row:t,col:n,anchor:r&&shiftAnchor(r,i)},o=cellLen(e);return[t,n]=e===`
|
|
56
56
|
`?[t+1,0]:[t,n+o],i+=o,{glyph:e,cell:a,width:o}})})}function inked(e){return e.trim()!==``}function walk$1(e){let t=walkGlyphs(e.map(({segment:e})=>e));return e.map((e,n)=>({...e,glyphs:t[n]}))}function edgesBeside(e,t){let n,r=()=>{let n=new Map;return e.forEach(({look:e,glyphs:r},i)=>{let a=t[i];if(e===void 0||a===void 0||!(`painted`in a))return;let o=a.painted;r.forEach(({cell:t},r)=>{if(t===void 0)return;let i=n.get(t.row)??[];i.push({col:t.col,anchor:t.anchor,look:e,moved:o[r]}),n.set(t.row,i)})}),n};return(e,t,i)=>{let a=(n??=r()).get(e[0].row)??[],o=e[0].col,s=e[e.length-1].col;if(t===`right`)return a.find(e=>e.col>s&&drawnBy(e.anchor,i));for(let e=a.length-1;e>=0;e--){let t=a[e];if(t.col<o&&drawnBy(t.anchor,i))return t}}}function drawsLines(e){return[e.underline,e.underline2,e.strike,e.overline,e.frame,e.encircle].some(e=>e===!0)}function measured$1(e,t,n,r){let i=r.backgroundColor.hex,a,o=()=>t().flatMap(({look:e,glyphs:t})=>{if(e===void 0)return[];let n=e.pair.bg.hex!==i||drawsLines(e.style);return t.flatMap(({glyph:t,cell:r,width:i})=>r===void 0?[]:[{cell:{...r,width:i,pair:e.pair,seam:e.seam},shows:inked(t)||n}])}),s=()=>a??=o(),c,l,u=e.flatMap(({segment:e,look:t})=>t!==void 0&&inked(e.text)&&!t.seam?[t.pair]:[]),d=[...new Map(u.map(e=>[`${e.fg.hex}/${e.bg.hex}/${e.terminal.fg}/${e.terminal.bg}/${e.reverse}`,e])).values()],f=e=>d.flatMap(t=>t.terminal[e]?[]:[t[e].hex]);return{all:()=>c??=s().map(({cell:e})=>e),cells:()=>l??=s().flatMap(({cell:e,shows:t})=>t?[e]:[]),pairs:d,colors:new Set([...f(`fg`),...f(`bg`)]),fills:new Set(f(`bg`)),depth:n,theme:r}}function confined(e,...t){let n=new Set(t),r=e=>{for(let t=e.anchor;t;t=t.inner)if(n.has(t.owner))return!0;return!1},i=e=>({...e,all:()=>e.all().filter(r),cells:()=>e.cells().filter(r)});return t=>Animation.map(e(i(t)),e=>(t,n)=>r(n)?e(t,n):t)}function onScreen(e,t){return t?{fg:e.bg,bg:e.fg}:e}function movedSpecs(e,t,n,r){let i=t.bg.compositeOver(SURFACE_BLACK),a=t.fg.compositeOver(i);return{fg:ColorSpec.matchMove(e.fg,a,n,r,!0),bg:ColorSpec.matchMove(e.bg,i,n,r,!1)}}function writesAlike(e,t){return slotWritesAlike(e.color,t.color,!0)&&slotWritesAlike(e.bgcolor,t.bgcolor,!1)}function slotWritesAlike(e,t,n){return e===t||written$2(e,n)===written$2(t,n)}function written$2(e,t){return e?.getAnsiCodes(t).join(`;`)??``}function returned(e){if(e.attributes===void 0)throw TypeError(`an effect frame returns the look it was handed with its changes, { ...look, fg, bg }: this one returned no attributes`);return e}const MOVED=ATTRIBUTE_NAMES.filter(e=>e!==`reverse`);function cellAttributes(e){return Object.fromEntries(MOVED.map(t=>[t,e[t]]))}function sameAttributes(e,t){return e===t||MOVED.every(n=>e[n]===t[n])}function sameSpec(e,t){return e===t||e!==void 0&&t!==void 0&&e.type===t.type&&e.name===t.name}function sameColors(e,t){return sameColor(e.fg,t.fg)&&sameColor(e.bg,t.bg)}function sameColor(e,t){return e.red===t.red&&e.green===t.green&&e.blue===t.blue&&e.alpha===t.alpha}const P=(()=>{let e=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];return[...e,...e]})(),fade=e=>e*e*e*(e*(e*6-15)+10),lerp=(e,t,n)=>e+n*(t-e);function grad(e,t,n,r){let i=e&15,a=i<8?t:n,o=i<4?n:i===12||i===14?t:r;return(i&1?-a:a)+(i&2?-o:o)}function noise(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=Math.floor(n),o=r&255,s=i&255,c=a&255;e-=r,t-=i,n-=a;let l=fade(e),u=fade(t),d=fade(n),f=P[o]+s,p=P[f]+c,m=P[f+1]+c,h=P[o+1]+s,g=P[h]+c,_=P[h+1]+c;return lerp(lerp(lerp(grad(P[p],e,t,n),grad(P[g],e-1,t,n),l),lerp(grad(P[m],e,t-1,n),grad(P[_],e-1,t-1,n),l),u),lerp(lerp(grad(P[p+1],e,t,n-1),grad(P[g+1],e-1,t,n-1),l),lerp(grad(P[m+1],e,t-1,n-1),grad(P[_+1],e-1,t-1,n-1),l),u),d)}function fbm(e,t,n,r){let i=0,a=1,o=0;for(let s=0;s<r;s++){let r=2**s;i+=a*noise(e*r,t*r,n*r),o+=a,a/=2}return i/o}function hash(e,t){let n=Math.sin(e*12.9898+t*78.233)*43758.5453;return n-Math.floor(n)}function smoothstep(e,t,n){let r=Math.min(1,Math.max(0,(n-e)/(t-e)));return r*r*(3-2*r)}const LEGIBLE$1=4.5,LEVELS$1=48,STRENGTHS=Array.from({length:LEVELS$1},(e,t)=>(t+1)/LEVELS$1),ROUNDING=.01;function floorOf$1(e,t){return Math.min(contrastRatio(e.fg,e.bg),LEGIBLE$1)-(t===ColorDepth.TRUECOLOR?ROUNDING:0)}const SIDES=[`fg`,`bg`];function shares({pairs:e,depth:t,theme:n},r,i){let a=(e,t)=>e.terminal[t]?void 0:e[t].hex,o=new Map(e.flatMap(e=>SIDES.flatMap(t=>{let n=a(e,t);return n===void 0?[]:[[n,e[t]]]}))),s=new Map([...r].filter(e=>!o.has(e)).map(e=>[e,1])),c=e=>Oklch.fromRgba(o.get(e)).l;for(let l of[...r].filter(e=>o.has(e)).sort((e,t)=>c(t)-c(e))){let r=e.flatMap(e=>{let t=SIDES.find(t=>a(e,t)===l);if(t===void 0)return[];let n=a(e,t===`fg`?`bg`:`fg`);return[[e,t,n===void 0?0:s.get(n)??0]]}),o=e=>r.every(([r,a,o])=>{let s=floorOf$1(r,t),c=(t,n)=>touchedAt(i,r[t],(t===a?e:o)*n);return STRENGTHS.every(e=>{let i=Effected.shows(r,{fg:c(`fg`,e),bg:c(`bg`,e)},t,n);return contrastRatio(i.fg,i.bg)>=s})}),[c,u]=o(1)?[1,1]:[0,1];for(let e=0;e<20&&u-c>.001;e++){let e=(c+u)/2;[c,u]=o(e)?[e,u]:[c,e]}s.set(l,c)}return s}function onColors(e,t){let n=new WeakMemo;return stillOnSlots(atShares(e,r=>{let i=t??r.colors,a=[drawnKey(r),`|`,...i].join(` `);return n.get(r.theme,()=>new Memo).get(a,()=>shares(r,i,e.touch))}))}function drawnKey({depth:e,pairs:t}){return[e,...t.map(pairKey)].join(` `)}function pairKey({fg:e,bg:t,terminal:n,reverse:r}){return`${e.hex}/${t.hex}/${n.fg}/${n.bg}/${r}`}function atShares(e,t){return n=>{let r=t(n);return Animation.continuous(t=>{let i=e.field(t,n);return(t,n)=>{let a=Math.round(clamp01(i(n))*LEVELS$1)/LEVELS$1,o=(t,n)=>touchedAt(e.touch,t,(n?0:r.get(t.hex)??0)*a);return{...t,fg:o(t.fg,n.terminal.fg),bg:o(t.bg,n.terminal.bg)}}})}}function stillOnSlots(e){return t=>onlySlots(t.depth)?Animation.constant(e=>e):e(t)}function onlySlots(e){switch(e){case ColorDepth.DEFAULT:case ColorDepth.STANDARD:case ColorDepth.WINDOWS:return!0;case ColorDepth.EIGHT_BIT:case ColorDepth.TRUECOLOR:return!1}}function touchedAt(e,t,n){return n===0?t:e(t,n)}function requireCurve(e){if(!(Number.isFinite(e.seconds)&&e.seconds>0))throw RangeError(`curve: seconds must be a positive number of seconds, got ${e.seconds}`);if(!(e.swing>=0&&e.swing<=1))throw RangeError(`curve: swing must be in [0, 1], got ${e.swing}`)}function requireZ(e,t){if(!Number.isFinite(t))throw RangeError(`${e} z must be a finite place in the noise, got ${t}`)}const EFFECT_CURVES={shimmer:{seconds:109,ease:EASES.linear,swing:.9},pulse:{seconds:43,ease:EASES.linear,swing:.85},sparkle:{seconds:139,ease:EASES.linear,swing:.95},wheel:{seconds:907,ease:EASES.linear,swing:1},fade:{seconds:20,ease:EASES[`ease-in-out`],swing:1},dissolve:{seconds:30,ease:EASES[`ease-in-out`],swing:1}},EFFECT_LIGHTS={sun:new ColorRgba(255,228,176),firefly:new ColorRgba(222,245,140)},SHIMMER_WIDTH=24,clamp01=e=>Math.min(1,Math.max(0,e));function blend(e,t,n){if(!(n>=0&&n<=1))throw RangeError(`blend: w must be in [0, 1]; got ${n}`);let r=Math.PI/180,i=(1-n)*e.c*Math.cos(e.h*r)+n*t.c*Math.cos(t.h*r),a=(1-n)*e.c*Math.sin(e.h*r)+n*t.c*Math.sin(t.h*r);return new Oklch((1-n)*e.l+n*t.l,Math.hypot(i,a),Math.atan2(a,i)/r,e.alpha)}function light(e){let t=Oklch.fromRgba(e);return(e,n)=>{let r=Oklch.fromRgba(e);return blend(r,new Oklch(Math.max(r.l,t.l),t.c,t.h,t.alpha),n).toRgba()}}const lasts=(e,t)=>t*e[e.length-1][0];function swell(e,t,n){let r=t/n,i=e.findIndex(([e])=>r<e);if(!(r>0)||i<0)return 0;let[a,o]=i===0?[0,0]:e[i-1],[s,c]=e[i];return n*(o+(c-o)*(1-Math.cos(Math.PI*(r-a)/(s-a)))/2)}function given(e,t,n){let r=lasts(e,n),i=t=>{let r=0;for(let i=0;i<24;i++)r+=swell(e,(i+.5)/24*t,n);return r*t};return i(Math.min(Math.max(t,0),r))/i(r)}const FLASH=[[.24,1],[.6,0]];function pulse(e,t,n){requireCurve(e),requireZ(`pulse`,n);let r=.9+.2*hash(n,3.1),i=.1,a=t=>.1*noise(t/(3*e.seconds),.5,.5+n),o=a(0);return{touch:light(t),field:t=>{let i=r*t/e.seconds+a(t)-o,s=Math.floor(i),c=.7+.3*smoothstep(-.5,.5,noise(s*.37,2.1,n)),l=.5-.5*Math.cos(2*Math.PI*(i-s)),u=e.swing*e.ease(c*l);return()=>u}}}const STRIDE=80,bump$1=e=>Math.abs(e)>=1?0:(1-e*e)**3;function shimmer(e,t,n,r){requireCurve(e),requireZ(`shimmer`,r);let i=e.seconds,a=i/2,o=e=>smoothstep(-.4,.4,noise(e/7,3.3,5.5+r)),s=.7,c=.51,l=.4,u=(e,n,u)=>{let d=o(e),f=(hash(e,7.5+r)<.35+.6*d)*(.3+.7*d*(.6+.4*hash(e,8.5+r))),p=i*u/STRIDE*(c+l*hash(e,5.5+r)),m=clamp01((n-(e+s*hash(e,6.5+r))*a)/p);return{strength:f,centre:m*u-t+.06*u*Math.sin(Math.PI*m)*noise(m,2.7,e+r)}},d=(e,t)=>{let n=s+(c+l)*i*t/STRIDE/a,r=Math.floor(e/a),o=[];for(let i=Math.max(0,Math.ceil(r-n));i<=r;i++)o.push(u(i,e,t));return o},f=(e,t,n)=>Math.exp(-((noise(e,t,n)/.8)**2));return{touch:light(n),field:(n,i)=>{let[a,o]=extent(i.cells().map(e=>e.col)),s=d(n,o-a+1+2*t);return i=>{let o=0;for(let{strength:e,centre:n}of s)o=Math.max(o,e*bump$1((i.col-a-n)/t));let c=i.row+r,l=.8*noise(i.col*.05,c*.3+1.3,n*.02),u=(f(i.col*.21+l,c*.9,n*.022)*f(i.col*.33+9.1-l,c*.7,n*.018+4.2))**2;return e.swing*e.ease(o*(.1+.6*u))}}}}function sparkle(e,t,n){requireCurve(e),requireZ(`sparkle`,n);let r=8,i=3,a=5,o=5,s=5,c=e.seconds,l=22.1,u=3.1,d=(e,t,r,i,a)=>{let o=e*4.9+t*31.7+.3+n,s=e+.5+.7*noise(e*1.7+.2,.3+t*2.9,.5+n),l=r+hash(e+t*1013,.7+n)*c,u=Math.floor(l/c),d=hash(u,o+1)<.15?0:1,f=.5+.5*hash(u,o+2),p=hash(u,o+3)*(1-lasts(FLASH,f)),m=l/c-u-p;return{x:i+s*8+5*(2*hash(u,o+4)-1)+5*f*(2*hash(u,o+5)-1)*given(FLASH,m,f)+1.5*noise(o,.1,r*.035),y:a+t*3+.6*noise(o,2.2,r*.035),glow:d*swell(FLASH,m,f)}};return{touch:light(t),field:(t,n)=>{let r=n.cells(),[i,a]=extent(r.map(e=>e.col)),[o,s]=extent(r.map(e=>e.row)),c=e=>(e-i)/8-.5,f=e=>(e-o)/3,[p,m]=[Math.ceil(c(i-l)),Math.floor(c(a+l))],[h,g]=[Math.ceil(f(o-u)),Math.floor(f(s+u))],_=Array.from({length:g-h+1},(e,n)=>Array.from({length:m-p+1},(e,r)=>d(p+r,h+n,t,i,o)));return t=>{let n=0,[r,i]=[Math.max(p,Math.ceil(c(t.col-l))),Math.min(m,Math.floor(c(t.col+l)))],[a,o]=[Math.max(h,Math.ceil(f(t.row-u))),Math.min(g,Math.floor(f(t.row+u)))];for(let e=a;e<=o;e++)for(let a=r;a<=i;a++){let r=_[e-h][a-p];n=Math.max(n,r.glow*bump$1(Math.hypot(t.col-r.x,2*(t.row-r.y))/5))}return e.swing*e.ease(n)}}}}function veiled(e,t){return n=>{let r=Oklch.fromRgba(n.theme.backgroundColor);return Animation.continuous(i=>{let a=e(i,n);return(e,n)=>{let i=t*(1-clamp01(a(n)));if(i===0)return e;let o=blend(Oklch.fromRgba(e.bg),r,i);return{...e,fg:blend(Oklch.fromRgba(e.fg),o,i).toRgba(),bg:o.toRgba()}}})}}function order(e){return t=>clamp01(.5+1.1*fbm(t.col*.09+1.4*noise(t.col*.035,t.row*.2+2.6,e+.5),t.row*.45,e,3))}var Transition=class{effect;schedule;constructor(e,t){this.effect=e,this.schedule=t}done(e){return Animation.done(this.schedule,e)}};function transition(e,t){let n=Animation.of({...Animation.sequence(Animation.continuous(()=>void 0),e,Animation.constant(void 0)),reduced:()=>Animation.cut(void 0,void 0)}),r=new Transition(i=>{let a=t(i);return Animation.of({at:e=>a.at(e),nextChange:e=>r.done(e)?1/0:a.nextChange(e),lastChange:e=>r.done(e)?n.lastChange(e):a.lastChange(e),reduced:()=>Animation.cut(a.at(0),a.at(e))})},n);return r}const OWN=.45;function ownChange(e,t){return(n,r)=>{let[i,a]=extent(r.map(t)),o=(a>i?1-OWN:0)*e.seconds,s=Phase.once(0,e.seconds-o);return e=>{let r=a>i?clamp01((t(e)-i)/(a-i)):0;return{along:r,progress:s(n-r*o)}}}}function extent(e){let t=e[0]??0,n=t;for(let r of e)t=Math.min(t,r),n=Math.max(n,r);return[t,n]}function fadeIn(e,t){requireCurve(e),requireZ(`fadeIn`,t);let n=ownChange(e,order(1.7+t));return transition(e.seconds,veiled((t,r)=>{let i=n(t,r.cells());return t=>e.ease(i(t).progress)},e.swing))}const DISSOLVE_SHAPE={depth:.4,from:.5,to:.95,maskFrom:.35,maskTo:.75,late:.6};function dissolveOut(e,t){requireCurve(e),requireZ(`dissolveOut`,t);let n=order(9.3+t),r=ownChange(e,order(4.2+t)),{depth:i,from:a,to:o,maskFrom:s,maskTo:c,late:l}=DISSOLVE_SHAPE;return transition(e.seconds,veiled((t,u)=>{let d=r(t,u.cells());return t=>{let{along:r,progress:u}=d(t),f=e.ease(u),p=clamp01((f-a)/(o-a)),m=i*smoothstep(s,c,n(t))*(1-l+l*r)*Math.sin(Math.PI*p)**2;return 1-f+m}},e.swing))}const STRAY_PERIODS=[211,337],STRAY=180,STRAY_SPREAD=24,ownPlace=(e,t)=>({row:e.row,centre:e.col+t/2});function segmentsOf$1(e){let{colors:t}=e,n=(e,t)=>`${e}:${t}`,r=new Map,i=new Set,a=e=>{if(e.seam)return;let n=(e,n)=>!e&&t.has(n)?n:void 0;return n(e.pair.terminal.bg,e.pair.bg.hex)??n(e.pair.terminal.fg,e.pair.fg.hex)},o=[],s=new Map;for(let t of e.all()){r.set(n(t.row,t.col),t);let e=a(t);for(let r=t.col;r<t.col+t.width;r++)t.seam&&i.add(n(t.row,r)),e!==void 0&&(s.set(n(t.row,r),o.length),o.push({row:t.row,col:r,hex:e}))}let c=o.map((e,t)=>t),l=e=>{for(;c[e]!==e;)c[e]=c[c[e]],e=c[e];return e},u=(e,t,r)=>{let i=s.get(n(t,r));i!==void 0&&o[i].hex===o[e].hex&&(c[l(e)]=l(i))};o.forEach(({row:e,col:t},n)=>{u(n,e,t-1),u(n,e-1,t)});let d=new Map;o.forEach(({row:e,col:t,hex:n},r)=>{let i=l(r),a=d.get(i);a===void 0?d.set(i,{hex:n,top:e,bottom:e,left:t,right:t}):[a.top,a.bottom,a.left,a.right]=[Math.min(a.top,e),Math.max(a.bottom,e),Math.min(a.left,t),Math.max(a.right,t)]});let f=(e,t)=>{let r=s.get(n(e,t));return r===void 0?void 0:d.get(l(r))},p=e=>({row:(e.top+e.bottom)/2,centre:(e.left+e.right+1)/2}),m=(e,t,r)=>{let a=t;for(;i.has(n(e,a));)a+=r;return f(e,a)};return(e,t)=>{let i=r.get(n(e.row,e.col)),a=i?.width??1,o=(i?.seam===!0?[m(e.row,e.col-1,-1),m(e.row,e.col+a,1)]:[]).find(e=>e?.hex===t)??f(e.row,e.col);return o===void 0?ownPlace(e,a):p(o)}}function wheel(e,t){requireCurve(e),requireZ(`wheel`,t);let n=e.seconds,r=({row:e,centre:n},r)=>noise(r/STRAY_PERIODS[0],n/STRAY_SPREAD+5.9,t+e/STRAY_SPREAD+2.3)+.5*noise(r/STRAY_PERIODS[1],n/STRAY_SPREAD+97.3,t+e/STRAY_SPREAD+7.1),i=(t,i)=>360*i/n+e.swing*STRAY*((r(t,i)-r(t,0))/1.5),a=new WeakMemo;return stillOnSlots(e=>{let{colors:t,fills:n,depth:r,theme:o}=e,s=(e,n)=>!e&&t.has(n.hex),c=(e,t,r)=>n.has(e.hex)||!r?e.hex:t.hex,l=(e,t)=>`${e.hex} ${t}`,u=a.get(o,()=>new Memo).get(drawnKey(e),()=>turnedBounds(e.pairs,r,(e,t)=>{let n=t===`fg`?`bg`:`fg`;return s(e.terminal[t],e[t])?l(e[t],c(e[t],e[n],s(e.terminal[n],e[n]))):void 0})),d=measuredIndexed(r,o),f=segmentsOf$1(e);return Animation.continuous(e=>{let t=new Map,n=(t,n,a)=>{let o=hueTurned(t,i(a,e));return nearestWithin(o.looks,t,r===ColorDepth.TRUECOLOR?o.either.map(measured):d,u.get(l(t,n))??UNBOUNDED)},a=(e,r,i)=>{let a=`${l(e,r)} ${i.row}:${i.centre}`,o=t.get(a)??n(e,r,i);return t.set(a,o),o};return(e,t)=>{let n={fg:s(t.terminal.fg,e.fg),bg:s(t.terminal.bg,e.bg)},r=(e,n,r,i)=>n?a(e,c(e,r,i),f(t,e.hex)):e;return{...e,fg:r(e.fg,n.fg,e.bg,n.bg),bg:r(e.bg,n.bg,e.fg,n.fg)}}})})}function hueTurned(e,t){if(t===0)return{looks:e,either:[e]};let n=Oklch.fromRgba(e),r=relativeLuminance(e),i=e=>new Oklch(e,n.c,n.h+t,n.alpha).toRgba(),[a,o]=[0,1];for(let e=0;e<24;e++){let e=(a+o)/2;[a,o]=relativeLuminance(i(e))<r?[e,o]:[a,e]}return{looks:i(o),either:[i(a),i(o)]}}const stop=e=>Math.log(contrastRatio(e,new ColorRgba(0,0,0))),UNBOUNDED={lo:-1/0,hi:1/0},STILL$1={lo:1/0,hi:-1/0},ROUNDING_GAP=Math.log(1.031);function turnedBounds(e,t,n){let r=new Map;for(let i of e.filter(e=>floorOf$1(e,t)>1)){let e=(Math.log(contrastRatio(i.fg,i.bg))-Math.log(floorOf$1(i,t)))/SIDES.filter(e=>n(i,e)!==void 0).length;for(let t of SIDES){let a=n(i,t);if(a===void 0)continue;let[o,s]=[stop(i[t]),stop(i[t===`fg`?`bg`:`fg`])],{lo:c,hi:l}=r.get(a)??UNBOUNDED;r.set(a,o>=s?{lo:Math.max(c,o-e),hi:l}:{lo:c,hi:Math.min(l,o+e)})}}return new Map([...r].map(([e,{lo:t,hi:n}])=>[e,n-t<ROUNDING_GAP?STILL$1:{lo:t,hi:n}]))}const measured=e=>({color:e,looks:Oklch.fromRgba(e),stop:stop(e)}),measuredMemo=new WeakMemo;function measuredIndexed(e,t){return measuredMemo.get(ColorSpec.indexed(e,t),e=>e.map(([,e])=>measured(e)))}function nearestWithin(e,t,n,{lo:r,hi:i}){return nearestOf(e,[measured(t),...n.filter(({stop:e})=>e>=r&&e<=i)]).color}function nearestOf(e,t){let n=Oklch.fromRgba(e),r;for(let e of t){let t=n.deltaE(e.looks);(r===void 0||t<r[1])&&(r=[e,t])}return r?.[0]}function blink({attribute:e,off:t,on:n}){let r=beat([t,n]),i=[e=>e,t=>({...t,attributes:{...t.attributes,[e]:!0}})];return()=>Animation.map(r,e=>i[e])}const ATTRIBUTE_DEFAULTS={blink:{attribute:`conceal`,off:.5,on:.5},boldPulse:{attribute:`bold`,off:.7,on:.3}},EFFECT_CATALOGUE={loops:{shimmer:(e,t=EFFECT_CURVES.shimmer)=>onColors(shimmer(t,24,EFFECT_LIGHTS.sun,e.z)),pulse:(e,t=EFFECT_CURVES.pulse)=>onColors(pulse(t,EFFECT_LIGHTS.sun,e.z)),sparkle:(e,t=EFFECT_CURVES.sparkle)=>onColors(sparkle(t,EFFECT_LIGHTS.firefly,e.z)),wheel:(e,t=EFFECT_CURVES.wheel)=>wheel(t,e.z)},transitions:{fade:(e,t=EFFECT_CURVES.fade)=>fadeIn(t,e.z),dissolve:(e,t=EFFECT_CURVES.dissolve)=>dissolveOut(t,e.z)},attributes:{blink:()=>blink(ATTRIBUTE_DEFAULTS.blink),boldPulse:()=>blink(ATTRIBUTE_DEFAULTS.boldPulse)}};function placeGlyphs(e,t){let n=0,r=walkGlyphs(e).map(e=>e.map(({glyph:e,cell:r})=>({glyph:e,cell:r&&{...r,glyph:e,index:n++,seed:cellSeed(t,r.row,r.col)}})));return{placed:r,cells:r.flatMap(e=>e.flatMap(({cell:e})=>e===void 0?[]:[e]))}}function showGlyphs(e,t){let n=e.map(e=>e.map(({glyph:e,cell:n})=>n===void 0?e:shows(t,n)));return standsApart(e.flat(),n.flat()),n}function reglyphText(e,t,n){let{placed:r,cells:i}=placeGlyphs([new Segment(e.plain)],n.key);return Animation.map(t({cells:i,asciiOnly:n.asciiOnly}),t=>rewritten(e,r[0],showGlyphs(r,t)[0]))}function rewritten(e,t,n){if(n.every((e,n)=>e===t[n].glyph))return e;let r=[0],i=[0];t.forEach(({glyph:e},t)=>{r.push(r[t]+e.length),i.push(i[t]+n[t].length)});let a=e=>{let a=0;for(;a+1<r.length&&r[a+1]<=e;)a++;return a===t.length?i[a]:i[a]+Math.min(e-r[a],n[a].length)},o=e.blankCopy(n.join(``));for(let t of e.spans)o.stylize(t.style,a(t.start),a(t.end));return o}const BREAKS=pattern(/[\n\t]/);function shows(e,t){let n=e(t);if(n===t.glyph)return n;if(cellLen(n)!==cellLen(t.glyph)||BREAKS.test(n)||stripControlChars(n)!==n)throw RangeError(`a glyph effect turned ${JSON.stringify(t.glyph)} at row ${t.row}, column ${t.col} into ${JSON.stringify(n)}: it must be ${cellLen(t.glyph)} cell(s) wide, with no line break or control character`);return n}function standsApart(e,t){let n=n=>e[n]?.cell===void 0?``:t[n];t.forEach((t,r)=>{let{glyph:i,cell:a}=e[r];if(a===void 0||t===i)return;let[o,s]=[n(r-1),n(r+1)];if(graphemes(o+t+s).length!==graphemes(o).length+graphemes(t).length+graphemes(s).length)throw RangeError(`a glyph effect turned ${JSON.stringify(i)} at row ${a.row}, column ${a.col} into ${JSON.stringify(t)}, which joins the cell beside it into one character`)})}function blank(e){return` `.repeat(cellLen(e))}function text$1(e){let t=new Map;for(let n of e.filter(e=>inked(e.glyph)))t.set(n.row,{first:t.get(n.row)?.first??n.index,last:n.index});let n=new Map;for(let r of e){let e=t.get(r.row);e!==void 0&&r.index>=e.first&&r.index<=e.last&&cellLen(r.glyph)>0&&n.set(r.index,n.size)}return{length:n.size,place:n}}function arrived(e,t){return Math.min(e,Math.max(0,Math.floor(e*t)))}function stepped(e){let t=beat([e]);return(n,r)=>Animation.of({at:r=>n(Math.round(t.lastChange(r)/e)),nextChange:e=>t.nextChange(e),lastChange:e=>t.lastChange(e),reduced:()=>Animation.constant(r)})}const AS_WRITTEN=e=>e.glyph;function typewriter(e){let t=Phase.once(0,e.seconds),n=settled$1(e.ease);return transition(e.seconds,({cells:e})=>{let{length:r,place:i}=text$1(e);return Animation.continuous(e=>{let a=arrived(r,n(t(e)));return e=>(i.get(e.index)??-1)<a?e.glyph:blank(e.glyph)})})}const SCRAMBLE_GLYPHS=[...`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#$%&*+<=>?@`],FLICKER=1/15;function scramble(e,t){requireZ(`scramble`,t);let n=Phase.once(0,e.seconds),r=settled$1(e.ease),i=stepped(FLICKER)(e=>e,0);return transition(e.seconds,({cells:e})=>{let{length:a,place:o}=text$1(e);return Animation.continuous(e=>{let s=arrived(a,r(n(e))),c=i.at(e);return e=>!inked(e.glyph)||(o.get(e.index)??-1)<s?e.glyph:churned(e,t,c)})})}function churned(e,t,n){let r=r=>SCRAMBLE_GLYPHS[Math.floor(hash(e.seed*7919+r,t+n*.618)*SCRAMBLE_GLYPHS.length)];return Array.from({length:cellLen(e.glyph)},(e,t)=>r(t)).join(``)}function backspace(e){let t=Phase.once(0,e.seconds),n=settled$1(e.ease);return transition(e.seconds,({cells:e})=>{let{length:r,place:i}=text$1(e);return Animation.continuous(e=>{let a=r-arrived(r,n(t(e)));return e=>(i.get(e.index)??-1)<a?e.glyph:blank(e.glyph)})})}const CHURN=.3;function scrambleOut(e,t){requireZ(`scrambleOut`,t);let n=Phase.once(0,e.seconds),r=settled$1(e.ease),i=stepped(FLICKER)(e=>e,0);return transition(e.seconds,({cells:e})=>{let{length:a,place:o}=text$1(e);return Animation.continuous(e=>{let s=r(n(e)),c=arrived(a,s/(1-CHURN)),l=arrived(a,(s-CHURN)/(1-CHURN)),u=i.at(e);return e=>{let n=o.get(e.index)??1/0;return n<l?blank(e.glyph):!inked(e.glyph)||n>=c?e.glyph:churned(e,t,u)}})})}function swapCase(e){let t=[...e].map(e=>e===e.toUpperCase()?e.toLowerCase():e.toUpperCase()).join(``);return cellLen(t)===cellLen(e)?t:e}function caseWave({step:e,width:t},n){if(positiveSeconds(`caseWave step`,e),!(Number.isInteger(t)&&t>0))throw RangeError(`caseWave width must be a positive whole number of columns, got ${t}`);requireZ(`caseWave`,n);let r=stepped(e);return({cells:e})=>{let i=e.reduce((e,t)=>Math.max(e,t.col+cellLen(t.glyph)),0)+t,a=Math.floor(hash(n,2.3)*i);return r(e=>{let n=((e+a)%i+i)%i;return e=>e.col<n&&e.col+cellLen(e.glyph)>n-t?swapCase(e.glyph):e.glyph},AS_WRITTEN)}}function particles(e,t){let n=e=>{let t=graphemes(e);if(t.length===0||t.some(e=>cellLen(e)!==1))throw RangeError(`particles needs one-cell glyphs, got ${JSON.stringify(e)}`);return t},[r,i]=[n(e.glyphs),n(e.ascii)];if(!isAscii(e.ascii))throw RangeError(`particles ascii must be ASCII, got ${JSON.stringify(e.ascii)}`);if(!(e.density>=0&&e.density<=1))throw RangeError(`particles density must be in [0, 1], got ${e.density}`);if(!Number.isInteger(e.drift))throw RangeError(`particles drift must be a whole number of rows, got ${e.drift}`);if(!(e.life>0))throw RangeError(`particles life must be a positive number of steps, got ${e.life}`);positiveSeconds(`particles step`,e.step),requireZ(`particles`,t);let a=stepped(e.step);return({asciiOnly:n})=>{let o=drawable$1({asciiOnly:n},r,i,e=>e.join(``));return a(n=>{let r=Number.isFinite(e.life)?Math.floor(n/e.life):0,i=e.drift*n;return n=>{if(inked(n.glyph)||cellLen(n.glyph)===0)return n.glyph;let a=n.row-i,s=t+1.37*n.col+.71*r;return hash(a,s)<e.density?o[Math.floor(hash(a,s+3.1)*o.length)]+blank(n.glyph).slice(1):n.glyph}},AS_WRITTEN)}}const GLYPH_DEFAULTS={typewriter:{seconds:2,ease:EASES.linear},scramble:{seconds:2.5,ease:EASES[`ease-in`]},backspace:{seconds:1.5,ease:EASES.linear},scrambleOut:{seconds:2.5,ease:EASES[`ease-out`]},wave:{step:.06,width:3},rain:{glyphs:`│╎`,ascii:`|:`,density:.06,step:.08,drift:1,life:1/0},stars:{glyphs:`·+*`,ascii:`.+*`,density:.04,step:1.5,drift:0,life:1}},GLYPH_EFFECT_CATALOGUE={loops:{wave:e=>caseWave(GLYPH_DEFAULTS.wave,e.z),rain:e=>particles(GLYPH_DEFAULTS.rain,e.z),stars:e=>particles(GLYPH_DEFAULTS.stars,e.z)},transitions:{typewriter:(e,t=GLYPH_DEFAULTS.typewriter)=>typewriter(t),scramble:(e,t=GLYPH_DEFAULTS.scramble)=>scramble(t,e.z),backspace:(e,t=GLYPH_DEFAULTS.backspace)=>backspace(t),scrambleOut:(e,t=GLYPH_DEFAULTS.scrambleOut)=>scrambleOut(t,e.z)}};var FrameSequence=class{beat;width;_shown;constructor(e){this.beat=beat(e.map(e=>e.seconds));let t=e.map(e=>setIntoLine(e.text.copy())),n=t.map(e=>e.cellLength);this.width=Math.max(...n),this._shown=t.map((e,t)=>(e.noWrap=!0,e.overflow=`crop`,e.padRight(this.width-n[t])))}at(e){return this._shown[this.beat.at(e)].copy()}nextChange(e){return this.beat.nextChange(e)}lastChange(e){return this.beat.lastChange(e)}reduced(){return Animation.map(this.beat.reduced(),e=>this._shown[e].copy())}render(e){return placedRender(this,e)}measure(){return{minimum:this.width,maximum:this.width}}};function textFrameAt(e,t,n){let r=shownAt(e,t,n),i=r.value.copy();return i.style=layerStyle(i.style,stamp(holdOf(r,t))),i}function renderToBlock(e,t){let n=[...render(e,t)],r=0;for(let e of n)r+=e.cellLength;return{segments:n,width:r}}const EMPTY_BLOCK={segments:[],width:0},PAD_LEFT_BY_ALIGN={left:()=>0,justify:()=>0,center:e=>Math.floor(e/2),right:e=>e};function computePadLeft(e,t){return PAD_LEFT_BY_ALIGN[e](t)}function computeSlotFills(e,t,n,r){let i=Math.max(0,r-1),a=e===`justify`&&!t&&i>0&&n>0?n:0,o=i>0?Math.floor(a/i):0,s=a-o*i;return Array.from({length:i},(e,t)=>o+ +(t<s))}var FlexStrip=class{items;joiner;gap;align;constructor(e,t){this.items=e,this.joiner=t?.joiner,this.gap=t?.gap??0,this.align=t?.align??`left`}*render(e){let t=this.items;if(t.length===0)return;let n=Math.max(1,e.maxWidth),r=this.gap,i=this.joiner,a=t.map(t=>renderToBlock(drawItem(t),e)),o=n=>i?renderToBlock(drawJoin(i,null,t[n],{index:n}),e):EMPTY_BLOCK,s=n=>i?renderToBlock(drawJoin(i,t[n],null,{index:n+1}),e):EMPTY_BLOCK,c=(n,r)=>i?renderToBlock(drawJoin(i,t[n],t[r],{index:r}),e):EMPTY_BLOCK,l=[],u=null,d=r>0?{segments:[new Segment(` `.repeat(r))],width:r}:EMPTY_BLOCK;for(let e=0;e<t.length;e++){let t=a[e];if(u===null){let n=o(e),r=s(e),i=n.width>0?[n,t]:[t],a=[i.length-1];u={blocks:i,width:n.width+t.width,lastIndex:e,itemBlockIndices:a},u.endCap=r;continue}let i=u.lastIndex,f=c(i,e),p=s(e),m=(r>0?r:0)+f.width+(r>0?r:0)+t.width;if(u.width+m+p.width<=n)r>0&&u.blocks.push(d),f.width>0&&u.blocks.push(f),r>0&&u.blocks.push(d),u.blocks.push(t),u.itemBlockIndices.push(u.blocks.length-1),u.width+=m,u.lastIndex=e,u.endCap=p;else{let n=u.endCap;n.width>0&&u.blocks.push(n),u.width+=n.width,l.push(u);let r=o(e),i=s(e),a=r.width>0?[r,t]:[t],c=[a.length-1];u={blocks:a,width:r.width+t.width,lastIndex:e,itemBlockIndices:c},u.endCap=i}}let f=u;{let e=f.endCap;e.width>0&&f.blocks.push(e),f.width+=e.width,l.push(f)}let p=this.align;for(let e=0;e<l.length;e++){let t=l[e],r=e===l.length-1,i=Math.max(0,n-t.width),a=computePadLeft(p,i),o=computeSlotFills(p,r,i,t.itemBlockIndices.length),s=new Map;t.itemBlockIndices.forEach((e,t)=>s.set(e,t)),a>0&&(yield new Segment(` `.repeat(a)));for(let e=0;e<t.blocks.length;e++){let n=s.get(e);if(n!==void 0&&n>0){let e=o[n-1];e>0&&(yield new Segment(` `.repeat(e)))}yield*t.blocks[e].segments}yield Segment.line()}}measure(e){let t=this.items;if(t.length===0)return{minimum:0,maximum:0};let n=0,r=0;for(let i=0;i<t.length;i++){let a=renderToBlock(t[i],e).width,o=this.joiner?renderToBlock(drawJoin(this.joiner,null,t[i],{index:i}),e).width:0,s=this.joiner?renderToBlock(drawJoin(this.joiner,t[i],null,{index:i+1}),e).width:0;n=Math.max(n,a+o+s),r+=a,i>0&&(r+=this.gap*2,this.joiner&&(r+=renderToBlock(drawJoin(this.joiner,t[i-1],t[i],{index:i}),e).width))}return this.joiner&&(r+=renderToBlock(drawJoin(this.joiner,null,t[0],{index:0}),e).width,r+=renderToBlock(drawJoin(this.joiner,t[t.length-1],null,{index:t.length}),e).width),{minimum:n,maximum:r}}};const DIAGNOSTIC_ERROR_COLORS={fg:`#ffffff`,bg:`#c82828`},DIAGNOSTIC_WARNING_COLORS={fg:`#000000`,bg:`#dca028`},DIAGNOSTIC_INFO_COLORS={fg:`#ffffff`,bg:`#2f6db5`},ANSI_RESET=`\x1B[0m`;function sgrOf(e,t){return`\x1b[${e};2;${[1,3,5].map(e=>Number.parseInt(t.slice(e,e+2),16)).join(`;`)}m`}const DIAGNOSTIC_ERROR_FG=sgrOf(38,DIAGNOSTIC_ERROR_COLORS.fg),DIAGNOSTIC_ERROR_BG=sgrOf(48,DIAGNOSTIC_ERROR_COLORS.bg),ELLIPSIS=`…`,NEUTRALIZED_RANGES=[[0,31],[127,159],[8234,8238],[8294,8303]];function isControlChar(e){return NEUTRALIZED_RANGES.some(([t,n])=>e>=t&&e<=n)}function sanitizeText(e){let t=``;for(let n of e)t+=isControlChar(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function sanitizeAndTruncate(e,t){let n=sanitizeText(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,ELLIPSIS);r+=e,i++}return r}const OPEN=`${DIAGNOSTIC_ERROR_BG}${DIAGNOSTIC_ERROR_FG}`,PREFIX=`⚠ cc-candybar: `,MAX_MESSAGE_LEN=60;function permanentGlyphText(e){return`${PREFIX}${describe$2(e)}`}function formatPermanentGlyph(e){return`${OPEN}${permanentGlyphText(e)}${ANSI_RESET}\n`}function describe$2(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: ${sanitizeAndTruncate(e.message,MAX_MESSAGE_LEN)}`;case`render_failed`:return`render failed: ${sanitizeAndTruncate(e.message,MAX_MESSAGE_LEN)}`;case`switched_off`:return`switched off: ${sanitizeAndTruncate(e.message,MAX_MESSAGE_LEN)}`;case`malformed_response`:return`malformed daemon response: ${sanitizeAndTruncate(e.message,MAX_MESSAGE_LEN)}`}}function parseFrame(e){return{...e,nextChange:e.nextChange??1/0}}function standIn$1(e,t){return{depth:e.depth,rows:t,nextChange:1/0,motion:e.motion===`still`?`still`:`can-move`,pending:[]}}function diagnosticFrame(e,t){return{depth:`truecolor`,rows:[{kind:`diagnostic`,runs:[{text:sanitizeText(e),...t}]}],nextChange:1/0,motion:`still`,pending:[]}}function renderFailedFrame(e){return diagnosticFrame(permanentGlyphText({kind:`permanent`,cause:`render_failed`,message:e}),DIAGNOSTIC_ERROR_COLORS)}function laneEncoded(e,t){try{return e(t)}catch(t){return e(diagnosticFrame(`⚠ cc-candybar ${t instanceof Error?t.message:String(t)}`,DIAGNOSTIC_ERROR_COLORS))}}function drawnColor(e){return e.type===ColorDepth.TRUECOLOR?e.value.hex:e.number===void 0?e.name:`color(${e.number})`}const ATTRIBUTES$2=Object.keys(new Style().attributes);function lookOf(e,t){let{color:n,bgcolor:r}=e.drawnColors(t),i=ATTRIBUTES$2.filter(t=>e[t]===!0);return{...n!==void 0&&{fg:drawnColor(n)},...r!==void 0&&{bg:drawnColor(r)},...i.length>0&&{attrs:i}}}function runOf$2({text:e,style:t},n){return{text:e,...t!==void 0&&n!==null&&lookOf(t,n),...t?.link!==void 0&&{link:t.link}}}function runLines(e,t){let n=e.filter(e=>!e.isControl&&e.text.length>0);return Segment.splitLines(n).map(e=>e.map(e=>runOf$2(e,t)))}function segmentOf({text:e,fg:t,bg:n,attrs:r=[],link:i}){return new Segment(e,new Style({color:t,bgcolor:n,link:i,...Object.fromEntries(r.map(e=>[e,!0]))}))}function encodeAnsi(e,t){let n=resolveDestination(t);return e.map(e=>segmentsToString(e.map(segmentOf),n)).join(`
|
|
57
57
|
`)}function ansiOf(e){return encodeAnsi(e.rows.map(e=>e.runs),e.depth)}function composeBar(e){return ansiOf(e)+`
|
|
58
|
-
`}const sameLook$1=(e,t)=>e.fg===t.fg&&e.bg===t.bg&&e.link===t.link&&e.attrs?.join()===t.attrs?.join();function mergedRuns({runs:e}){let t=[];for(let n of e){let e=t.at(-1);e!==void 0&&sameLook$1(e,n)?t[t.length-1]={...e,text:e.text+n.text}:t.push(n)}return t}function plainOf(e){return e.map(e=>e.text).join(``)}const failedWith=e=>({ok:!1,error:e,code:`RENDER_FAILED`,daemonV:3}),renderFailed=e=>failedWith(failureOf(e).message),renderFailure=e=>({...e,kind:`threw`}),RENDER_ANSWERS={ansi:e=>({ok:!0,output:composeBar(e)}),frame:e=>({ok:!0,frame:e})};function holdsGit(e){return fs.existsSync(path.join(e,`.git`))}function gitRootOf(e){let t=path.resolve(e);for(;;){if(holdsGit(t))return t;let e=path.dirname(t);if(e===t)return;t=e}}function checkoutOf(e){let t=gitRootOf(e);return t===void 0?{root:path.resolve(e),git:!1}:{root:t,git:!0}}function probe(e){try{return ok$1(e())}catch(e){return e.code===`ENOENT`?ABSENT$2:failed$2(e.message,`read`)}}const realDir=e=>probe(()=>fs.realpathSync.native(e)),why=(e,t)=>t.kind===`absent`?`${e} is not there`:t.reason;function gitDirNamed(e){let t=probe(()=>fs.readFileSync(path.join(e,`.git`),`utf-8`));if(t.kind!==`ok`)return t;let n=t.value.match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();return n===void 0?failed$2(`${path.join(e,`.git`)} names no gitdir`,`parse`):ok$1(path.resolve(e,n))}function commonDirOf(e){let t=probe(()=>fs.readFileSync(path.join(e,`commondir`),`utf-8`));if(t.kind!==`ok`)return t;let n=t.value.trim();return n===``?failed$2(`${path.join(e,`commondir`)} is empty`,`parse`):ok$1(path.resolve(e,n))}const UNLINKED={kind:`unlinked`},unproven=e=>({kind:`unproven`,reason:e});function worktreeLink(e){let t=gitRootOf(e);if(t===void 0)return UNLINKED;let n=path.join(t,`.git`),r=probe(()=>fs.statSync(n));if(r.kind===`ok`&&r.value.isDirectory())return UNLINKED;let i=probe(()=>fs.lstatSync(n));if(i.kind!==`ok`)return unproven(why(n,i));if(!i.value.isFile())return unproven(`${n} is not a file`);let a=gitDirNamed(t);if(a.kind!==`ok`)return unproven(why(n,a));let o=realDir(a.value);if(o.kind!==`ok`)return unproven(why(a.value,o));let s=commonDirOf(o.value);if(s.kind===`absent`)return UNLINKED;if(s.kind===`failed`)return unproven(s.reason);let c=realDir(s.value);if(c.kind!==`ok`)return unproven(why(s.value,c));if(path.dirname(o.value)!==path.join(c.value,`worktrees`))return unproven(`${o.value} is not a worktree of ${c.value}`);let l=path.join(o.value,`gitdir`),u=probe(()=>fs.readFileSync(l,`utf-8`));if(u.kind!==`ok`)return unproven(why(l,u));let d=path.resolve(o.value,u.value.trim()),f=realDir(path.dirname(d));if(path.basename(d)!==`.git`||f.kind!==`ok`||f.value!==t)return unproven(`${o.value} is the worktree at ${d}, not ${t}`);let p=path.basename(c.value)===`.git`?path.dirname(c.value):c.value;return{kind:`linked`,main:path.join(p,path.relative(t,e))}}function checkoutLocation(e){let t=realDir(e),n=t.kind===`ok`?t.value:path.resolve(e),r=gitRootOf(n);if(r===void 0)return{main:``,worktree:``,subpath:``,noRepo:!0};let i=path.relative(r,n),a=i===``?``:`/${i.split(path.sep).join(`/`)}`,o=worktreeLink(n);return o.kind===`linked`?{main:path.resolve(o.main,path.relative(n,r)),worktree:path.basename(r),subpath:a,noRepo:!1}:{main:r,worktree:``,subpath:a,noRepo:!1}}function noteFacts(e,t){for(let n of Object.entries(t))e.push(n)}const LEVEL={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`,down:`warn`};function detailOf(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.message]];case`threw`:return[[`error`,e.detail]];case`closing`:return[[`closing`,e.message]];case`abandoned`:return[[`abandoned`,`1`]];case`down`:return[[`down`,e.message]]}}function requestEvent(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...detailOf(n)];return{level:LEVEL[n.kind],line:eventLine(e,i)}}const NOTHING_TO_SETTLE=e=>{};function failed$1(e,t,n=``){return{outcome:renderFailure(t),resp:failedWith(`renderer ${e.name}: ${n}${t.message}`),seen:`failed`,settled:NOTHING_TO_SETTLE}}function located(e){let t=e.hookData.workspace?.current_dir??e.cwd;return{...e,hookData:{...e.hookData,...t!==void 0&&path.isAbsolute(t)&&{location:checkoutLocation(t)}}}}function recorded(e,t){e.push(...t.record)}async function answerStatusline(e,t,n,r,i,a,o,s,c,l){let u=located(a),d=(t,n)=>void e.deliver({kind:`event`,at:instantAt(i),event:{kind:`effect-done`,session:t.session,of:t.id,outcome:n===null?{kind:`ok`}:{kind:`failed`,reason:n}}},[[`effect`,String(t.id)]]),f=t.requested(u),p=await e.answer({kind:`event`,at:s,event:{kind:`config`,context:u,worldState:f}});if(recorded(l,p),p.kind===`threw`)return noteFacts(l,{renderer:e.name}),failed$1(e,p.failure,`its config turn: `);let m=await e.answer({kind:`event`,at:s,event:{kind:`request`,id:o,context:u,waitMs:c-i.monotonic(),idleSince:n.since(u.hookData.session_id,s)??null,following:[...r.following(u.hookData.session_id)],feeds:r.feedsOf(u.hookData.session_id,s)}});recorded(l,m),noteFacts(l,{hop:p.hopMs===null||m.hopMs===null?`-`:`${p.hopMs+m.hopMs}ms`});let{effects:h}=m;noteFacts(l,{renderer:e.name,effects:h.map(e=>e.kind===`present`?`present:${e.surface}`:e.kind).join(`,`)||`-`});let g=null;for(let e of h)switch(e.kind){case`present`:m.kind===`threw`?d(e,`its turn threw`):e.request===o?g===null?g=e:d(e,`a second statusline frame for request ${o}`):d(e,`presents request ${e.request}, not this turn's ${o}`);break;case`change`:break}if(m.kind===`threw`)return failed$1(e,m.failure);if(g===null)return failed$1(e,failureOf(Error(`presented no statusline frame for request ${o}`)));let _=g,v=i.monotonic(),y;try{y=RENDER_ANSWERS[u.encoding](parseFrame(_.frame))}catch(t){let n=failureOf(t);return d(_,`encoding its frame threw: ${n.message}`),failed$1(e,n,`its frame could not be encoded: `)}return noteFacts(l,{encoded:`${elapsedMs(i,v)}ms`}),{outcome:{kind:`ok`},resp:y,seen:_.frame.motion,settled:e=>d(_,e?null:`the client did not take the answer`)}}function expandHome(e,t){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?t+e.slice(1):e}function resolveUserPath(e,t,n){return path.resolve(e,expandHome(t,n))}function explicitConfigPath(e,t,n){return typeof t==`string`&&t!==``?resolveUserPath(e,t,n):void 0}const CONFIG_ENV=`CC_CANDYBAR_CONFIG`;function detectConfigEnv({env:e,home:t},n){return explicitConfigPath(n,e[CONFIG_ENV],t)}function requestedConfigTarget(e,t){return e===void 0?t===void 0?{source:`search`}:{source:`environment`,path:t}:{source:`argument`,path:e}}function cliConfigTarget(e,t,n){return requestedConfigTarget(explicitConfigPath(n,e,t.home),detectConfigEnv(t,n))}function chainName(e,t=`bundled default (no config file loaded)`){return e.join(` < `)||t}const KNOWN_TOP_LEVEL=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`]),REQUIRED_FIELDS=[[`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`]],OPTIONAL_FIELDS=[[`workspace.added_dirs`,`string-list`]];function validateHookData(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of REQUIRED_FIELDS){let i=resolvePath$1(n,e);if(i==null)t.missingRequired.push(e);else{let n=kindOf(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of OPTIONAL_FIELDS){let i=resolvePath$1(n,e),a=i===void 0?r:listKind(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))KNOWN_TOP_LEVEL.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function kindOf(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function listKind(e){return Array.isArray(e)&&e.every(e=>kindOf(e)===`string`)?`string-list`:kindOf(e)}function resolvePath$1(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 answeredOf(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const SIGHTING_ROLES=[`statusline`,`frames`],roleOf=e=>e?.kind===`frames`?`frames`:`statusline`,DRAWN_MOTIONS=[`moves`,`can-move`,`still`],RATE_LIMITS_SEEN=[`carried`,`missing`,`unanswered`],FRAMES_SEEN=[...DRAWN_MOTIONS,`failed`,`drawing`];function rateLimitsSeen(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:answeredOf(e)===`no`?`unanswered`:`missing`}function transcriptSaid(e){return{path:e.transcript_path,answered:answeredOf(e)===`yes`}}var RenderSightings=class{seen=new Map;see(e,t,n,r){let i=roleOf(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)}};function parseRenderArgs(e,t,n){let{tokens:r}=parseArgs({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),i=(r??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),a=(r??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===i&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:explicitConfigPath(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function parseRenderEncoding(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=RENDER_ENCODINGS.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${RENDER_ENCODINGS.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function checkRenderRequest(e,t,n,r){let{report:i}=validateHookData(e.hookData),a=[];for(let e of i.missingRequired)a.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of i.typeMismatches)a.push(`field '${e}' expected ${t}, got ${n}`);let o=parseSessionId(e.hookData?.session_id);o.ok||a.push(`field 'session_id' ${o.problem}`),(typeof e.cwd!=`string`||!isAbsolute(e.cwd))&&a.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&a.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let s=parseRenderEncoding(e.encoding);s.ok||a.push(s.problem);let c=parseClientDeadline(e.deadline);if(c.kind===`refused`)return{ok:!1,problems:[...a,c.problem]};if(a.length>0||!o.ok||!s.ok)return{ok:!1,problems:a};for(let e of i.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let l=parseClientHints(e),{configFile:u,refusedArgs:d}=parseRenderArgs(e.args,e.cwd,r);return{ok:!0,req:{...e,hookData:{...e.hookData,session_id:o.id},deadline:c,encoding:s.encoding,hints:l,rateLimits:rateLimitsSeen(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:requestedConfigTarget(u,l.configEnv)},refusedArgs:d}}}const CLICK_PROGRAM_TIMEOUT_MS=5e3,clickLaunchVia=e=>t=>e.launch({...t,args:t.args?.slice(),timeoutMs:CLICK_PROGRAM_TIMEOUT_MS});async function clickLaunch(e,t,n,r){let i=await e(t);if(i.ok)return{outcome:{kind:`ok`},said:r};let a=clickFailed(i,n);return{outcome:{kind:`skipped`,reason:a},said:a}}function clickFailed(e,t){if(e.reason===`rate-limited`)return`${t} not run: ${failureText(e)}`;throw e.reason===`aborted`?new DaemonClosing(t):Error(`${t} failed (${failureText(e)})`)}const HANDOFF_POLL_MS=50;async function clickHandoff(e,t,n,r,i,a){let o=mkdtempSync(path.join(a,`cc-candybar-handoff-`));try{let a={stdout:`/dev/null`,stderr:path.join(o,`stderr`),status:path.join(o,`status`)},s=e.launchJobSync(t,a);if(!s.ok){r(`warn`,clickFailed({...s,stdout:``,stderr:``,exitCode:null,signal:null},n));return}s.release();let c=e.clock.monotonic()+i;for(;;){let o=e.jobGroupAlive(s.pid),l=readJobEnd(a.status);if(l!==null){if(l.kind===`exit`&&l.code===0)return;clickFailed(l.kind===`exit`?{ok:!1,reason:`non-zero`,stdout:``,stderr:readFileSync(a.stderr,`utf8`),exitCode:l.code,signal:null}:{ok:!1,reason:`timeout`,stdout:``,stderr:``,exitCode:null,signal:null},n);return}if(!o)throw Error(`${n} failed (lost): the opener ended with no verdict`);if(e.clock.monotonic()>=c){r(`info`,`${t.category} handed off at ${i}ms, pid ${s.pid}`);return}await sleep(e.clock,HANDOFF_POLL_MS)}}finally{rmSync(o,{recursive:!0,force:!0,maxRetries:3})}}const LINK_KEY_BYTES=32,MAC_SPELLING=/^[0-9a-f]{64}$/,LINK_MAC_BYTES=16,LINK_MAC_SPELLING=/^[A-Za-z0-9_-]{22}$/,LINK_MAC_MARK=`#`;function transitForm(e){return e.toWellFormed().replace(/%(?![0-9A-Fa-f]{2})|[^A-Za-z0-9\-._~!$&'()*+,;=:@/?%]/gu,encodeURIComponent)}function unprovenLink(e){let t=isBarLink(e)?e.lastIndexOf(LINK_MAC_MARK):-1;return t===-1?e:e.slice(0,t)}function linkMac(e,t){return Buffer.from(createHmac(`sha256`,e).update(t).digest().subarray(0,LINK_MAC_BYTES)).toString(`base64`).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replace(/=+$/,``)}function signLinkWith(e,t){let n=transitForm(t);return`${n}${LINK_MAC_MARK}${linkMac(e,n)}`}function openLinkWith(e,t){let n=t.lastIndexOf(LINK_MAC_MARK);if(n===-1)return{kind:`failed`,reason:`the link carries no signature: the bar did not draw it, or drew it before its links were signed`};let r=t.slice(0,n),i=t.slice(n+1);return LINK_MAC_SPELLING.test(i)&&timingSafeEqual(Buffer.from(i),Buffer.from(linkMac(e,r)))?{kind:`ok`,value:r}:{kind:`failed`,reason:`the link's signature does not match what it carries: it was changed after the bar drew it, or another key signed it`}}function digest(e,t){return createHmac(`sha256`,e).update(JSON.stringify([t.sessionId,t.action,t.declaration,t.evaluated])).digest()}function linkSigner(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);let t=new Map;return{sign:t=>digest(e,t).toString(`hex`),verify:(t,n)=>MAC_SPELLING.test(n)?timingSafeEqual(Buffer.from(n,`hex`),digest(e,t)):!1,signLink:n=>{let r=t.get(n);return r===void 0&&(t.size>=SIGNED_LINKS_HELD&&t.clear(),r=signLinkWith(e,n),t.set(n,r)),r},openLink:t=>openLinkWith(e,t)}}const SIGNED_LINKS_HELD=1024;function linkSignerOver(e){let t,n=()=>{let n=e();return n.kind===`ok`?{kind:`ok`,value:t??=linkSigner(n.value)}:n},r=()=>{let e=n();if(e.kind===`failed`)throw Error(e.reason);return e.value};return{sign:e=>r().sign(e),verify:(e,t)=>r().verify(e,t),signLink:e=>r().signLink(e),openLink:e=>{let t=n();return t.kind===`ok`?t.value.openLink(e):t}}}let preview;function previewSigner(){return preview??=linkSigner(randomBytes(32))}function signingFrames(e){let t=t=>isBarLink(t)?e.signLink(t):t;return e=>({...e,rows:e.rows.map(e=>({...e,runs:e.runs.map(e=>e.link===void 0?e:{...e,link:t(e.link)})}))})}const TMUX_ENV={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`},inTmux=e=>e!=null;function detectTmuxHint(e){let t=e[TMUX_ENV.socket]??``,n=e[TMUX_ENV.pane]??``;if(t===``||n===``)return null;let r=e[TMUX_ENV.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const RENDERERS$1=[`claude`,`tmux`],IN_TMUX=`ne .tmux.pane ""`,LANES={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}},LANE_NAMES=Object.keys(LANES),TOGGLED_LANES=LANE_NAMES.filter(e=>LANES[e].switch.on===!0),ANSWERING={by:`request`},DRAWING_VAR=`drawing`,drawingVar=e=>`${DRAWING_VAR}.${e}`,UNFOLLOWED={subscribers:0,fps:0,shown:!0},laneFeedVar=(e,t)=>`feeds.${e}.${t}`;function perLane(e){return Object.fromEntries(LANE_NAMES.map(t=>[t,e(t)]))}const UNFOLLOWED_FEEDS=perLane(()=>UNFOLLOWED);function parseLane(e){return typeof e==`string`&&Object.hasOwn(LANES,e)?e:null}function feedsFact(e){return LANE_NAMES.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(`,`)||`-`}const RENDER_THEME=new Theme({"strip.separator":`default`,"strip.rail":`default`});function resolvedStyle(e){return RENDER_THEME.resolve(e)}function memoPerPalette(){let e=new WeakMap;return(t,n,r)=>{let i=e.get(t);i===void 0&&(i=new Map,e.set(t,i));let a=i.get(n);if(a!==void 0)return a;let o=r();return i.set(n,o),o}}const is=(e,t)=>e===t;function sameBy(e){let t=Object.keys(e);return(n,r)=>t.every(t=>e[t](n[t],r[t]))}const sameEach=e=>(t,n)=>t.length===n.length&&t.every((t,r)=>e(t,n[r])),DECOR_HUES=[`primary`,`secondary`,`accent`],LADDER=[`darken-3`,`darken-2`,`darken-1`,`base`,`lighten-1`,`lighten-2`,`lighten-3`],SHADE_SUFFIX={"darken-3":`-darken-3`,"darken-2":`-darken-2`,"darken-1":`-darken-1`,base:``,"lighten-1":`-lighten-1`,"lighten-2":`-lighten-2`,"lighten-3":`-lighten-3`,muted:`-muted`},shadeRole=(e,t)=>`${e}${SHADE_SUFFIX[t]}`,poleText=(e,t,n,r)=>textOn(e,n,r),roleText=(e,t,n,r)=>legibleOn(e,e.get(`text-${t}`),n,r),ladderWindow=e=>({tones:[LADDER[e],LADDER[e+2],LADDER[e+1]],text:poleText,activated:`muted`}),centredWindow=e=>({tones:[LADDER[3-e],LADDER[3+e],LADDER[3]],text:poleText,activated:`muted`}),pairWindow=e=>({tones:[LADDER[3-e],LADDER[3+e]],text:poleText,activated:`muted`}),TRIAL_SHADES={wide:centredWindow(2),widest:centredWindow(3),pair:pairWindow(2),"pair-wide":pairWindow(3)},TRIAL_SHADE_NAMES=Object.keys(TRIAL_SHADES),SHADES={muted:{tones:[`muted`,`base`],text:roleText,activated:`lighten-2`},deepest:ladderWindow(0),deeper:ladderWindow(1),middle:ladderWindow(2),brighter:ladderWindow(3),brightest:ladderWindow(4),...TRIAL_SHADES},lineageHue=(e,t)=>e[t%e.length],KEYSTONE_HUE=`accent`,WHOLE_ROW=1/0,OPENS_TODAY={keystones:[],open:[`accent`,`primary`,`secondary`]},KEYSTONE_PLACEMENTS={door:[`bar-start`],start:[`line-start`],end:[`line-end`],ends:[`line-start`,`line-end`]},OPEN_LINEAGES={primary:[`primary`],secondary:[`secondary`],alternate:[`primary`,`secondary`]};function tunings(){let e=Object.entries(KEYSTONE_PLACEMENTS).flatMap(([e,t])=>Object.entries(OPEN_LINEAGES).map(([n,r])=>[`${e}-${n}`,{hues:[`secondary`],run:WHOLE_ROW,keystones:t,open:r}]));return Object.fromEntries(e)}const TUNINGS=tunings(),VARIATIONS={accent:{hues:[`secondary`,`accent`],run:WHOLE_ROW,...OPENS_TODAY},duo:{hues:[`primary`,`secondary`],run:WHOLE_ROW,...OPENS_TODAY},mono:{hues:[`primary`],run:WHOLE_ROW,...OPENS_TODAY},alt:{hues:[`secondary`,`accent`],run:3,...OPENS_TODAY},...TUNINGS},TRIAL_VARIATION_NAMES=Object.keys(TUNINGS),vocabularyOf=(e,t,n)=>turnsHeld(e,t,t.variation.hues.flatMap(r=>{let i=windowAt(e,r,t.shade,n);return t.shade.tones.map((e,t)=>({hue:r,shade:i[t%i.length]}))}),n);function windowAt(e,t,n,r){return WINDOWS(e,`${t}|${n.tones.join(`,`)}|${r}`,()=>{let i=drawnIn(e,t,r),a=windowSize(n.tones.length,new Set(LADDER.map(i)).size),[o,...s]=n.tones,c=[o];for(let e of s)c.length<a&&c.every(t=>i(t)!==i(e))&&c.push(e);return inWalkOrder(Array.from({length:a-c.length}).reduce(a=>{let o=widen(e,t,n.tones,a.map(i),r);return o===void 0?a:[...a,o]},c))})}const inWalkOrder=e=>{if(e.length<3)return e;let t=LADDER,[n,...r]=[...e].sort((e,n)=>t.indexOf(e)-t.indexOf(n));return[n,r.at(-1),...r.slice(0,-1)]},windowSize=(e,t)=>Math.max(2,Math.min(e,t-1)),WINDOWS=memoPerPalette(),drawnIn=(e,t,n)=>r=>drawnColour(e.get(shadeRole(t,r)),n).hex;function widen(e,t,n,r,i){let a=drawnIn(e,t,i);return ladderFrom(n,e.dark).find(e=>!r.includes(a(e)))}function ladderFrom(e,t){let n=LADDER,r=e=>e===`muted`?t?-1:n.length:n.indexOf(e),i=t?1:-1;return LADDER.map((t,n)=>({rung:t,at:n,distance:Math.min(...e.map(e=>Math.abs(n-r(e))))})).filter(({distance:e})=>e>0).sort((e,t)=>e.distance-t.distance||(t.at-e.at)*i).map(({rung:e})=>e)}const inBin=(e,t)=>Math.floor(e*t),inHalves=(e,t)=>{let n=t-1;for(let t=e;t<.5&&n>0;t*=2)n--;return n},PHI=.6180339887498949,vanDerCorput=e=>{let t=0,n=.5;for(let r=e;r>0;r>>=1,n/=2)t+=n*(r&1);return t},DISTRIBUTION_NAMES=[`van-der-corput`,`golden-angle`,`ends-interleaved`,`monotonic`,`uniform`],isDistributionName=e=>typeof e==`string`&&DISTRIBUTION_NAMES.includes(e),DISTRIBUTIONS={"van-der-corput":{place:vanDerCorput,quantize:inHalves},"golden-angle":{place:e=>e*PHI%1,quantize:inBin},"ends-interleaved":{place:(e,t)=>((e%2==0?e/2:t-1-(e-1)/2)+.5)/t,quantize:inBin},monotonic:{place:(e,t)=>(e+.5)/t,quantize:inBin},uniform:{place:()=>.5,quantize:inHalves}},DEFAULT_DISTRIBUTION=`van-der-corput`,placedBy=e=>DISTRIBUTIONS[e??`van-der-corput`];function entryOf$1(e,t){if(e===void 0)return 0;let{place:n,quantize:r}=e.distribution;return r(n(e.index,e.count),t)}function vocabularySelect(e,t){let n=e[entryOf$1(t,e.length)];if(n===void 0)throw Error(`vocabularySelect: empty vocabulary`);return n}function rowAndCell(e){let t=e=>e.axis===`cell`,n=e.findIndex(t);return{row:(n===-1?e:e.slice(0,n)).at(-1),cell:e.findLast(t)}}const rowStart=(e,t)=>entryOf$1(t,e.hues.length);function decorEntryFor(e,t,n,r){let{row:i,cell:a}=rowAndCell(n);return a===void 0?dealtAt(e,t,i,a,r):lineAt(e,t,i,a,r)[a.index-a.lineStart]}function dealtAt(e,t,n,r,i){let{hues:a,run:o,keystones:s}=t.variation,c=r===void 0?0:Math.floor(r.index/o),l=a[(rowStart(t.variation,n)+c)%a.length];if(l===void 0)throw Error(`decorEntryFor: empty variation`);let u=s.some(e=>KEYSTONE_AT[e](n,r))?KEYSTONE_HUE:l;return{hue:u,shade:vocabularySelect(windowAt(e,u,t.shade,i),r)}}function lineAt(e,t,n,r,i){let{hues:a,run:o,keystones:s,open:c}=t.variation;return LINES(e,[a.join(`,`),o,s.join(`,`),c.join(`,`),t.shade.tones.join(`,`),t.shade.activated,n===void 0?``:stepKey(n),stepKey(r,r.lineStart),i].join(`|`),()=>turnsHeld(e,t,Array.from({length:r.lineEnd-r.lineStart+1},(a,o)=>dealtAt(e,t,n,{...r,index:r.lineStart+o},i)),i))}const LINES=memoPerPalette();function stepKey({axis:e,index:t,count:n,distribution:r,lineStart:i,lineEnd:a,...o},s=t){return`${e},${s},${n},${distributionName(r)},${i},${a}`}function distributionName(e){let t=DISTRIBUTION_NAME.get(e);if(t===void 0)throw Error(`decorEntryFor: a cell placed outside DISTRIBUTIONS`);return t}const DISTRIBUTION_NAME=new Map(DISTRIBUTION_NAMES.map(e=>[DISTRIBUTIONS[e],e]));function turnsHeld(e,t,n,r){let i=[...n],a=t=>{let n=i[t];return n&&drawnIn(e,n.hue,r)(n.shade)},o=drawnPress(e,{decor:t,depth:0},r),s=(n,o)=>{let{hue:s}=i[n],c=[a(n-1),a(n+1),...o].filter(e=>e!==void 0),l=windowAt(e,s,t.shade,r),u=l.find(t=>!c.includes(drawnIn(e,s,r)(t)))??widen(e,s,l,c,r);return u===void 0?void 0:{hue:s,shade:u}},c=e=>[[o],[]].flatMap(t=>[e,e-1].map(e=>({place:e,off:t})));for(let e=1;e<i.length;e++)if(!(i[e-1].hue===i[e].hue||a(e-1)!==a(e)))for(let{place:t,off:n}of c(e)){let e=s(t,n);if(e!==void 0){i[t]=e;break}}return i}const KEYSTONE_AT={"bar-start":(e,t)=>(e?.index??0)===0&&(t?.index??0)===0,"line-start":(e,t)=>t===void 0||t.index===t.lineStart,"line-end":(e,t)=>t===void 0||t.index===t.lineEnd},PLANE_ROLE=`surface`,decorEntryColour=(e,t)=>e.get(shadeRole(t.hue,t.shade)),TEXT_MIN_CONTRAST=4.5;function textOn(e,t,n){return POLE_TEXT(e,`${t.hex}|${n}`,()=>{let r=contrastFor(t);return legibleOn(e,[`background`,`foreground`].map(t=>e.get(t)).reduce((e,t)=>contrastRatio(r,t)<contrastRatio(r,e)?t:e),t,n)})}const POLE_TEXT=memoPerPalette();function legibleOn(e,t,n,r){return LEGIBLE(e,`${t.hex}|${n.hex}|${r}`,()=>ensureContrast(t,n,TEXT_MIN_CONTRAST,r))}const LEGIBLE=memoPerPalette(),hueOf=({decor:e,depth:t})=>lineageHue(e.variation.open,t),bandEntries=(e,t,n)=>windowAt(e,hueOf(t),t.decor.shade,n).map(e=>({hue:hueOf(t),shade:e}));function pressedAt(e,t,n){let{decor:r,depth:i}=t,{variation:a,shade:o}=r;return PRESSED(e,[i,a.open.join(`,`),a.hues.join(`,`),a.keystones.length,o.tones.join(`,`),o.activated,n].join(`|`),()=>{let s=hueOf(t),c=t=>windowAt(e,t,o,n).map(drawnIn(e,t,n)),l=a.keystones.length>0?[KEYSTONE_HUE]:[],u=i===0?[...a.hues,...l].flatMap(c):(t=>[...c(hueOf(t)),drawnPress(e,t,n)])({decor:r,depth:i-1}),d=[...c(s),...u];return d.includes(drawnIn(e,s,n)(o.activated))?widen(e,s,[o.activated],d,n)??o.activated:o.activated})}const PRESSED=memoPerPalette(),drawnPress=(e,t,n)=>drawnIn(e,hueOf(t),n)(pressedAt(e,t,n)),nestedIn=e=>({...e,depth:e.depth+1});function bandFor(e,t,n){return{state:e.get(shadeRole(hueOf(t),pressedAt(e,t,n))),plane:e.get(PLANE_ROLE),items:bandEntries(e,t,n).map(t=>decorEntryColour(e,t))}}function bandItemFor(e,t,n,r){return vocabularySelect(bandFor(e,t,r).items,n)}function bandItem(e,t,n,r){let i=bandItemFor(e,t,n,r);return{tint:i,text:t.decor.shade.text(e,hueOf(t),i,r)}}function sameRegion(e,t){switch(e.kind){case`bar`:return t.kind===`bar`&&sameBarRegion(e,t);case`band`:return t.kind===`band`&&sameBandRegion(e,t)}}const sameAddress=sameEach(sameBy({index:is,count:is,distribution:is,axis:is,lineStart:is,lineEnd:is})),sameDecor=sameBy({variation:is,shade:is}),sameDisclosure=sameBy({decor:sameDecor,depth:is}),sameBarRegion=sameBy({kind:is,decor:sameDecor,address:sameAddress}),sameBandRegion=sameBy({kind:is,band:sameDisclosure,address:sameAddress}),barRoot=e=>({kind:`bar`,decor:e,address:[]}),descend=(e,t)=>({...e,address:[...e.address,t]}),bandRoot=e=>({kind:`band`,band:e,address:[]});function decorationFor(e,t,n){switch(t.kind){case`bar`:{let{decor:r,address:i}=t,a=decorEntryFor(e,r,i,n),o=decorEntryColour(e,a);return{tint:o,text:r.shade.text(e,a.hue,o,n),disclosure:{decor:r,depth:0}}}case`band`:{let{band:r,address:i}=t;return{...bandItem(e,r,rowAndCell(i).cell,n),disclosure:nestedIn(r)}}}}const RETIRED_THEMES=new Map([[`dark`,`textual-dark`],[`light`,`textual-light`]]);function retiredThemeNote(e){let t=typeof e==`string`?RETIRED_THEMES.get(e):void 0;return t===void 0?``:` — "${e}" was retired; write "${t}", the same palette`}const THEME_FLOOR=`textual-dark`;function effectiveGlobal(e,t,n,r,i){let a=t===null?null:i(t);return e??a??n??r}function listResolvablePaletteNames(){return listThemePalettes()}const FOLLOW_BAR=`bar`;function placementThemeNames(){return[`bar`,...listResolvablePaletteNames()]}let placementThemeSet;function isPlacementThemeName(e){return placementThemeSet??=new Set(placementThemeNames()),placementThemeSet.has(e)}function effectiveMemberName(e,t,n,r,i){let a=e=>Object.prototype.hasOwnProperty.call(i,e)?e:null;return effectiveGlobal(e===void 0?null:a(e),t,a(n??r),r,a)}const EXPRESSION_SLOTS=[`style`,`palette`,`effect`];function isExpression(e){return e!==void 0&&e.includes(`{{`)}function resolveSelection(e,t,n,r,i){let a=isExpression(n)?{kind:`expression`,source:n}:i(n??r.name);return effectiveGlobal(e===void 0?null:i(e),t,a,r,i)}const STYLE_FLOOR=`none`;function namedStyle(e,t){let n=t[e];return n===void 0?null:{kind:`decided`,name:e,value:n}}function decideStyleName(e,t){return namedStyle(e,t)??namedStyle(`none`,t)??{kind:`decided`,name:`none`,value:IDENTITY}}function resolveStyleSelection(e,t,n,r){return resolveSelection(e,t,n,decideStyleName(STYLE_FLOOR,r),e=>namedStyle(e,r))}const EFFECT_FLOOR=`none`,SLOT_FLOORS={style:STYLE_FLOOR,palette:THEME_FLOOR,effect:EFFECT_FLOOR};function ruleFloorMessage(e,t,n){return`${e} rendered "${SLOT_FLOORS[t]}": ${n}`}const EFFECT_NAMES=Object.freeze([EFFECT_FLOOR,...Object.keys(EFFECT_CATALOGUE.loops)]),ANIMATION_SPEEDS=Object.freeze({"1x":1,"5x":5,"10x":10,"20x":20}),ANIMATION_SPEED_NAMES=Object.keys(ANIMATION_SPEEDS),PLACEMENT_EFFECTS=Object.freeze([`bar`,...EFFECT_NAMES]);function namedEffect(e){let t=EFFECT_NAMES.find(t=>t===e);return t===void 0?null:{kind:`decided`,name:e,value:t}}function decideEffectName(e){return namedEffect(e)??{kind:`decided`,name:`none`,value:`none`}}function resolveEffectSelection(e,t,n){return resolveSelection(e,t,n,decideEffectName(EFFECT_FLOOR),namedEffect)}const ENDCAPS_SHAPES=Object.freeze(Object.keys(JOINERS)),STYLE_ERA_ENDCAPS=[`powerline`,`capsule`,`plain`];function isStyleEraEndcaps(e){return STYLE_ERA_ENDCAPS.includes(e)}const COLOR_COMPATIBILITIES=[`truecolor`,`256`,`ansi`,`none`];function isColorCompatibility(e){return COLOR_COMPATIBILITIES.includes(e)}function drawnDepth(e){return resolveColorSystem(e)??ColorDepth.DEFAULT}const VARIATION_NAMES=Object.keys(VARIATIONS),SHADE_NAMES=Object.keys(SHADES),BOOLEAN_TRUE=`true`,BOOLEAN_FALSE=`false`,BOOLEAN_MEMBERS=[BOOLEAN_TRUE,BOOLEAN_FALSE],PADDING_RANGE={min:0,max:16};function parseSessionBoolean(e){return e===`true`?!0:e===`false`?!1:null}function parseSessionInt(e,t){let n=Number(e);return Number.isInteger(n)&&String(n)===e&&n>=t.min&&n<=t.max?n:null}const flashes=(e,t)=>Array.from({length:e*2},(e,n)=>({lit:n%2==0,seconds:t})),CLOSING_FLASH=[...flashes(3,1),...flashes(3,.25)],CLOSING_FLASH_SECONDS=CLOSING_FLASH.reduce((e,{seconds:t})=>e+t,0),MENU_TIMEOUT_RANGE={min:15,max:600,step:15},closesAt=(e,t)=>e+t,flashBegins=e=>e-CLOSING_FLASH_SECONDS,STILL={kind:`still`},animationAt=e=>Timeline.at(e.timeline,e.wall),BAR_SCOPE=Symbol(`bar`);function isMoving(e){return e.name!==EFFECT_FLOOR}function together(e){return t=>Animation.map(Animation.all(e.map(({timeline:e,effect:n})=>Timeline.run(e,n(t)))),e=>(t,n)=>e.reduce((e,t)=>t(e,n),t))}const ASSUMED_TERMINAL=DEFAULT_TERMINAL_THEME;function fromGround(e,t){let n=new TerminalTheme(t,ASSUMED_TERMINAL.foregroundColor,ASSUMED_TERMINAL.ansiColors,ASSUMED_TERMINAL.palette);return t=>e({...t,theme:n})}function paintedOn(e,t){return n=>confined(()=>e(n),...t)(n)}function noiseOffset(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 NOISE_DEPTH=4096;function closingFlash(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=CLOSING_FLASH.reduceRight((e,{lit:t,seconds:n})=>Animation.sequence(Animation.constant(t?r:i),n,e),Animation.constant(i)),o=Animation.sequence(Animation.constant(i),n,a);return()=>o}var SessionEffects=class{inForce=null;anchor=Timeline.play(0);placements=new Map;made=new Map;passages=null;frame={effect:EFFECT_FLOOR,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:Timeline.withRate(this.anchor,e,t)}}motion(e,t,n,r=null){let i=animationAt(t),a=e=>Timeline.seek(t.timeline,t.wall,e),o=this.inForce?.name===e?this.inForce:{name:e,since:i},s={scope:BAR_SCOPE,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=EFFECT_CATALOGUE.transitions[e]({z:noiseOffset(`${this.key}@${t}`)*NOISE_DEPTH});return{name:e,since:i,done:e=>r.done(e),effect:fromGround(r.effect,n)}},C=({since:e,done:t})=>t(i-e),w=(e,t,n)=>({drawing:t,passage:g===null?null:n===void 0||n.passage?.name===`dissolve`?S(`fade`,e,t):n.passage!==null&&!C(n.passage)?n.passage:null}),T=(e,t)=>{if(t===void 0||t.drawing.opened||t.drawing.own.length===0)return;if(t.passage?.name===`dissolve`)return C(t.passage)?void 0:t;let r={...t.drawing,own:t.drawing.own.map(n.hold)};return{drawing:r,passage:S(`dissolve`,e,r)}},E=(e,t)=>{if(_.has(e))throw Error(`placement "${e}" was reached twice in one frame`);_.add(e);let r=g?.(e),{drawing:a,deeper:o}=n.returned(e,t),s=a===null?T(e,r):w(e,a,r);return s===void 0?t:(s.passage!==null&&(v.set(e,s.passage),(s.passage.name===`fade`?y:b).push({placement:e,t:i-s.passage.since})),a===null?[...s.drawing.own,...o]:t)},D=(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}},O=(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=noiseOffset(t.scope===BAR_SCOPE?e:`${e}@${t.scope}`),s=a?i.effect:EFFECT_CATALOGUE.loops[t.name]({z:o*NOISE_DEPTH});return x[a?`reused`:`made`]++,n.set(t.scope,{name:t.name,effect:s}),s},k=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?s:D(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()]},A=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:confined(n.effect,...t)}]})},j=r===null?[]:[{timeline:Timeline.play(r.idleSince),effect:closingFlash(r.fill,r.text,flashBegins(r.timeoutS))}],M=e=>e===`menu`?j:[];return{placed:h===`off`?(e,t)=>t:E,row:(e,n,r)=>{let i=(r.some(e=>e.placement.effect!==`bar`)?k(r):[{...s,owners:void 0}]).filter(isMoving),o=A(r),c=M(n);if(i.length===0&&o.length===0&&c.length===0)return STILL;let l=`${this.key}#${e}`;return{kind:`moving`,time:t.wall,wrap:e=>new Effected(e,together([...i.map(e=>{let t=O(l,e);return{timeline:a(e.t),effect:e.owners===void 0?t:paintedOn(t,e.owners)}}),...o,...c]),{key:l,theme:ASSUMED_TERMINAL})}},drawn:()=>{this.anchor=t.timeline,this.inForce=o,this.placements=l,this.made=d,this.passages=h===`off`?null:v,this.frame=x}}}};const MAX_SESSIONS$5=256;var EffectSessions=class{sessions=new Map;constructor(e=MAX_SESSIONS$5){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new SessionEffects(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 UNBOUNDED_DRAW_WIDTH=80,ROW_HOST={};function draw(e,t){let n=resolveDestination(t.colorSystem),{time:r}=t,i=1/0,a=[...render(e,{maxWidth:t.width??UNBOUNDED_DRAW_WIDTH,isTerminal:!1,asciiOnly:!1,theme:RENDER_THEME,colorSystem:n.colorSystem,...r===void 0?{}:{frame:{time:r,host:ROW_HOST}},onStyleError:e=>{throw e},onHold:({nextChange:e})=>{i=Math.min(i,e)}})];return{lines:runLines(a,n.colorSystem),nextChange:Math.min(Segment.nextChange(a),i)}}const separatorJoiners=new Map;function plainWith(e){let t=separatorJoiners.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}=JOINERS.plain,a=new CellJoiner({glyph:n(r.glyph),ascii:r.ascii},i);return separatorJoiners.set(e,a),a}function pickJoiner(e,t){return e===`plain`&&t!==void 0?plainWith(t):JOINERS[e]}const geometryMemo=new Map;function stripGeometry(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=geometryMemo.get(t);if(n!==void 0)return n;let r=pickJoiner(e.endcaps,e.separator),i=e=>new RichText(`x`,{end:``,overflow:`ignore`,style:new Style({bgcolor:e})}),a=e=>{let{lines:t}=draw(new Strip(e,r),{colorSystem:null});return new RichText(plainOf(t.flat())).cellLength},o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return geometryMemo.set(t,s),s}function stripChromeCols(e){return stripGeometry(e).chrome}function stripSeamCols(e){return stripGeometry(e).seam}const PRIVATE_USE=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function privateGlyphsIn(e){return[...new Set(e.match(PRIVATE_USE)??[])].join(``)}function stripPrivateGlyphs(e){let t=pickJoiner(e.endcaps,e.separator),n=e=>new RichText(`x`,{end:``,style:new Style({bgcolor:e})}),{lines:r}=draw(new Strip([n(`#101010`),n(`#202020`)],t),{colorSystem:null});return privateGlyphsIn(plainOf(r.flat()))}function lineWidth(e){return e.wrap?e.width:1/0}function wrappedLines(e,t){return draw(new RichText(e,{overflow:`fold`,end:``}),{colorSystem:null,width:t}).lines.map(plainOf)}function drawStripCells(e,t,n=STILL){if(e.length===0)return{lines:[[]],nextChange:1/0};let r=pickJoiner(t.endcaps,t.separator),i=Number.isFinite(lineWidth(t)),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new FlexStrip([...e],{joiner:r}):new Strip([...e],r),s=n.kind===`still`?draw(o,a):draw(n.wrap(o),{...a,time:n.time});if(s.lines.length===0)throw Error(`drawStripCells: rich-js strip drew no line`);return s}function renderStripCells(e,t){return encodeAnsi(drawStripCells(e,t).lines,t.colorCompatibility)}const TERMINALS={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`}}},row=e=>TERMINALS[e];function isBundling(e){return row(e).glyphs.kind===`bundled`}function isConfigured(e){return row(e).glyphs.kind===`configured`}const terminalLabel=e=>row(e).label,ITERM_POWERLINE=[{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 itermDrawsItself(e,t){let n=t.codePointAt(0);return ITERM_POWERLINE.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&releasedSince(e,t)===!0)}const NAMES=Object.keys(TERMINALS);function release$1(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function releasedSince(e,t){let n=release$1(e),r=release$1(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 fromXtversion(e){for(let t of NAMES){let n=row(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 fromTerm(e){let t=NAMES.find(t=>row(t).term===e);return t===void 0?null:{name:t,version:null}}function identifyInTmux(e){let t=fromXtversion(e.termtype)??fromTerm(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 identifyFromEnv(e){let t=e.TERM_PROGRAM,n=NAMES.find(e=>row(e).program===t),r=n===void 0?fromTerm(e.TERM):{name:n,version:row(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 sightingOf(e){switch(e.kind){case`known`:return terminalLabel(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function identifiedAs(e){switch(e.kind){case`known`:return terminalLabel(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function linkSupport({name:e,version:t}){let n=row(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=releasedSince(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const LINK_TERMINALS=NAMES.filter(e=>row(e).links!==null).map(terminalLabel).join(`, `);function statusLineOf(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(!isJsonObject(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||!isJsonObject(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function envVarOf(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 UNWRITTEN_SCOPES=[`managed`,`project`],doctorWrites=e=>!UNWRITTEN_SCOPES.includes(e.scope),ENV_FIX_FILE={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:projectLocalSettingsFile(t.projectDir)}),user:e=>({scope:`user`,path:e})},GLYPH_MARKS=[`drawn`,`boxes`],TRANSCRIPT_WINDOW_BYTES=1024*1024,whoseWidth=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function describeFix(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 problemsVerdict(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const TMUX_TRUECOLOR_VAR=TMUX_ENV.truecolor;function ofTmuxClient(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 tmuxTruecolor={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>ofTmuxClient(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=envVarOf(t.sources,TMUX_TRUECOLOR_VAR);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:`${TMUX_TRUECOLOR_VAR} 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`,TMUX_TRUECOLOR_VAR],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=ENV_FIX_FILE[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 ${TMUX_TRUECOLOR_VAR} to "1" there`}:o(s)})},utf8={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>ofTmuxClient(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"})},termWidth={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:`${whoseWidth(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 ${whoseWidth(e.value.of)} measured`}},UNUSED={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},NAMED_BY={argument:`command argument`,environment:`$${CONFIG_ENV}`,unknown:`source unknown`};function judgedConfig({target:e,layers:t}){return e.source===`search`?t.length===0?chainName(t):`${chainName(t)} (searched)`:`${e.path} (${NAMED_BY[e.source]})`}function configProblems(e){switch(e.kind){case`failed`:{let t=[...e.error.split(`
|
|
59
|
-
`).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}" ${UNUSED[e]}`)]}}const config={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{let t=judgedConfig(e),n=problemsVerdict(configProblems(e));return n.ok?{ok:!0,note:t}:{...n,reason:`${t}: ${n.reason}`}}},REINSTALL="re-run `cc-candybar install`";function handlerAppProblems(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:// — ${REINSTALL}`];let{app:t,forwarder:n}=e.value;return n?[]:[`${t} opens cc-candybar://, but it is not the forwarder app \`cc-candybar install\` builds — ${REINSTALL}`]}const urlHandler={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.delivery.kind===`forwarder`?{ok:!0}:{ok:!1,reason:`the link was delivered by a click request (\`cc-candybar url-handle\`), not the forwarder app — ${REINSTALL}`};case`lost`:return problemsVerdict([...handlerAppProblems(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}`])}}},RECENT_CLIENT_S=300;function clientStanding({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 remedy(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${LANE_NAMES.join(`|`)}>\``:e.checkout===null?REINSTALL:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function installProblems(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 — ${remedy(e,`native`)}`];let{bundle:i,source:a}=clientStanding(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} — ${remedy(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 — ${remedy(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 noRenderOf=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)`},install={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`:`${noRenderOf(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:problemsVerdict([...new Set(i.flatMap(e=>installProblems(n,r,e)))])}};function unreadPostMortems({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||laterIdentity(e.identity,t.value.through)):[]}function otherDaemons(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const daemon={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`?otherDaemons(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return problemsVerdict([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=unreadPostMortems(e.value,n),u=problemsVerdict([...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 ${mb(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 ${mb(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&approachingLimit(o.charge.bytes,s)?[`the daemon holds ${chargeWords(o.charge)} of its ${mb(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}}}},CLICK_TO_SEE=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function drawsLinks(e,t){let n=sightingOf(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?linkSupport(e.terminal):{kind:`unknown`}}function linkProblems({identified:e,tmuxClient:t},n){let r=identifiedAs(e),i=drawsLinks(e,n),a=sightingOf(e)===null?CLICK_TO_SEE:`${CLICK_TO_SEE}, 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: ${LINK_TERMINALS}`];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 links={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 problemsVerdict(linkProblems(t,n))}}},EFFECT_REFRESH_INTERVAL=1,refreshedFrames=e=>e.filter(e=>e.role===`statusline`),effectRefresh={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})=>chainVerdict(e,barsSeen(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:unknownMotion(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:noRenderOf(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}}},barsSeen=e=>{let t=refreshedFrames(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, a placement with an effect of its own that is not drawn now, or a moving bar handed off to another lane, which comes back here when the handoff ends)`}: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`}},unknownMotion=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function chainVerdict(e,t){let n=statusLineOf(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 unknownMotion(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 doctorWrites(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 codePoints=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function terminalCalled(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return identifiedAs(e);case`bundling`:case`unread`:case`configured`:return[terminalLabel(e.name),e.version].filter(e=>e!==null).join(` `)}}function sightedIn(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return sightingOf(e);case`bundling`:case`unread`:return terminalLabel(e.name);case`configured`:{let t=terminalLabel(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 glyphSighting(e){let t=sightedIn(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${codePoints(e.glyphs)}`}}const NERD_FONT_CHECK=`nerdFont`,nerdFont={name:NERD_FONT_CHECK,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=glyphSighting(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=terminalCalled(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 ${codePoints(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=TERMINALS[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:releasedSince(i.version,e);if(t===!0)return{ok:!0};let n=terminalLabel(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 ${codePoints(n)} — set a Nerd Font as its font`)}}}};function named$1(e){return e.join(`, `)}function optOut(e){return`or set missingData: "ignore" on ${named$1(e)}`}function pullRequestProblems(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${named$1(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`?[`${named$1(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${optOut(t)}`]:[`${named$1(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${optOut(t)}`]}function rateLimitProblems(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${named$1(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${named$1(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`:`${named$1(n)}: ${noRenderOf(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`)?[`${named$1(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${named$1(n)}`]:[]}const segmentData={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>problemsVerdict([...pullRequestProblems(e.pullRequests),...rateLimitProblems(e.rateLimits,t)])};function transcriptProblems({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 ${TRANSCRIPT_WINDOW_BYTES/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const sessionData={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`:`${noRenderOf(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:problemsVerdict(e.value.flatMap(transcriptProblems))},CHECKS=[config,install,daemon,urlHandler,links,tmuxTruecolor,utf8,termWidth,effectRefresh,nerdFont,segmentData,sessionData],MARKED_CHECKS=CHECKS.filter(e=>e.takesMark);function runDoctor(e){return CHECKS.map(t=>({check:t,verdict:t.probe(e)}))}function checkByName(e){return CHECKS.find(t=>t.name===e)}const scopeOf$1=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},inScope=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),ownProject=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=inScope(e,t);return r===void 0?n:r.projectDir},barsOf=(e,t)=>inScope(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r})),NONCE=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function parseProbeNonce(e){return NONCE.test(e)?e:null}function clickArrived(e){switch(e.via){case`link`:return{kind:`arrived`,delivery:e.delivery};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}function sessionWidth(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}}}}function parseClick(e,t,n){if(e.startsWith(DOCTOR_PROBE_PREFIX)){let n=parseProbeNonce(e.slice(DOCTOR_PROBE_PREFIX.length));return n===null?{kind:`refused`,problem:`the probe link carries no probe nonce`}:{kind:`probe`,nonce:n,delivery:t}}if(e.startsWith(STATUS_LINE_CLICK_PREFIX))return t.kind===`cli`?{kind:`status-line`,value:e.slice(STATUS_LINE_CLICK_PREFIX.length)}:{kind:`refused`,problem:`a status-line click comes only from tmux's own binding`};if(!isBarLink(e))return{kind:`refused`,problem:`expected a ${URL_SCHEME$1}:// link, got: ${e}`};let r=openClick(e,n);return r.kind===`link`?{...r,delivery:t}:r}function openClick(e,t){let n=t.openLink(e);if(n.kind===`failed`)return{kind:`refused`,problem:n.reason};let r=parseHandlerUrl(n.value);return r.ok?{kind:`link`,verb:r.verb,value:r.value,link:n.value}:{kind:`refused`,problem:r.problem}}const DIRECTIONS=[`vertical`,`horizontal`],AXIS_OF={vertical:`row`,horizontal:`cell`};function placementId(e){return e.id??e.name}function placementIds(e){return[...walkNodes(e)].flatMap(e=>e.kind===`segment`?[placementId(e)]:[])}function freePlacementId(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function mapOpens(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*walkNodes(e){yield e;for(let t of childrenOf(e))yield*walkNodes(t)}const childPath=(e,t)=>`${e}.children[${t}]`,bodyPath=e=>`${e}.opens.body`;function*walkNodePaths(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*walkNodePaths(r,childPath(t,n));else e.opens!==void 0&&(yield*walkNodePaths(e.opens.body,bodyPath(t)))}function childrenOf(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}function parseArm(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const CACHE_KEYS=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function hasCacheField(e){return e.kind===`file`||e.kind===`shell`}function mapVariableTemplates(e,t){let n=e.kind===`template`?{...e,template:t(e.template,`template`)}:e;return hasCacheField(n)&&`key`in n.cache?{...n,cache:{...n.cache,key:t(n.cache.key,`cache.key`)}}:n}function variableTemplates(e){let t=[];return mapVariableTemplates(e,(e,n)=>(t.push([n,e]),e)),t}const MISSING_DATA=[`fail`,`ignore`];function missingDataOf(e){return e.missingData??`fail`}function*stateVarDecls(e){for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&(yield[t,n]);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&(yield[`${t}.${e}`,r])}const THEME_SETTING=`theme`,EFFECT_SETTING=`effect`,IMPLIED_SETTINGS=[THEME_SETTING,EFFECT_SETTING];function settingsOf(e){return{...e.settings,[THEME_SETTING]:{label:THEME_SETTING,domain:`theme`,default:e.palette??`bar`},[EFFECT_SETTING]:{label:EFFECT_SETTING,domain:PLACEMENT_EFFECTS,default:`bar`}}}function rangeOf$1(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function settingOrderProblems(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=rangeOf$1(r)?.atLeast;if(i===void 0)return[];let a=t[n],o=t[i];return a>=o?[]:[{setting:n,message:`"${n}" (${a}) is below "${i}" (${o}) — ${r.label} must be at least ${e[i].label}`}]})}function inSettingDomain(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&isPlacementThemeName(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function settingSpelling(e){return String(e)}function parseSettingSpelling(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return parseSessionInt(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return inSettingDomain(e,r)?r:void 0}function placementSetting(e,t,n,r){let i=e.settings?.[t]??n.default,a=e.drafts?.[t],o=a===void 0?null:r(a);return(o===null?void 0:parseSettingSpelling(n,o))??i}function describeSettingDomain(e){let{domain:t}=e;return t===`bool`?`true or false`:t===`theme`?`"bar" (the bar's own theme) or an installed theme name`:`min`in t?`an integer from ${t.min} to ${t.max}`:`one of ${t.map(e=>JSON.stringify(e)).join(`, `)}`}const JUSTIFY_MODES=[`left`,`center`,`right`],TRUNCATE_MODES=[`right`,`left`,`middle`],ROW_NAME_RE=/^[A-Za-z_][A-Za-z0-9_]*$/;function positionalRowName(e){return`#${e+1}`}const EMPTY_ROWS={rows:{}};function isRowsFragment(e){return`rows`in e}function positionalRows(e){return Object.fromEntries(e.map((e,t)=>[positionalRowName(t),e]))}function rootOf(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:positionalRows(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:positionalRows([n])}}function rootNode(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function fragmentNode(e){return isRowsFragment(e)?rootNode(e):e}function*fragmentNodePaths(e,t){if(!isRowsFragment(e)){yield*walkNodePaths(e,t);return}yield[rootNode(e),t];for(let[n,r]of Object.entries(e.rows))yield*walkNodePaths(r,`${t}.rows.${n}`)}function mergeRoot(e,t){return isRowsFragment(e)?{...t,...e,rows:{...t.rows,...e.rows}}:rootOf(e)}function insertCells(e,t){return t.reduce((e,t)=>{let n=t.id??t.seg,r=[...walkNodes(rootNode(e.root))].flatMap(e=>e.kind===`segment`?[e]:[]);if(r.some(e=>e.name===t.seg&&(t.id===void 0||placementId(e)===t.id)))return e;let i=r.find(e=>placementId(e)===n);if(i!==void 0)return refuse$1(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,besideRow(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]))}}:refuse$1(e,t,`${t.relation} "${t.anchor}", but there is no placement "${t.anchor}"`)},{root:e,unplaced:[]})}function refuse$1(e,t,n){return{...e,unplaced:[...e.unplaced,{cell:t,reason:n}]}}function besideRow(e,t,n,r){if(e.kind===`segment`&&placementId(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`?beside(e,t,n,r):besideInBody(e,t,n,r)}function beside(e,t,n,r){let i=e.children.findIndex(e=>e.kind===`segment`&&placementId(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`?beside(a,t,n,r):besideInBody(a,t,n,r);if(o!==null)return{...e,children:e.children.map((e,t)=>t===i?o:e)}}return null}function besideInBody(e,t,n,r){let i=!1,a=mapOpens(e,e=>{let a=beside(e,t,n,r);return i=a!==null,a??e});return i?a:null}function restages(e){if(!isRowsFragment(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const PRESET_FLOOR=`default`,FLOOR_FRAGMENT={};function presetNames(e){return[...new Set([PRESET_FLOOR,...Object.keys(e)])]}function effectivePresetName(e,t,n){return effectiveMemberName(void 0,e,t,PRESET_FLOOR,n)}function presetByName(e,t){let n={[PRESET_FLOOR]:FLOOR_FRAGMENT,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${PRESET_FLOOR}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function presetRoot(e,t){let n=presetByName(e.presets,t).root??EMPTY_ROWS;return{node:rootNode(mergeRoot(n,e.root)),path:restages(n)?`presets.${t}.root`:`root`}}function placeInserts(e,t,n){if(t.length===0)return{config:e,notices:[]};let r=insertCells(e.root,t),i=Object.entries(e.presets).filter(([,e])=>restages(e.root??EMPTY_ROWS)).map(([n,r])=>({name:n,preset:r,...insertCells(mergeRoot(r.root??EMPTY_ROWS,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:rootNode(n)}]))}},notices:[...a].flatMap(([e,t])=>[...t].map(([t,n])=>insertNotice(e,`${t} (in ${n.join(`, `)})`)))}}function insertNotice(e,t){return`${e.by.file}: ${e.by.entry} places "${e.seg}" ${t}`}function presetGlobals(e,t){return{...e.globals,...presetByName(e.presets,t).globals}}const PLUGIN_SCOPES=[`plugins`,`repo`];function pluginNs({scope:e,name:t}){return`${e}.${t}`}function ownedBy(e){return t=>t===e||t.startsWith(`${e}.`)}const SELF=`self`;function scopeOf(e){return PLUGIN_SCOPES.find(t=>e===t||e.startsWith(`${t}.`))}function otherScopeHint(e,t){let n=scopeOf(e);if(n===void 0||n===e)return``;let r=PLUGIN_SCOPES.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 STRING_LITERAL_RE=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*templateBlocks(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 PATH=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,OPERAND_RE=RegExp(`^(?:(\\$)(?:\\.(${PATH}))?|\\.(${PATH})?)(?=[\\s)]|$)`);function operandAt(e,t,n){let r=OPERAND_RE.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 KEYWORD_RE=/^(\w+)\b\s*([\s\S]*)$/;function*scopedBlocks(e,t){let n=[t];for(let r of templateBlocks(e)){let e=r.text.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=KEYWORD_RE.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:operandAt(i[1],s,t);continue}yield{code:e,dot:o,block:r},i===`if`&&n.push(o),i===`with`&&n.push(operandAt(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const TEMPLATE_KEYWORD_RE=/(?<![.$])\btemplate\s+$/;function*helperCalls(e,t,n){let r=0;for(let i of[...e.matchAll(STRING_LITERAL_RE)]){let a=i.index+i[0].length;TEMPLATE_KEYWORD_RE.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:operandAt(e.slice(a),t,n),index:i.index}),r=a}}function*callGraphBlocks(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...scopedBlocks(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...helperCalls(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 perTemplate(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const WALKS=new WeakMap;function callGraph(e,t){let n=WALKS.get(t);return n===void 0&&(n=perTemplate(e=>[...callGraphBlocks(e,t)]),WALKS.set(t,n)),n(e)}const REF_RE=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${PATH})`,`g`);function*dotRefs({code:e,dot:t,root:n}){let r=e.replace(STRING_LITERAL_RE,``);for(let e of[...r.matchAll(REF_RE)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function templateReads(e,t){let n=new Map;for(let r of callGraph(e,t))for(let e of dotRefs(r))n.has(e)||n.set(e,r.via);return n}const BINDING_KEYWORD_RE=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,NAME_ARGS={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*actionBindings(e){let t=0,n=0,r=`action`;for(let i of[...e.matchAll(STRING_LITERAL_RE)]){let a=e.slice(t,i.index),o=BINDING_KEYWORD_RE.exec(a);o===null?a.trim()!==``&&(n=0):(n=NAME_ARGS[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 templateActionRefs(e,t){let n=new Map;for(let{code:r,via:i}of callGraph(e,t))for(let{name:e,site:t}of actionBindings(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}const namesTaking=e=>Object.keys(NAME_ARGS).filter(t=>NAME_ARGS[t]>=e).join(`|`),COMPUTED_BINDING_RE=RegExp(`(?<![\\w.$])(?:(?:${namesTaking(1)})\\s+|(?:${namesTaking(2)})\\s+""\\s+)(?=[^\\s"\`)|}])`);function bindsComputedAction(e,t){for(let{code:n}of callGraph(e,t))if(COMPUTED_BINDING_RE.test(n.replace(STRING_LITERAL_RE,`""`)))return!0;return!1}const BARE_NAME_RE=/(?<![\w.$])[A-Za-z_]\w*/g;function templateFunctions(e,t){let n=new Set;for(let{code:r}of callGraph(e,t))for(let[e]of r.replace(STRING_LITERAL_RE,``).matchAll(BARE_NAME_RE))n.add(e);return n}function templateHelperRefs(e,t){return new Set([...templateHelperCalls(e,t)].filter(e=>Object.hasOwn(t,e)))}function templateHelperCalls(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of callGraph(e,t))for(let{name:e}of helperCalls(r,i,a))n.add(e);return n}const SELF_REF_RE=e=>RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.${e}(?![A-Za-z0-9_])`,`g`);function bindSelf(e,t,n){let r=SELF_REF_RE(t),i=ownedBy(t),a=[];for(let{dot:t,block:n}of scopedBlocks(e,``)){let e=n.text.replace(STRING_LITERAL_RE,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[...helperCalls(n.text,t,``),...actionBindings(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*declarationsAt(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*declaredVariables(e){for(let[t,n]of declarationsAt(e))yield[t,n]}function variableRead(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 refResolves(e,t){return variableRead(e,t.names).some(n=>!e.startsWith(`${n}.`)||t.documents.has(n))}function templateScopeOf(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),isDocumentDecl(r)&&n.add(e)};for(let[t,n]of declaredVariables(e))r(t,n);return{names:t,documents:n,helpers:e.helpers}}function isDocumentDecl(e){return e.kind===`dropped`||e.kind===`source`||(e.kind===`shell`||e.kind===`file`)&&parseArm(e.parse)===`json`}const ACTION_KEYS=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`slash`,`run`,`do`];function runDeclaration(e){return JSON.stringify([e.run,Object.entries(e.env),e.cwd,e.refreshes])}function*actionTemplates(e){let t=[];mapActionTemplates(e,(e,n)=>(t.push([n,e]),e)),yield*t}function mapActionTemplates(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 actionBindsTemplateValue(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function valueReads({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),[...[...actionTemplates(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=perTemplate(e=>{let i=bindsComputedAction(e,t)?Object.keys(n):templateActionRefs(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]}),a=perTemplate(n=>i(n).flatMap(n=>[...templateReads(n,t).keys()].map(t=>({path:t,reaches:variableRead(t,e)}))));return{ofTemplate:a,calls:perTemplate(e=>new Set(i(e).flatMap(e=>[...templateFunctions(e,t)]))),ofVariable:t=>[...variableTemplates(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...hasCacheField(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function payloadPathOf(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}const FOLDS$1=new WeakMap;function valueReadsOf(e){let t=FOLDS$1.get(e);return t===void 0&&(t=valueReads({names:new Set([...declaredVariables(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),FOLDS$1.set(e,t)),t}function trackingOf(e,t){return e.kind===`absent`?ok$1(`none`):e.kind===`failed`?e:t.kind===`failed`?t:ok$1(t.kind===`ok`?`tracked`:`gone`)}const PR_FIELDS={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function prOfHead(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?failed$2(`HEAD: ${t.reason}`,t.failedAt):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const GITHUB_PR_STATES={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},GITLAB_MR_STATES={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function prStateOf(e,t,n){return Object.hasOwn(t,n)?ok$1(t[n]):failed$2(`${e}: unknown state ${JSON.stringify(n)}`,`parse`)}const READ_FIELD_NAMES={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function gitInfoFailures(e){return Object.keys(READ_FIELD_NAMES).flatMap(t=>{let n=e[t];return n.kind===`failed`?[`git.${READ_FIELD_NAMES[t]}: ${n.reason}`]:[]})}function classify(e,t,n){return t.ok?ok$1(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?ABSENT$2:failed$2(launchFailure(e,t),`read`)}function launchFailure(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??firstLine(t.stderr)].filter(Boolean).join(`, `)}`}function firstLine(e){return e.trim().split(`
|
|
58
|
+
`}const sameLook$1=(e,t)=>e.fg===t.fg&&e.bg===t.bg&&e.link===t.link&&e.attrs?.join()===t.attrs?.join();function mergedRuns({runs:e}){let t=[];for(let n of e){let e=t.at(-1);e!==void 0&&sameLook$1(e,n)?t[t.length-1]={...e,text:e.text+n.text}:t.push(n)}return t}function plainOf(e){return e.map(e=>e.text).join(``)}const failedWith=e=>({ok:!1,error:e,code:`RENDER_FAILED`,daemonV:3}),renderFailed=e=>failedWith(failureOf(e).message),renderFailure=e=>({...e,kind:`threw`}),RENDER_ANSWERS={ansi:e=>({ok:!0,output:composeBar(e)}),frame:e=>({ok:!0,frame:e})};function holdsGit(e){return fs.existsSync(path.join(e,`.git`))}function gitRootOf(e){let t=path.resolve(e);for(;;){if(holdsGit(t))return t;let e=path.dirname(t);if(e===t)return;t=e}}function checkoutOf(e){let t=gitRootOf(e);return t===void 0?{root:path.resolve(e),git:!1}:{root:t,git:!0}}function probe(e){try{return ok$1(e())}catch(e){return e.code===`ENOENT`?ABSENT$2:failed$2(e.message,`read`)}}const realDir=e=>probe(()=>fs.realpathSync.native(e)),why=(e,t)=>t.kind===`absent`?`${e} is not there`:t.reason;function gitDirNamed(e){let t=probe(()=>fs.readFileSync(path.join(e,`.git`),`utf-8`));if(t.kind!==`ok`)return t;let n=t.value.match(/^gitdir:\s*(.+)$/m)?.[1]?.trim();return n===void 0?failed$2(`${path.join(e,`.git`)} names no gitdir`,`parse`):ok$1(path.resolve(e,n))}function sharedExcludeOf(e){let t=path.join(e,`.git`),n=probe(()=>fs.statSync(t).isDirectory());if(n.kind!==`ok`)return n;if(n.value)return ok$1(path.join(t,`info`,`exclude`));let r=gitDirNamed(e);if(r.kind!==`ok`)return r;let i=commonDirOf(r.value);if(i.kind===`failed`)return i;let a=i.kind===`ok`?i.value:r.value;return ok$1(path.join(a,`info`,`exclude`))}function commonDirOf(e){let t=probe(()=>fs.readFileSync(path.join(e,`commondir`),`utf-8`));if(t.kind!==`ok`)return t;let n=t.value.trim();return n===``?failed$2(`${path.join(e,`commondir`)} is empty`,`parse`):ok$1(path.resolve(e,n))}const UNLINKED={kind:`unlinked`},unproven=e=>({kind:`unproven`,reason:e});function worktreeLink(e){let t=gitRootOf(e);if(t===void 0)return UNLINKED;let n=path.join(t,`.git`),r=probe(()=>fs.statSync(n));if(r.kind===`ok`&&r.value.isDirectory())return UNLINKED;let i=probe(()=>fs.lstatSync(n));if(i.kind!==`ok`)return unproven(why(n,i));if(!i.value.isFile())return unproven(`${n} is not a file`);let a=gitDirNamed(t);if(a.kind!==`ok`)return unproven(why(n,a));let o=realDir(a.value);if(o.kind!==`ok`)return unproven(why(a.value,o));let s=commonDirOf(o.value);if(s.kind===`absent`)return UNLINKED;if(s.kind===`failed`)return unproven(s.reason);let c=realDir(s.value);if(c.kind!==`ok`)return unproven(why(s.value,c));if(path.dirname(o.value)!==path.join(c.value,`worktrees`))return unproven(`${o.value} is not a worktree of ${c.value}`);let l=path.join(o.value,`gitdir`),u=probe(()=>fs.readFileSync(l,`utf-8`));if(u.kind!==`ok`)return unproven(why(l,u));let d=path.resolve(o.value,u.value.trim()),f=realDir(path.dirname(d));if(path.basename(d)!==`.git`||f.kind!==`ok`||f.value!==t)return unproven(`${o.value} is the worktree at ${d}, not ${t}`);let p=path.basename(c.value)===`.git`?path.dirname(c.value):c.value;return{kind:`linked`,main:path.join(p,path.relative(t,e))}}function checkoutLocation(e){let t=realDir(e),n=t.kind===`ok`?t.value:path.resolve(e),r=gitRootOf(n);if(r===void 0)return{main:``,worktree:``,subpath:``,noRepo:!0};let i=path.relative(r,n),a=i===``?``:`/${i.split(path.sep).join(`/`)}`,o=worktreeLink(n);return o.kind===`linked`?{main:path.resolve(o.main,path.relative(n,r)),worktree:path.basename(r),subpath:a,noRepo:!1}:{main:r,worktree:``,subpath:a,noRepo:!1}}function noteFacts(e,t){for(let n of Object.entries(t))e.push(n)}const LEVEL={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`,down:`warn`};function detailOf(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.message]];case`threw`:return[[`error`,e.detail]];case`closing`:return[[`closing`,e.message]];case`abandoned`:return[[`abandoned`,`1`]];case`down`:return[[`down`,e.message]]}}function requestEvent(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...detailOf(n)];return{level:LEVEL[n.kind],line:eventLine(e,i)}}const NOTHING_TO_SETTLE=e=>{};function failed$1(e,t,n=``){return{outcome:renderFailure(t),resp:failedWith(`renderer ${e.name}: ${n}${t.message}`),seen:`failed`,settled:NOTHING_TO_SETTLE}}function located(e){let t=e.hookData.workspace?.current_dir??e.cwd;return{...e,hookData:{...e.hookData,...t!==void 0&&path.isAbsolute(t)&&{location:checkoutLocation(t)}}}}function recorded(e,t){e.push(...t.record)}async function answerStatusline(e,t,n,r,i,a,o,s,c,l){let u=located(a),d=(t,n)=>void e.deliver({kind:`event`,at:instantAt(i),event:{kind:`effect-done`,session:t.session,of:t.id,outcome:n===null?{kind:`ok`}:{kind:`failed`,reason:n}}},[[`effect`,String(t.id)]]),f=t.requested(u),p=await e.answer({kind:`event`,at:s,event:{kind:`config`,context:u,worldState:f}});if(recorded(l,p),p.kind===`threw`)return noteFacts(l,{renderer:e.name}),failed$1(e,p.failure,`its config turn: `);let m=await e.answer({kind:`event`,at:s,event:{kind:`request`,id:o,context:u,waitMs:c-i.monotonic(),idleSince:n.since(u.hookData.session_id,s)??null,following:[...r.following(u.hookData.session_id)],feeds:r.feedsOf(u.hookData.session_id,s)}});recorded(l,m),noteFacts(l,{hop:p.hopMs===null||m.hopMs===null?`-`:`${p.hopMs+m.hopMs}ms`});let{effects:h}=m;noteFacts(l,{renderer:e.name,effects:h.map(e=>e.kind===`present`?`present:${e.surface}`:e.kind).join(`,`)||`-`});let g=null;for(let e of h)switch(e.kind){case`present`:m.kind===`threw`?d(e,`its turn threw`):e.request===o?g===null?g=e:d(e,`a second statusline frame for request ${o}`):d(e,`presents request ${e.request}, not this turn's ${o}`);break;case`change`:break}if(m.kind===`threw`)return failed$1(e,m.failure);if(g===null)return failed$1(e,failureOf(Error(`presented no statusline frame for request ${o}`)));let _=g,v=i.monotonic(),y;try{y=RENDER_ANSWERS[u.encoding](parseFrame(_.frame))}catch(t){let n=failureOf(t);return d(_,`encoding its frame threw: ${n.message}`),failed$1(e,n,`its frame could not be encoded: `)}return noteFacts(l,{encoded:`${elapsedMs(i,v)}ms`}),{outcome:{kind:`ok`},resp:y,seen:_.frame.motion,settled:e=>d(_,e?null:`the client did not take the answer`)}}function expandHome(e,t){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?t+e.slice(1):e}function resolveUserPath(e,t,n){return path.resolve(e,expandHome(t,n))}function explicitConfigPath(e,t,n){return typeof t==`string`&&t!==``?resolveUserPath(e,t,n):void 0}const CONFIG_ENV=`CC_CANDYBAR_CONFIG`;function detectConfigEnv({env:e,home:t},n){return explicitConfigPath(n,e[CONFIG_ENV],t)}function requestedConfigTarget(e,t){return e===void 0?t===void 0?{source:`search`}:{source:`environment`,path:t}:{source:`argument`,path:e}}function cliConfigTarget(e,t,n){return requestedConfigTarget(explicitConfigPath(n,e,t.home),detectConfigEnv(t,n))}function chainName(e,t=`bundled default (no config file loaded)`){return e.join(` < `)||t}const KNOWN_TOP_LEVEL=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`]),REQUIRED_FIELDS=[[`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`]],OPTIONAL_FIELDS=[[`workspace.added_dirs`,`string-list`]];function validateHookData(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of REQUIRED_FIELDS){let i=resolvePath$1(n,e);if(i==null)t.missingRequired.push(e);else{let n=kindOf(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of OPTIONAL_FIELDS){let i=resolvePath$1(n,e),a=i===void 0?r:listKind(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))KNOWN_TOP_LEVEL.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function kindOf(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function listKind(e){return Array.isArray(e)&&e.every(e=>kindOf(e)===`string`)?`string-list`:kindOf(e)}function resolvePath$1(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 answeredOf(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const SIGHTING_ROLES=[`statusline`,`frames`],roleOf=e=>e?.kind===`frames`?`frames`:`statusline`,DRAWN_MOTIONS=[`moves`,`can-move`,`still`],RATE_LIMITS_SEEN=[`carried`,`missing`,`unanswered`],FRAMES_SEEN=[...DRAWN_MOTIONS,`failed`,`drawing`];function rateLimitsSeen(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:answeredOf(e)===`no`?`unanswered`:`missing`}function transcriptSaid(e){return{path:e.transcript_path,answered:answeredOf(e)===`yes`}}var RenderSightings=class{seen=new Map;see(e,t,n,r){let i=roleOf(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)}};function parseRenderArgs(e,t,n){let{tokens:r}=parseArgs({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),i=(r??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),a=(r??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===i&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:explicitConfigPath(t,i?.value,n),refusedArgs:a.filter((e,t)=>a.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function parseRenderEncoding(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=RENDER_ENCODINGS.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${RENDER_ENCODINGS.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function checkRenderRequest(e,t,n,r){let{report:i}=validateHookData(e.hookData),a=[];for(let e of i.missingRequired)a.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of i.typeMismatches)a.push(`field '${e}' expected ${t}, got ${n}`);let o=parseSessionId(e.hookData?.session_id);o.ok||a.push(`field 'session_id' ${o.problem}`),(typeof e.cwd!=`string`||!isAbsolute(e.cwd))&&a.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&a.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let s=parseRenderEncoding(e.encoding);s.ok||a.push(s.problem);let c=parseClientDeadline(e.deadline);if(c.kind===`refused`)return{ok:!1,problems:[...a,c.problem]};if(a.length>0||!o.ok||!s.ok)return{ok:!1,problems:a};for(let e of i.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let l=parseClientHints(e),{configFile:u,refusedArgs:d}=parseRenderArgs(e.args,e.cwd,r);return{ok:!0,req:{...e,hookData:{...e.hookData,session_id:o.id},deadline:c,encoding:s.encoding,hints:l,rateLimits:rateLimitsSeen(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:requestedConfigTarget(u,l.configEnv)},refusedArgs:d}}}const CLICK_PROGRAM_TIMEOUT_MS=5e3,clickLaunchVia=e=>t=>e.launch({...t,args:t.args?.slice(),timeoutMs:CLICK_PROGRAM_TIMEOUT_MS});async function clickLaunch(e,t,n,r){let i=await e(t);if(i.ok)return{outcome:{kind:`ok`},said:r};let a=clickFailed(i,n);return{outcome:{kind:`skipped`,reason:a},said:a}}function clickFailed(e,t){if(e.reason===`rate-limited`)return`${t} not run: ${failureText(e)}`;throw e.reason===`aborted`?new DaemonClosing(t):Error(`${t} failed (${failureText(e)})`)}const HANDOFF_POLL_MS=50;async function clickHandoff(e,t,n,r,i,a){let o=mkdtempSync(path.join(a,`cc-candybar-handoff-`));try{let a={stdout:`/dev/null`,stderr:path.join(o,`stderr`),status:path.join(o,`status`)},s=e.launchJobSync(t,a);if(!s.ok){r(`warn`,clickFailed({...s,stdout:``,stderr:``,exitCode:null,signal:null},n));return}s.release();let c=e.clock.monotonic()+i;for(;;){let o=e.jobGroupAlive(s.pid),l=readJobEnd(a.status);if(l!==null){if(l.kind===`exit`&&l.code===0)return;clickFailed(l.kind===`exit`?{ok:!1,reason:`non-zero`,stdout:``,stderr:readFileSync(a.stderr,`utf8`),exitCode:l.code,signal:null}:{ok:!1,reason:`timeout`,stdout:``,stderr:``,exitCode:null,signal:null},n);return}if(!o)throw Error(`${n} failed (lost): the opener ended with no verdict`);if(e.clock.monotonic()>=c){r(`info`,`${t.category} handed off at ${i}ms, pid ${s.pid}`);return}await sleep(e.clock,HANDOFF_POLL_MS)}}finally{rmSync(o,{recursive:!0,force:!0,maxRetries:3})}}const LINK_KEY_BYTES=32,MAC_SPELLING=/^[0-9a-f]{64}$/,LINK_MAC_BYTES=16,LINK_MAC_SPELLING=/^[A-Za-z0-9_-]{22}$/,LINK_MAC_MARK=`#`;function transitForm(e){return e.toWellFormed().replace(/%(?![0-9A-Fa-f]{2})|[^A-Za-z0-9\-._~!$&'()*+,;=:@/?%]/gu,encodeURIComponent)}function unprovenLink(e){let t=isBarLink(e)?e.lastIndexOf(LINK_MAC_MARK):-1;return t===-1?e:e.slice(0,t)}function linkMac(e,t){return Buffer.from(createHmac(`sha256`,e).update(t).digest().subarray(0,LINK_MAC_BYTES)).toString(`base64`).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replace(/=+$/,``)}function signLinkWith(e,t){let n=transitForm(t);return`${n}${LINK_MAC_MARK}${linkMac(e,n)}`}function openLinkWith(e,t){let n=t.lastIndexOf(LINK_MAC_MARK);if(n===-1)return{kind:`failed`,reason:`the link carries no signature: the bar did not draw it, or drew it before its links were signed`};let r=t.slice(0,n),i=t.slice(n+1);return LINK_MAC_SPELLING.test(i)&&timingSafeEqual(Buffer.from(i),Buffer.from(linkMac(e,r)))?{kind:`ok`,value:r}:{kind:`failed`,reason:`the link's signature does not match what it carries: it was changed after the bar drew it, or another key signed it`}}function digest(e,t){return createHmac(`sha256`,e).update(JSON.stringify([t.sessionId,t.action,t.declaration,t.evaluated])).digest()}function linkSigner(e){if(e.length!==32)throw Error(`a link key is 32 bytes, got ${e.length}`);let t=new Map;return{sign:t=>digest(e,t).toString(`hex`),verify:(t,n)=>MAC_SPELLING.test(n)?timingSafeEqual(Buffer.from(n,`hex`),digest(e,t)):!1,signLink:n=>{let r=t.get(n);return r===void 0&&(t.size>=SIGNED_LINKS_HELD&&t.clear(),r=signLinkWith(e,n),t.set(n,r)),r},openLink:t=>openLinkWith(e,t)}}const SIGNED_LINKS_HELD=1024;function linkSignerOver(e){let t,n=()=>{let n=e();return n.kind===`ok`?{kind:`ok`,value:t??=linkSigner(n.value)}:n},r=()=>{let e=n();if(e.kind===`failed`)throw Error(e.reason);return e.value};return{sign:e=>r().sign(e),verify:(e,t)=>r().verify(e,t),signLink:e=>r().signLink(e),openLink:e=>{let t=n();return t.kind===`ok`?t.value.openLink(e):t}}}let preview;function previewSigner(){return preview??=linkSigner(randomBytes(32))}function signingFrames(e){let t=t=>isBarLink(t)?e.signLink(t):t;return e=>({...e,rows:e.rows.map(e=>({...e,runs:e.runs.map(e=>e.link===void 0?e:{...e,link:t(e.link)})}))})}const TMUX_ENV={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`},inTmux=e=>e!=null;function detectTmuxHint(e){let t=e[TMUX_ENV.socket]??``,n=e[TMUX_ENV.pane]??``;if(t===``||n===``)return null;let r=e[TMUX_ENV.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const RENDERERS$1=[`claude`,`tmux`],IN_TMUX=`ne .tmux.pane ""`,LANES={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}},LANE_NAMES=Object.keys(LANES),TOGGLED_LANES=LANE_NAMES.filter(e=>LANES[e].switch.on===!0),ANSWERING={by:`request`},DRAWING_VAR=`drawing`,drawingVar=e=>`${DRAWING_VAR}.${e}`,UNFOLLOWED={subscribers:0,fps:0,shown:!0},laneFeedVar=(e,t)=>`feeds.${e}.${t}`;function perLane(e){return Object.fromEntries(LANE_NAMES.map(t=>[t,e(t)]))}const UNFOLLOWED_FEEDS=perLane(()=>UNFOLLOWED);function parseLane(e){return typeof e==`string`&&Object.hasOwn(LANES,e)?e:null}function feedsFact(e){return LANE_NAMES.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(`,`)||`-`}const RENDER_THEME=new Theme({"strip.separator":`default`,"strip.rail":`default`});function resolvedStyle(e){return RENDER_THEME.resolve(e)}function memoPerPalette(){let e=new WeakMap;return(t,n,r)=>{let i=e.get(t);i===void 0&&(i=new Map,e.set(t,i));let a=i.get(n);if(a!==void 0)return a;let o=r();return i.set(n,o),o}}const is=(e,t)=>e===t;function sameBy(e){let t=Object.keys(e);return(n,r)=>t.every(t=>e[t](n[t],r[t]))}const sameEach=e=>(t,n)=>t.length===n.length&&t.every((t,r)=>e(t,n[r])),DECOR_HUES=[`primary`,`secondary`,`accent`],LADDER=[`darken-3`,`darken-2`,`darken-1`,`base`,`lighten-1`,`lighten-2`,`lighten-3`],SHADE_SUFFIX={"darken-3":`-darken-3`,"darken-2":`-darken-2`,"darken-1":`-darken-1`,base:``,"lighten-1":`-lighten-1`,"lighten-2":`-lighten-2`,"lighten-3":`-lighten-3`,muted:`-muted`},shadeRole=(e,t)=>`${e}${SHADE_SUFFIX[t]}`,poleText=(e,t,n,r)=>textOn(e,n,r),roleText=(e,t,n,r)=>legibleOn(e,e.get(`text-${t}`),n,r),ladderWindow=e=>({tones:[LADDER[e],LADDER[e+2],LADDER[e+1]],text:poleText,activated:`muted`}),centredWindow=e=>({tones:[LADDER[3-e],LADDER[3+e],LADDER[3]],text:poleText,activated:`muted`}),pairWindow=e=>({tones:[LADDER[3-e],LADDER[3+e]],text:poleText,activated:`muted`}),TRIAL_SHADES={wide:centredWindow(2),widest:centredWindow(3),pair:pairWindow(2),"pair-wide":pairWindow(3)},TRIAL_SHADE_NAMES=Object.keys(TRIAL_SHADES),SHADES={muted:{tones:[`muted`,`base`],text:roleText,activated:`lighten-2`},deepest:ladderWindow(0),deeper:ladderWindow(1),middle:ladderWindow(2),brighter:ladderWindow(3),brightest:ladderWindow(4),...TRIAL_SHADES},lineageHue=(e,t)=>e[t%e.length],KEYSTONE_HUE=`accent`,WHOLE_ROW=1/0,OPENS_TODAY={keystones:[],open:[`accent`,`primary`,`secondary`]},KEYSTONE_PLACEMENTS={door:[`bar-start`],start:[`line-start`],end:[`line-end`],ends:[`line-start`,`line-end`]},OPEN_LINEAGES={primary:[`primary`],secondary:[`secondary`],alternate:[`primary`,`secondary`]};function tunings(){let e=Object.entries(KEYSTONE_PLACEMENTS).flatMap(([e,t])=>Object.entries(OPEN_LINEAGES).map(([n,r])=>[`${e}-${n}`,{hues:[`secondary`],run:WHOLE_ROW,keystones:t,open:r}]));return Object.fromEntries(e)}const TUNINGS=tunings(),VARIATIONS={accent:{hues:[`secondary`,`accent`],run:WHOLE_ROW,...OPENS_TODAY},duo:{hues:[`primary`,`secondary`],run:WHOLE_ROW,...OPENS_TODAY},mono:{hues:[`primary`],run:WHOLE_ROW,...OPENS_TODAY},alt:{hues:[`secondary`,`accent`],run:3,...OPENS_TODAY},...TUNINGS},TRIAL_VARIATION_NAMES=Object.keys(TUNINGS),vocabularyOf=(e,t,n)=>turnsHeld(e,t,t.variation.hues.flatMap(r=>{let i=windowAt(e,r,t.shade,n);return t.shade.tones.map((e,t)=>({hue:r,shade:i[t%i.length]}))}),n);function windowAt(e,t,n,r){return WINDOWS(e,`${t}|${n.tones.join(`,`)}|${r}`,()=>{let i=drawnIn(e,t,r),a=windowSize(n.tones.length,new Set(LADDER.map(i)).size),[o,...s]=n.tones,c=[o];for(let e of s)c.length<a&&c.every(t=>i(t)!==i(e))&&c.push(e);return inWalkOrder(Array.from({length:a-c.length}).reduce(a=>{let o=widen(e,t,n.tones,a.map(i),r);return o===void 0?a:[...a,o]},c))})}const inWalkOrder=e=>{if(e.length<3)return e;let t=LADDER,[n,...r]=[...e].sort((e,n)=>t.indexOf(e)-t.indexOf(n));return[n,r.at(-1),...r.slice(0,-1)]},windowSize=(e,t)=>Math.max(2,Math.min(e,t-1)),WINDOWS=memoPerPalette(),drawnIn=(e,t,n)=>r=>drawnColour(e.get(shadeRole(t,r)),n).hex;function widen(e,t,n,r,i){let a=drawnIn(e,t,i);return ladderFrom(n,e.dark).find(e=>!r.includes(a(e)))}function ladderFrom(e,t){let n=LADDER,r=e=>e===`muted`?t?-1:n.length:n.indexOf(e),i=t?1:-1;return LADDER.map((t,n)=>({rung:t,at:n,distance:Math.min(...e.map(e=>Math.abs(n-r(e))))})).filter(({distance:e})=>e>0).sort((e,t)=>e.distance-t.distance||(t.at-e.at)*i).map(({rung:e})=>e)}const inBin=(e,t)=>Math.floor(e*t),inHalves=(e,t)=>{let n=t-1;for(let t=e;t<.5&&n>0;t*=2)n--;return n},PHI=.6180339887498949,vanDerCorput=e=>{let t=0,n=.5;for(let r=e;r>0;r>>=1,n/=2)t+=n*(r&1);return t},DISTRIBUTION_NAMES=[`van-der-corput`,`golden-angle`,`ends-interleaved`,`monotonic`,`uniform`],isDistributionName=e=>typeof e==`string`&&DISTRIBUTION_NAMES.includes(e),DISTRIBUTIONS={"van-der-corput":{place:vanDerCorput,quantize:inHalves},"golden-angle":{place:e=>e*PHI%1,quantize:inBin},"ends-interleaved":{place:(e,t)=>((e%2==0?e/2:t-1-(e-1)/2)+.5)/t,quantize:inBin},monotonic:{place:(e,t)=>(e+.5)/t,quantize:inBin},uniform:{place:()=>.5,quantize:inHalves}},DEFAULT_DISTRIBUTION=`van-der-corput`,placedBy=e=>DISTRIBUTIONS[e??`van-der-corput`];function entryOf$1(e,t){if(e===void 0)return 0;let{place:n,quantize:r}=e.distribution;return r(n(e.index,e.count),t)}function vocabularySelect(e,t){let n=e[entryOf$1(t,e.length)];if(n===void 0)throw Error(`vocabularySelect: empty vocabulary`);return n}function rowAndCell(e){let t=e=>e.axis===`cell`,n=e.findIndex(t);return{row:(n===-1?e:e.slice(0,n)).at(-1),cell:e.findLast(t)}}const rowStart=(e,t)=>entryOf$1(t,e.hues.length);function decorEntryFor(e,t,n,r){let{row:i,cell:a}=rowAndCell(n);return a===void 0?dealtAt(e,t,i,a,r):lineAt(e,t,i,a,r)[a.index-a.lineStart]}function dealtAt(e,t,n,r,i){let{hues:a,run:o,keystones:s}=t.variation,c=r===void 0?0:Math.floor(r.index/o),l=a[(rowStart(t.variation,n)+c)%a.length];if(l===void 0)throw Error(`decorEntryFor: empty variation`);let u=s.some(e=>KEYSTONE_AT[e](n,r))?KEYSTONE_HUE:l;return{hue:u,shade:vocabularySelect(windowAt(e,u,t.shade,i),r)}}function lineAt(e,t,n,r,i){let{hues:a,run:o,keystones:s,open:c}=t.variation;return LINES(e,[a.join(`,`),o,s.join(`,`),c.join(`,`),t.shade.tones.join(`,`),t.shade.activated,n===void 0?``:stepKey(n),stepKey(r,r.lineStart),i].join(`|`),()=>turnsHeld(e,t,Array.from({length:r.lineEnd-r.lineStart+1},(a,o)=>dealtAt(e,t,n,{...r,index:r.lineStart+o},i)),i))}const LINES=memoPerPalette();function stepKey({axis:e,index:t,count:n,distribution:r,lineStart:i,lineEnd:a,...o},s=t){return`${e},${s},${n},${distributionName(r)},${i},${a}`}function distributionName(e){let t=DISTRIBUTION_NAME.get(e);if(t===void 0)throw Error(`decorEntryFor: a cell placed outside DISTRIBUTIONS`);return t}const DISTRIBUTION_NAME=new Map(DISTRIBUTION_NAMES.map(e=>[DISTRIBUTIONS[e],e]));function turnsHeld(e,t,n,r){let i=[...n],a=t=>{let n=i[t];return n&&drawnIn(e,n.hue,r)(n.shade)},o=drawnPress(e,{decor:t,depth:0},r),s=(n,o)=>{let{hue:s}=i[n],c=[a(n-1),a(n+1),...o].filter(e=>e!==void 0),l=windowAt(e,s,t.shade,r),u=l.find(t=>!c.includes(drawnIn(e,s,r)(t)))??widen(e,s,l,c,r);return u===void 0?void 0:{hue:s,shade:u}},c=e=>[[o],[]].flatMap(t=>[e,e-1].map(e=>({place:e,off:t})));for(let e=1;e<i.length;e++)if(!(i[e-1].hue===i[e].hue||a(e-1)!==a(e)))for(let{place:t,off:n}of c(e)){let e=s(t,n);if(e!==void 0){i[t]=e;break}}return i}const KEYSTONE_AT={"bar-start":(e,t)=>(e?.index??0)===0&&(t?.index??0)===0,"line-start":(e,t)=>t===void 0||t.index===t.lineStart,"line-end":(e,t)=>t===void 0||t.index===t.lineEnd},PLANE_ROLE=`surface`,decorEntryColour=(e,t)=>e.get(shadeRole(t.hue,t.shade)),TEXT_MIN_CONTRAST=4.5;function textOn(e,t,n){return POLE_TEXT(e,`${t.hex}|${n}`,()=>{let r=contrastFor(t);return legibleOn(e,[`background`,`foreground`].map(t=>e.get(t)).reduce((e,t)=>contrastRatio(r,t)<contrastRatio(r,e)?t:e),t,n)})}const POLE_TEXT=memoPerPalette();function legibleOn(e,t,n,r){return LEGIBLE(e,`${t.hex}|${n.hex}|${r}`,()=>ensureContrast(t,n,TEXT_MIN_CONTRAST,r))}const LEGIBLE=memoPerPalette(),hueOf=({decor:e,depth:t})=>lineageHue(e.variation.open,t),bandEntries=(e,t,n)=>windowAt(e,hueOf(t),t.decor.shade,n).map(e=>({hue:hueOf(t),shade:e}));function pressedAt(e,t,n){let{decor:r,depth:i}=t,{variation:a,shade:o}=r;return PRESSED(e,[i,a.open.join(`,`),a.hues.join(`,`),a.keystones.length,o.tones.join(`,`),o.activated,n].join(`|`),()=>{let s=hueOf(t),c=t=>windowAt(e,t,o,n).map(drawnIn(e,t,n)),l=a.keystones.length>0?[KEYSTONE_HUE]:[],u=i===0?[...a.hues,...l].flatMap(c):(t=>[...c(hueOf(t)),drawnPress(e,t,n)])({decor:r,depth:i-1}),d=[...c(s),...u];return d.includes(drawnIn(e,s,n)(o.activated))?widen(e,s,[o.activated],d,n)??o.activated:o.activated})}const PRESSED=memoPerPalette(),drawnPress=(e,t,n)=>drawnIn(e,hueOf(t),n)(pressedAt(e,t,n)),nestedIn=e=>({...e,depth:e.depth+1});function bandFor(e,t,n){return{state:e.get(shadeRole(hueOf(t),pressedAt(e,t,n))),plane:e.get(PLANE_ROLE),items:bandEntries(e,t,n).map(t=>decorEntryColour(e,t))}}function bandItemFor(e,t,n,r){return vocabularySelect(bandFor(e,t,r).items,n)}function bandItem(e,t,n,r){let i=bandItemFor(e,t,n,r);return{tint:i,text:t.decor.shade.text(e,hueOf(t),i,r)}}function sameRegion(e,t){switch(e.kind){case`bar`:return t.kind===`bar`&&sameBarRegion(e,t);case`band`:return t.kind===`band`&&sameBandRegion(e,t)}}const sameAddress=sameEach(sameBy({index:is,count:is,distribution:is,axis:is,lineStart:is,lineEnd:is})),sameDecor=sameBy({variation:is,shade:is}),sameDisclosure=sameBy({decor:sameDecor,depth:is}),sameBarRegion=sameBy({kind:is,decor:sameDecor,address:sameAddress}),sameBandRegion=sameBy({kind:is,band:sameDisclosure,address:sameAddress}),barRoot=e=>({kind:`bar`,decor:e,address:[]}),descend=(e,t)=>({...e,address:[...e.address,t]}),bandRoot=e=>({kind:`band`,band:e,address:[]});function decorationFor(e,t,n){switch(t.kind){case`bar`:{let{decor:r,address:i}=t,a=decorEntryFor(e,r,i,n),o=decorEntryColour(e,a);return{tint:o,text:r.shade.text(e,a.hue,o,n),disclosure:{decor:r,depth:0}}}case`band`:{let{band:r,address:i}=t;return{...bandItem(e,r,rowAndCell(i).cell,n),disclosure:nestedIn(r)}}}}const RETIRED_THEMES=new Map([[`dark`,`textual-dark`],[`light`,`textual-light`]]);function retiredThemeNote(e){let t=typeof e==`string`?RETIRED_THEMES.get(e):void 0;return t===void 0?``:` — "${e}" was retired; write "${t}", the same palette`}const THEME_FLOOR=`textual-dark`;function effectiveGlobal(e,t,n,r,i){let a=t===null?null:i(t);return e??a??n??r}function listResolvablePaletteNames(){return listThemePalettes()}const FOLLOW_BAR=`bar`;function placementThemeNames(){return[`bar`,...listResolvablePaletteNames()]}let placementThemeSet;function isPlacementThemeName(e){return placementThemeSet??=new Set(placementThemeNames()),placementThemeSet.has(e)}function effectiveMemberName(e,t,n,r,i){let a=e=>Object.prototype.hasOwnProperty.call(i,e)?e:null;return effectiveGlobal(e===void 0?null:a(e),t,a(n??r),r,a)}const EXPRESSION_SLOTS=[`style`,`palette`,`effect`];function isExpression(e){return e!==void 0&&e.includes(`{{`)}function resolveSelection(e,t,n,r,i){let a=isExpression(n)?{kind:`expression`,source:n}:i(n??r.name);return effectiveGlobal(e===void 0?null:i(e),t,a,r,i)}const STYLE_FLOOR=`none`;function namedStyle(e,t){let n=t[e];return n===void 0?null:{kind:`decided`,name:e,value:n}}function decideStyleName(e,t){return namedStyle(e,t)??namedStyle(`none`,t)??{kind:`decided`,name:`none`,value:IDENTITY}}function resolveStyleSelection(e,t,n,r){return resolveSelection(e,t,n,decideStyleName(STYLE_FLOOR,r),e=>namedStyle(e,r))}const EFFECT_FLOOR=`none`,SLOT_FLOORS={style:STYLE_FLOOR,palette:THEME_FLOOR,effect:EFFECT_FLOOR};function ruleFloorMessage(e,t,n){return`${e} rendered "${SLOT_FLOORS[t]}": ${n}`}const EFFECT_NAMES=Object.freeze([EFFECT_FLOOR,...Object.keys(EFFECT_CATALOGUE.loops)]),ANIMATION_SPEEDS=Object.freeze({"1x":1,"5x":5,"10x":10,"20x":20}),ANIMATION_SPEED_NAMES=Object.keys(ANIMATION_SPEEDS),PLACEMENT_EFFECTS=Object.freeze([`bar`,...EFFECT_NAMES]);function namedEffect(e){let t=EFFECT_NAMES.find(t=>t===e);return t===void 0?null:{kind:`decided`,name:e,value:t}}function decideEffectName(e){return namedEffect(e)??{kind:`decided`,name:`none`,value:`none`}}function resolveEffectSelection(e,t,n){return resolveSelection(e,t,n,decideEffectName(EFFECT_FLOOR),namedEffect)}const ENDCAPS_SHAPES=Object.freeze(Object.keys(JOINERS)),STYLE_ERA_ENDCAPS=[`powerline`,`capsule`,`plain`];function isStyleEraEndcaps(e){return STYLE_ERA_ENDCAPS.includes(e)}const COLOR_COMPATIBILITIES=[`truecolor`,`256`,`ansi`,`none`];function isColorCompatibility(e){return COLOR_COMPATIBILITIES.includes(e)}function drawnDepth(e){return resolveColorSystem(e)??ColorDepth.DEFAULT}const VARIATION_NAMES=Object.keys(VARIATIONS),SHADE_NAMES=Object.keys(SHADES),BOOLEAN_TRUE=`true`,BOOLEAN_FALSE=`false`,BOOLEAN_MEMBERS=[BOOLEAN_TRUE,BOOLEAN_FALSE],PADDING_RANGE={min:0,max:16};function parseSessionBoolean(e){return e===`true`?!0:e===`false`?!1:null}function parseSessionInt(e,t){let n=Number(e);return Number.isInteger(n)&&String(n)===e&&n>=t.min&&n<=t.max?n:null}const flashes=(e,t)=>Array.from({length:e*2},(e,n)=>({lit:n%2==0,seconds:t})),CLOSING_FLASH=[...flashes(3,1),...flashes(3,.25)],CLOSING_FLASH_SECONDS=CLOSING_FLASH.reduce((e,{seconds:t})=>e+t,0),MENU_TIMEOUT_RANGE={min:15,max:600,step:15},closesAt=(e,t)=>e+t,flashBegins=e=>e-CLOSING_FLASH_SECONDS,STILL={kind:`still`},animationAt=e=>Timeline.at(e.timeline,e.wall),BAR_SCOPE=Symbol(`bar`);function isMoving(e){return e.name!==EFFECT_FLOOR}function together(e){return t=>Animation.map(Animation.all(e.map(({timeline:e,effect:n})=>Timeline.run(e,n(t)))),e=>(t,n)=>e.reduce((e,t)=>t(e,n),t))}const ASSUMED_TERMINAL=DEFAULT_TERMINAL_THEME;function fromGround(e,t){let n=new TerminalTheme(t,ASSUMED_TERMINAL.foregroundColor,ASSUMED_TERMINAL.ansiColors,ASSUMED_TERMINAL.palette);return t=>e({...t,theme:n})}function paintedOn(e,t){return n=>confined(()=>e(n),...t)(n)}function noiseOffset(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 NOISE_DEPTH=4096;function closingFlash(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=CLOSING_FLASH.reduceRight((e,{lit:t,seconds:n})=>Animation.sequence(Animation.constant(t?r:i),n,e),Animation.constant(i)),o=Animation.sequence(Animation.constant(i),n,a);return()=>o}var SessionEffects=class{inForce=null;anchor=Timeline.play(0);placements=new Map;made=new Map;passages=null;frame={effect:EFFECT_FLOOR,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:Timeline.withRate(this.anchor,e,t)}}motion(e,t,n,r=null){let i=animationAt(t),a=e=>Timeline.seek(t.timeline,t.wall,e),o=this.inForce?.name===e?this.inForce:{name:e,since:i},s={scope:BAR_SCOPE,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=EFFECT_CATALOGUE.transitions[e]({z:noiseOffset(`${this.key}@${t}`)*NOISE_DEPTH});return{name:e,since:i,done:e=>r.done(e),effect:fromGround(r.effect,n)}},C=({since:e,done:t})=>t(i-e),w=(e,t,n)=>({drawing:t,passage:g===null?null:n===void 0||n.passage?.name===`dissolve`?S(`fade`,e,t):n.passage!==null&&!C(n.passage)?n.passage:null}),T=(e,t)=>{if(t===void 0||t.drawing.opened||t.drawing.own.length===0)return;if(t.passage?.name===`dissolve`)return C(t.passage)?void 0:t;let r={...t.drawing,own:t.drawing.own.map(n.hold)};return{drawing:r,passage:S(`dissolve`,e,r)}},E=(e,t)=>{if(_.has(e))throw Error(`placement "${e}" was reached twice in one frame`);_.add(e);let r=g?.(e),{drawing:a,deeper:o}=n.returned(e,t),s=a===null?T(e,r):w(e,a,r);return s===void 0?t:(s.passage!==null&&(v.set(e,s.passage),(s.passage.name===`fade`?y:b).push({placement:e,t:i-s.passage.since})),a===null?[...s.drawing.own,...o]:t)},D=(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}},O=(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=noiseOffset(t.scope===BAR_SCOPE?e:`${e}@${t.scope}`),s=a?i.effect:EFFECT_CATALOGUE.loops[t.name]({z:o*NOISE_DEPTH});return x[a?`reused`:`made`]++,n.set(t.scope,{name:t.name,effect:s}),s},k=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?s:D(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()]},A=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:confined(n.effect,...t)}]})},j=r===null?[]:[{timeline:Timeline.play(r.idleSince),effect:closingFlash(r.fill,r.text,flashBegins(r.timeoutS))}],M=e=>e===`menu`?j:[];return{placed:h===`off`?(e,t)=>t:E,row:(e,n,r)=>{let i=(r.some(e=>e.placement.effect!==`bar`)?k(r):[{...s,owners:void 0}]).filter(isMoving),o=A(r),c=M(n);if(i.length===0&&o.length===0&&c.length===0)return STILL;let l=`${this.key}#${e}`;return{kind:`moving`,time:t.wall,wrap:e=>new Effected(e,together([...i.map(e=>{let t=O(l,e);return{timeline:a(e.t),effect:e.owners===void 0?t:paintedOn(t,e.owners)}}),...o,...c]),{key:l,theme:ASSUMED_TERMINAL})}},drawn:()=>{this.anchor=t.timeline,this.inForce=o,this.placements=l,this.made=d,this.passages=h===`off`?null:v,this.frame=x}}}};const MAX_SESSIONS$5=256;var EffectSessions=class{sessions=new Map;constructor(e=MAX_SESSIONS$5){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new SessionEffects(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 UNBOUNDED_DRAW_WIDTH=80,ROW_HOST={};function draw(e,t){let n=resolveDestination(t.colorSystem),{time:r}=t,i=1/0,a=[...render(e,{maxWidth:t.width??UNBOUNDED_DRAW_WIDTH,isTerminal:!1,asciiOnly:!1,theme:RENDER_THEME,colorSystem:n.colorSystem,...r===void 0?{}:{frame:{time:r,host:ROW_HOST}},onStyleError:e=>{throw e},onHold:({nextChange:e})=>{i=Math.min(i,e)}})];return{lines:runLines(a,n.colorSystem),nextChange:Math.min(Segment.nextChange(a),i)}}const separatorJoiners=new Map;function plainWith(e){let t=separatorJoiners.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}=JOINERS.plain,a=new CellJoiner({glyph:n(r.glyph),ascii:r.ascii},i);return separatorJoiners.set(e,a),a}function pickJoiner(e,t){return e===`plain`&&t!==void 0?plainWith(t):JOINERS[e]}const geometryMemo=new Map;function stripGeometry(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=geometryMemo.get(t);if(n!==void 0)return n;let r=pickJoiner(e.endcaps,e.separator),i=e=>new RichText(`x`,{end:``,overflow:`ignore`,style:new Style({bgcolor:e})}),a=e=>{let{lines:t}=draw(new Strip(e,r),{colorSystem:null});return new RichText(plainOf(t.flat())).cellLength},o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return geometryMemo.set(t,s),s}function stripChromeCols(e){return stripGeometry(e).chrome}function stripSeamCols(e){return stripGeometry(e).seam}const PRIVATE_USE=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function privateGlyphsIn(e){return[...new Set(e.match(PRIVATE_USE)??[])].join(``)}function stripPrivateGlyphs(e){let t=pickJoiner(e.endcaps,e.separator),n=e=>new RichText(`x`,{end:``,style:new Style({bgcolor:e})}),{lines:r}=draw(new Strip([n(`#101010`),n(`#202020`)],t),{colorSystem:null});return privateGlyphsIn(plainOf(r.flat()))}function lineWidth(e){return e.wrap?e.width:1/0}function wrappedLines(e,t){return draw(new RichText(e,{overflow:`fold`,end:``}),{colorSystem:null,width:t}).lines.map(plainOf)}function drawStripCells(e,t,n=STILL){if(e.length===0)return{lines:[[]],nextChange:1/0};let r=pickJoiner(t.endcaps,t.separator),i=Number.isFinite(lineWidth(t)),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new FlexStrip([...e],{joiner:r}):new Strip([...e],r),s=n.kind===`still`?draw(o,a):draw(n.wrap(o),{...a,time:n.time});if(s.lines.length===0)throw Error(`drawStripCells: rich-js strip drew no line`);return s}function renderStripCells(e,t){return encodeAnsi(drawStripCells(e,t).lines,t.colorCompatibility)}const TERMINALS={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`}}},row=e=>TERMINALS[e];function isBundling(e){return row(e).glyphs.kind===`bundled`}function isConfigured(e){return row(e).glyphs.kind===`configured`}const terminalLabel=e=>row(e).label,ITERM_POWERLINE=[{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 itermDrawsItself(e,t){let n=t.codePointAt(0);return ITERM_POWERLINE.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&releasedSince(e,t)===!0)}const NAMES=Object.keys(TERMINALS);function release$1(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function releasedSince(e,t){let n=release$1(e),r=release$1(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 fromXtversion(e){for(let t of NAMES){let n=row(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 fromTerm(e){let t=NAMES.find(t=>row(t).term===e);return t===void 0?null:{name:t,version:null}}function identifyInTmux(e){let t=fromXtversion(e.termtype)??fromTerm(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 identifyFromEnv(e){let t=e.TERM_PROGRAM,n=NAMES.find(e=>row(e).program===t),r=n===void 0?fromTerm(e.TERM):{name:n,version:row(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 sightingOf(e){switch(e.kind){case`known`:return terminalLabel(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function identifiedAs(e){switch(e.kind){case`known`:return terminalLabel(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function linkSupport({name:e,version:t}){let n=row(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=releasedSince(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const LINK_TERMINALS=NAMES.filter(e=>row(e).links!==null).map(terminalLabel).join(`, `);function statusLineOf(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(!isJsonObject(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||!isJsonObject(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function envVarOf(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 UNWRITTEN_SCOPES=[`managed`,`project`],doctorWrites=e=>!UNWRITTEN_SCOPES.includes(e.scope),ENV_FIX_FILE={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:projectLocalSettingsFile(t.projectDir)}),user:e=>({scope:`user`,path:e})},GLYPH_MARKS=[`drawn`,`boxes`],TRANSCRIPT_WINDOW_BYTES=1024*1024,whoseWidth=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function describeFix(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 problemsVerdict(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const TMUX_TRUECOLOR_VAR=TMUX_ENV.truecolor;function ofTmuxClient(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 tmuxTruecolor={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>ofTmuxClient(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=envVarOf(t.sources,TMUX_TRUECOLOR_VAR);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:`${TMUX_TRUECOLOR_VAR} 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`,TMUX_TRUECOLOR_VAR],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=ENV_FIX_FILE[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 ${TMUX_TRUECOLOR_VAR} to "1" there`}:o(s)})},utf8={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>ofTmuxClient(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"})},termWidth={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:`${whoseWidth(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 ${whoseWidth(e.value.of)} measured`}},UNUSED={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},NAMED_BY={argument:`command argument`,environment:`$${CONFIG_ENV}`,unknown:`source unknown`};function judgedConfig({target:e,layers:t}){return e.source===`search`?t.length===0?chainName(t):`${chainName(t)} (searched)`:`${e.path} (${NAMED_BY[e.source]})`}function configProblems(e){switch(e.kind){case`failed`:{let t=[...e.error.split(`
|
|
59
|
+
`).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}" ${UNUSED[e]}`)]}}const config={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{let t=judgedConfig(e),n=problemsVerdict(configProblems(e));return n.ok?{ok:!0,note:t}:{...n,reason:`${t}: ${n.reason}`}}},REINSTALL="re-run `cc-candybar install`";function handlerAppProblems(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:// — ${REINSTALL}`];let{app:t,forwarder:n}=e.value;return n?[]:[`${t} opens cc-candybar://, but it is not the forwarder app \`cc-candybar install\` builds — ${REINSTALL}`]}const urlHandler={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.delivery.kind===`forwarder`?{ok:!0}:{ok:!1,reason:`the link was delivered by a click request (\`cc-candybar url-handle\`), not the forwarder app — ${REINSTALL}`};case`lost`:return problemsVerdict([...handlerAppProblems(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}`])}}},RECENT_CLIENT_S=300;function clientStanding({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 remedy(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${LANE_NAMES.join(`|`)}>\``:e.checkout===null?REINSTALL:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function installProblems(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 — ${remedy(e,`native`)}`];let{bundle:i,source:a}=clientStanding(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} — ${remedy(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 — ${remedy(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 noRenderOf=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)`},install={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`:`${noRenderOf(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:problemsVerdict([...new Set(i.flatMap(e=>installProblems(n,r,e)))])}};function unreadPostMortems({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||laterIdentity(e.identity,t.value.through)):[]}function otherDaemons(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const daemon={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`?otherDaemons(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return problemsVerdict([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=unreadPostMortems(e.value,n),u=problemsVerdict([...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 ${mb(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 ${mb(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&approachingLimit(o.charge.bytes,s)?[`the daemon holds ${chargeWords(o.charge)} of its ${mb(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}}}},CLICK_TO_SEE=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function drawsLinks(e,t){let n=sightingOf(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?linkSupport(e.terminal):{kind:`unknown`}}function linkProblems({identified:e,tmuxClient:t},n){let r=identifiedAs(e),i=drawsLinks(e,n),a=sightingOf(e)===null?CLICK_TO_SEE:`${CLICK_TO_SEE}, 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: ${LINK_TERMINALS}`];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 links={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 problemsVerdict(linkProblems(t,n))}}},EFFECT_REFRESH_INTERVAL=1,refreshedFrames=e=>e.filter(e=>e.role===`statusline`),effectRefresh={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})=>chainVerdict(e,barsSeen(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:unknownMotion(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:noRenderOf(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}}},barsSeen=e=>{let t=refreshedFrames(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, a placement with an effect of its own that is not drawn now, or a moving bar handed off to another lane, which comes back here when the handoff ends)`}: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`}},unknownMotion=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function chainVerdict(e,t){let n=statusLineOf(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 unknownMotion(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 doctorWrites(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 codePoints=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function terminalCalled(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return identifiedAs(e);case`bundling`:case`unread`:case`configured`:return[terminalLabel(e.name),e.version].filter(e=>e!==null).join(` `)}}function sightedIn(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return sightingOf(e);case`bundling`:case`unread`:return terminalLabel(e.name);case`configured`:{let t=terminalLabel(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 glyphSighting(e){let t=sightedIn(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${codePoints(e.glyphs)}`}}const NERD_FONT_CHECK=`nerdFont`,nerdFont={name:NERD_FONT_CHECK,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=glyphSighting(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=terminalCalled(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 ${codePoints(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=TERMINALS[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:releasedSince(i.version,e);if(t===!0)return{ok:!0};let n=terminalLabel(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 ${codePoints(n)} — set a Nerd Font as its font`)}}}};function named$1(e){return e.join(`, `)}function optOut(e){return`or set missingData: "ignore" on ${named$1(e)}`}function pullRequestProblems(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${named$1(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`?[`${named$1(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${optOut(t)}`]:[`${named$1(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${optOut(t)}`]}function rateLimitProblems(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${named$1(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${named$1(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`:`${named$1(n)}: ${noRenderOf(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`)?[`${named$1(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${named$1(n)}`]:[]}const segmentData={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>problemsVerdict([...pullRequestProblems(e.pullRequests),...rateLimitProblems(e.rateLimits,t)])};function transcriptProblems({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 ${TRANSCRIPT_WINDOW_BYTES/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const sessionData={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`:`${noRenderOf(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:problemsVerdict(e.value.flatMap(transcriptProblems))},CHECKS=[config,install,daemon,urlHandler,links,tmuxTruecolor,utf8,termWidth,effectRefresh,nerdFont,segmentData,sessionData],MARKED_CHECKS=CHECKS.filter(e=>e.takesMark);function runDoctor(e){return CHECKS.map(t=>({check:t,verdict:t.probe(e)}))}function checkByName(e){return CHECKS.find(t=>t.name===e)}const scopeOf$2=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},inScope=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),ownProject=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=inScope(e,t);return r===void 0?n:r.projectDir},barsOf=(e,t)=>inScope(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r})),NONCE=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function parseProbeNonce(e){return NONCE.test(e)?e:null}function clickArrived(e){switch(e.via){case`link`:return{kind:`arrived`,delivery:e.delivery};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}function sessionWidth(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}}}}function parseClick(e,t,n){if(e.startsWith(DOCTOR_PROBE_PREFIX)){let n=parseProbeNonce(e.slice(DOCTOR_PROBE_PREFIX.length));return n===null?{kind:`refused`,problem:`the probe link carries no probe nonce`}:{kind:`probe`,nonce:n,delivery:t}}if(e.startsWith(STATUS_LINE_CLICK_PREFIX))return t.kind===`cli`?{kind:`status-line`,value:e.slice(STATUS_LINE_CLICK_PREFIX.length)}:{kind:`refused`,problem:`a status-line click comes only from tmux's own binding`};if(!isBarLink(e))return{kind:`refused`,problem:`expected a ${URL_SCHEME$1}:// link, got: ${e}`};let r=openClick(e,n);return r.kind===`link`?{...r,delivery:t}:r}function openClick(e,t){let n=t.openLink(e);if(n.kind===`failed`)return{kind:`refused`,problem:n.reason};let r=parseHandlerUrl(n.value);return r.ok?{kind:`link`,verb:r.verb,value:r.value,link:n.value}:{kind:`refused`,problem:r.problem}}const DIRECTIONS=[`vertical`,`horizontal`],AXIS_OF={vertical:`row`,horizontal:`cell`};function placementId(e){return e.id??e.name}function placementIds(e){return[...walkNodes(e)].flatMap(e=>e.kind===`segment`?[placementId(e)]:[])}function freePlacementId(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function mapOpens(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*walkNodes(e){yield e;for(let t of childrenOf(e))yield*walkNodes(t)}const childPath=(e,t)=>`${e}.children[${t}]`,bodyPath=e=>`${e}.opens.body`;function*walkNodePaths(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*walkNodePaths(r,childPath(t,n));else e.opens!==void 0&&(yield*walkNodePaths(e.opens.body,bodyPath(t)))}function childrenOf(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}function parseArm(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const CACHE_KEYS=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function hasCacheField(e){return e.kind===`file`||e.kind===`shell`}function mapVariableTemplates(e,t){let n=e.kind===`template`?{...e,template:t(e.template,`template`)}:e;return hasCacheField(n)&&`key`in n.cache?{...n,cache:{...n.cache,key:t(n.cache.key,`cache.key`)}}:n}function variableTemplates(e){let t=[];return mapVariableTemplates(e,(e,n)=>(t.push([n,e]),e)),t}const MISSING_DATA=[`fail`,`ignore`];function missingDataOf(e){return e.missingData??`fail`}function*stateVarDecls(e){for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&(yield[t,n]);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&(yield[`${t}.${e}`,r])}const THEME_SETTING=`theme`,EFFECT_SETTING=`effect`,IMPLIED_SETTINGS=[THEME_SETTING,EFFECT_SETTING];function settingsOf(e){return{...e.settings,[THEME_SETTING]:{label:THEME_SETTING,domain:`theme`,default:e.palette??`bar`},[EFFECT_SETTING]:{label:EFFECT_SETTING,domain:PLACEMENT_EFFECTS,default:`bar`}}}function rangeOf$1(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function settingOrderProblems(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=rangeOf$1(r)?.atLeast;if(i===void 0)return[];let a=t[n],o=t[i];return a>=o?[]:[{setting:n,message:`"${n}" (${a}) is below "${i}" (${o}) — ${r.label} must be at least ${e[i].label}`}]})}function inSettingDomain(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&isPlacementThemeName(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function settingSpelling(e){return String(e)}function parseSettingSpelling(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return parseSessionInt(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return inSettingDomain(e,r)?r:void 0}function placementSetting(e,t,n,r){let i=e.settings?.[t]??n.default,a=e.drafts?.[t],o=a===void 0?null:r(a);return(o===null?void 0:parseSettingSpelling(n,o))??i}function describeSettingDomain(e){let{domain:t}=e;return t===`bool`?`true or false`:t===`theme`?`"bar" (the bar's own theme) or an installed theme name`:`min`in t?`an integer from ${t.min} to ${t.max}`:`one of ${t.map(e=>JSON.stringify(e)).join(`, `)}`}const JUSTIFY_MODES=[`left`,`center`,`right`],TRUNCATE_MODES=[`right`,`left`,`middle`],ROW_NAME_RE=/^[A-Za-z_][A-Za-z0-9_]*$/;function positionalRowName(e){return`#${e+1}`}const EMPTY_ROWS={rows:{}};function isRowsFragment(e){return`rows`in e}function positionalRows(e){return Object.fromEntries(e.map((e,t)=>[positionalRowName(t),e]))}function rootOf(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:positionalRows(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:positionalRows([n])}}function rootNode(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function fragmentNode(e){return isRowsFragment(e)?rootNode(e):e}function*fragmentNodePaths(e,t){if(!isRowsFragment(e)){yield*walkNodePaths(e,t);return}yield[rootNode(e),t];for(let[n,r]of Object.entries(e.rows))yield*walkNodePaths(r,`${t}.rows.${n}`)}function mergeRoot(e,t){return isRowsFragment(e)?{...t,...e,rows:{...t.rows,...e.rows}}:rootOf(e)}function insertCells(e,t){return t.reduce((e,t)=>{let n=t.id??t.seg,r=[...walkNodes(rootNode(e.root))].flatMap(e=>e.kind===`segment`?[e]:[]);if(r.some(e=>e.name===t.seg&&(t.id===void 0||placementId(e)===t.id)))return e;let i=r.find(e=>placementId(e)===n);if(i!==void 0)return refuse$1(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,besideRow(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]))}}:refuse$1(e,t,`${t.relation} "${t.anchor}", but there is no placement "${t.anchor}"`)},{root:e,unplaced:[]})}function refuse$1(e,t,n){return{...e,unplaced:[...e.unplaced,{cell:t,reason:n}]}}function besideRow(e,t,n,r){if(e.kind===`segment`&&placementId(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`?beside(e,t,n,r):besideInBody(e,t,n,r)}function beside(e,t,n,r){let i=e.children.findIndex(e=>e.kind===`segment`&&placementId(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`?beside(a,t,n,r):besideInBody(a,t,n,r);if(o!==null)return{...e,children:e.children.map((e,t)=>t===i?o:e)}}return null}function besideInBody(e,t,n,r){let i=!1,a=mapOpens(e,e=>{let a=beside(e,t,n,r);return i=a!==null,a??e});return i?a:null}function restages(e){if(!isRowsFragment(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const PRESET_FLOOR=`default`,FLOOR_FRAGMENT={};function presetNames(e){return[...new Set([PRESET_FLOOR,...Object.keys(e)])]}function effectivePresetName(e,t,n){return effectiveMemberName(void 0,e,t,PRESET_FLOOR,n)}function presetByName(e,t){let n={[PRESET_FLOOR]:FLOOR_FRAGMENT,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${PRESET_FLOOR}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function presetRoot(e,t){let n=presetByName(e.presets,t).root??EMPTY_ROWS;return{node:rootNode(mergeRoot(n,e.root)),path:restages(n)?`presets.${t}.root`:`root`}}function placeInserts(e,t,n){if(t.length===0)return{config:e,notices:[]};let r=insertCells(e.root,t),i=Object.entries(e.presets).filter(([,e])=>restages(e.root??EMPTY_ROWS)).map(([n,r])=>({name:n,preset:r,...insertCells(mergeRoot(r.root??EMPTY_ROWS,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:rootNode(n)}]))}},notices:[...a].flatMap(([e,t])=>[...t].map(([t,n])=>insertNotice(e,`${t} (in ${n.join(`, `)})`)))}}function insertNotice(e,t){return`${e.by.file}: ${e.by.entry} places "${e.seg}" ${t}`}function presetGlobals(e,t){return{...e.globals,...presetByName(e.presets,t).globals}}const PLUGIN_SCOPES=[`plugins`,`repo`];function pluginNs({scope:e,name:t}){return`${e}.${t}`}function ownedBy(e){return t=>t===e||t.startsWith(`${e}.`)}const SELF=`self`;function scopeOf$1(e){return PLUGIN_SCOPES.find(t=>e===t||e.startsWith(`${t}.`))}function otherScopeHint(e,t){let n=scopeOf$1(e);if(n===void 0||n===e)return``;let r=PLUGIN_SCOPES.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 STRING_LITERAL_RE=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*templateBlocks(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 PATH=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,OPERAND_RE=RegExp(`^(?:(\\$)(?:\\.(${PATH}))?|\\.(${PATH})?)(?=[\\s)]|$)`);function operandAt(e,t,n){let r=OPERAND_RE.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 KEYWORD_RE=/^(\w+)\b\s*([\s\S]*)$/;function*scopedBlocks(e,t){let n=[t];for(let r of templateBlocks(e)){let e=r.text.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=KEYWORD_RE.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:operandAt(i[1],s,t);continue}yield{code:e,dot:o,block:r},i===`if`&&n.push(o),i===`with`&&n.push(operandAt(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const TEMPLATE_KEYWORD_RE=/(?<![.$])\btemplate\s+$/;function*helperCalls(e,t,n){let r=0;for(let i of[...e.matchAll(STRING_LITERAL_RE)]){let a=i.index+i[0].length;TEMPLATE_KEYWORD_RE.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:operandAt(e.slice(a),t,n),index:i.index}),r=a}}function*callGraphBlocks(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...scopedBlocks(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...helperCalls(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 perTemplate(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const WALKS=new WeakMap;function callGraph(e,t){let n=WALKS.get(t);return n===void 0&&(n=perTemplate(e=>[...callGraphBlocks(e,t)]),WALKS.set(t,n)),n(e)}const REF_RE=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${PATH})`,`g`);function*dotRefs({code:e,dot:t,root:n}){let r=e.replace(STRING_LITERAL_RE,``);for(let e of[...r.matchAll(REF_RE)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function templateReads(e,t){let n=new Map;for(let r of callGraph(e,t))for(let e of dotRefs(r))n.has(e)||n.set(e,r.via);return n}const BINDING_KEYWORD_RE=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,NAME_ARGS={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*actionBindings(e){let t=0,n=0,r=`action`;for(let i of[...e.matchAll(STRING_LITERAL_RE)]){let a=e.slice(t,i.index),o=BINDING_KEYWORD_RE.exec(a);o===null?a.trim()!==``&&(n=0):(n=NAME_ARGS[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 templateActionRefs(e,t){let n=new Map;for(let{code:r,via:i}of callGraph(e,t))for(let{name:e,site:t}of actionBindings(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}const namesTaking=e=>Object.keys(NAME_ARGS).filter(t=>NAME_ARGS[t]>=e).join(`|`),COMPUTED_BINDING_RE=RegExp(`(?<![\\w.$])(?:(?:${namesTaking(1)})\\s+|(?:${namesTaking(2)})\\s+""\\s+)(?=[^\\s"\`)|}])`);function bindsComputedAction(e,t){for(let{code:n}of callGraph(e,t))if(COMPUTED_BINDING_RE.test(n.replace(STRING_LITERAL_RE,`""`)))return!0;return!1}const BARE_NAME_RE=/(?<![\w.$])[A-Za-z_]\w*/g;function templateFunctions(e,t){let n=new Set;for(let{code:r}of callGraph(e,t))for(let[e]of r.replace(STRING_LITERAL_RE,``).matchAll(BARE_NAME_RE))n.add(e);return n}function templateHelperRefs(e,t){return new Set([...templateHelperCalls(e,t)].filter(e=>Object.hasOwn(t,e)))}function templateHelperCalls(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of callGraph(e,t))for(let{name:e}of helperCalls(r,i,a))n.add(e);return n}const SELF_REF_RE=e=>RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.${e}(?![A-Za-z0-9_])`,`g`);function bindSelf(e,t,n){let r=SELF_REF_RE(t),i=ownedBy(t),a=[];for(let{dot:t,block:n}of scopedBlocks(e,``)){let e=n.text.replace(STRING_LITERAL_RE,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[...helperCalls(n.text,t,``),...actionBindings(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*declarationsAt(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*declaredVariables(e){for(let[t,n]of declarationsAt(e))yield[t,n]}function variableRead(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 refResolves(e,t){return variableRead(e,t.names).some(n=>!e.startsWith(`${n}.`)||t.documents.has(n))}function templateScopeOf(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),isDocumentDecl(r)&&n.add(e)};for(let[t,n]of declaredVariables(e))r(t,n);return{names:t,documents:n,helpers:e.helpers}}function isDocumentDecl(e){return e.kind===`dropped`||e.kind===`source`||(e.kind===`shell`||e.kind===`file`)&&parseArm(e.parse)===`json`}const LAYER_ROLES=[`user`,`project`,`local`];function layerFlags(e){return Object.fromEntries(LAYER_ROLES.map(t=>[t,e.includes(t)]))}function layerRoleOf(e){return LAYER_ROLES.includes(e)?e:null}const ACTION_KEYS=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`slash`,`run`,`do`],LAYER_CHOICES={persist:LAYER_ROLES,reset:LAYER_ROLES,preset:LAYER_ROLES,themeDefault:LAYER_ROLES,save:[...LAYER_ROLES,`ask`]};function runDeclaration(e){return JSON.stringify([e.run,Object.entries(e.env),e.cwd,e.refreshes])}function*actionTemplates(e){let t=[];mapActionTemplates(e,(e,n)=>(t.push([n,e]),e)),yield*t}function mapActionTemplates(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 actionBindsTemplateValue(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function valueReads({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),[...[...actionTemplates(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=perTemplate(e=>{let i=bindsComputedAction(e,t)?Object.keys(n):templateActionRefs(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]}),a=perTemplate(n=>i(n).flatMap(n=>[...templateReads(n,t).keys()].map(t=>({path:t,reaches:variableRead(t,e)}))));return{ofTemplate:a,calls:perTemplate(e=>new Set(i(e).flatMap(e=>[...templateFunctions(e,t)]))),ofVariable:t=>[...variableTemplates(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...hasCacheField(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function payloadPathOf(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}const FOLDS$1=new WeakMap;function valueReadsOf(e){let t=FOLDS$1.get(e);return t===void 0&&(t=valueReads({names:new Set([...declaredVariables(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),FOLDS$1.set(e,t)),t}function trackingOf(e,t){return e.kind===`absent`?ok$1(`none`):e.kind===`failed`?e:t.kind===`failed`?t:ok$1(t.kind===`ok`?`tracked`:`gone`)}const PR_FIELDS={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function prOfHead(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?failed$2(`HEAD: ${t.reason}`,t.failedAt):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const GITHUB_PR_STATES={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},GITLAB_MR_STATES={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function prStateOf(e,t,n){return Object.hasOwn(t,n)?ok$1(t[n]):failed$2(`${e}: unknown state ${JSON.stringify(n)}`,`parse`)}const READ_FIELD_NAMES={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function gitInfoFailures(e){return Object.keys(READ_FIELD_NAMES).flatMap(t=>{let n=e[t];return n.kind===`failed`?[`git.${READ_FIELD_NAMES[t]}: ${n.reason}`]:[]})}function classify(e,t,n){return t.ok?ok$1(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?ABSENT$2:failed$2(launchFailure(e,t),`read`)}function launchFailure(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??firstLine(t.stderr)].filter(Boolean).join(`, `)}`}function firstLine(e){return e.trim().split(`
|
|
60
60
|
`,1)[0]??``}const FORGE_CLI={github:`gh`,gitlab:`glab`};function isMissingCommand(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const DOS_DRIVE_PATH=/^[A-Za-z]:[\\/]/;function parseRemoteRef(e){let t=e.trim();if(DOS_DRIVE_PATH.test(t))return null;let n=t.match(/^(?:[^@/]+@)?(\[[^\]]+\]):(.*)$/)??t.match(/^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.*)$/),r=n?`ssh://${n[1]}/${n[2].replace(/^\/+/,``)}`:t,i;try{i=new URL(r)}catch{return null}return{scheme:i.protocol.replace(/:$/,``),host:i.hostname.toLowerCase(),port:i.port,path:i.pathname.replace(/^\/+/,``).replace(/\/+$/,``)}}function remoteHost(e){return parseRemoteRef(e)?.host||null}function detectForge(e){let t=remoteHost(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const REMOTES_ARGS=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function remotesOf(e){let t=classify(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?parseRemotes(t.value):[]}}function parseRemotes(e){let t=new Map;for(let n of e.split(`
|
|
61
61
|
`)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function identifyingUrl(e){return e.urls.find(e=>remoteWebUrl(e)!==null)??e.urls[0]??null}function pickRepoRemote(e){return e.find(e=>e.name===`origin`)??e[0]??null}function repoRemoteUrl(e){let t=pickRepoRemote(e);return t?identifyingUrl(t):null}function forgeRemoteUrl(e){let t=pickRepoRemote(e);return t?t.urls.find(e=>detectForge(e)!==null)??identifyingUrl(t):null}function repoNameFromUrl(e){let t=(parseRemoteRef(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function remoteWebUrl(e){let t=parseRemoteRef(e);if(!t)return null;let n=t.scheme===`https`?{scheme:`https`,port:t.port}:t.scheme===`http`?{scheme:`http`,port:t.port}:t.scheme===`ssh`||t.scheme===`git`?{scheme:`https`,port:``}:null;if(!n||!t.host)return null;let r=t.path.replace(/\.git$/,``);if(!r)return null;let i=n.port?`${t.host}:${n.port}`:t.host;return`${n.scheme}://${i}/${r}`}function repoWebUrl(e){let t=repoRemoteUrl(e);return t===null?null:remoteWebUrl(t)}function classifyForgePr(e,t,n,r){return t.ok?r(t.stdout):isMissingCommand(t)||t.reason===`non-zero`&&n.test(t.stderr)?ABSENT$2:failed$2(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??firstLine(t.stderr)].filter(Boolean).join(`, `)}`,`read`)}function isRecord$1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function parseStatusV2(e){let t=`detached`,n=ABSENT$2,r=ABSENT$2,i=ABSENT$2,a=0,o=0,s=0,c=0;for(let l of e.split(`
|
|
62
62
|
`)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?ABSENT$2:ok$1(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=ok$1(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=ok$1({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function parseGithubPr(e){let t;try{t=JSON.parse(e)}catch(e){return failed$2(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`,`parse`)}if(!isRecord$1(t))return failed$2(`gh pr view: JSON is not an object`,`parse`);let{number:n,state:r,url:i,headRefOid:a}=t;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return failed$2(`gh pr view: missing number/state/url/headRefOid`,`parse`);let o=prStateOf(`gh pr view`,GITHUB_PR_STATES,r);return o.kind===`ok`?ok$1({number:n,state:o.value,url:i,head:a}):o}function parseGitlabMr(e){let t;try{t=JSON.parse(e)}catch(e){return failed$2(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`,`parse`)}if(!isRecord$1(t))return failed$2(`glab mr view: JSON is not an object`,`parse`);let n=t.iid,r=t.state,i=t.web_url,a=t.sha;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return failed$2(`glab mr view: missing iid/state/web_url/sha`,`parse`);let o=prStateOf(`glab mr view`,GITLAB_MR_STATES,r);return o.kind===`ok`?ok$1({number:n,state:o.value,url:i,head:a}):o}const under$1=(e,t)=>[...e].some(e=>e===t||e.startsWith(`${t}.`)),READS={pullRequests:e=>Object.keys(PR_FIELDS).some(t=>e.has(`git.${t}`)),rateLimits:e=>under$1(e,`block`)||under$1(e,`weekly`)};function segmentTemplates(e,t){let n=e.segments[t];return n?[...[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]),...Object.values(n.partials??{})]:[]}function inputClosure(e,t){let n=valueReadsOf(e),r=new Map(declaredVariables(e)),i=t.flatMap(e=>n.ofTemplate(e).flatMap(({reaches:e})=>e)),a=new Set,o=new Set;for(;i.length>0;){let e=i.pop();if(a.has(e))continue;a.add(e);let t=r.get(e),s=payloadPathOf(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function dataNeeds(e,t){let n=new Map;for(let r of walkNodes(presetRoot(e,t).node)){if(r.kind!==`segment`)continue;let e=n.get(r.name)??[];r.when&&e.push(r.when),n.set(r.name,e)}let r=[...n.keys()].filter(t=>missingDataOf(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,inputClosure(e,[...segmentTemplates(e,t),...n.get(t)])])),a=e=>r.filter(t=>READS[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}var TemplateError=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?buildSnippet(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}},ParseError=class extends TemplateError{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},EvalError=class extends TemplateError{name=`EvalError`;kind=`EvalError`},FuncNotFoundError=class extends EvalError{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=nearestMatches(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}},ArgCountError=class extends EvalError{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}},TypeMismatchError=class extends EvalError{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}},NotIntegerError=class extends TypeMismatchError{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)}`}},MissingFieldError=class extends EvalError{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},FailError=class extends EvalError{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function buildSnippet(e,t){let n=e.split(`
|
|
@@ -75,7 +75,7 @@ import{createRequire}from"node:module";import process$1 from"node:process";impor
|
|
|
75
75
|
|
|
76
76
|
`)}},DroppedPlacements=class extends Error{constructor(e){super(e.map(e=>e.message).join(`
|
|
77
77
|
`)),this.errors=e,this.name=`DroppedPlacements`}};function findKeyLine(e,t){return keyLocator(e)(t)}function keyLocator(e){let t,n=()=>(t??={node:parseOrUndefined(e)},t.node);return t=>keyLine(e,n,t)}function parseOrUndefined(e){try{return parseDocument(e)}catch(e){if(e instanceof Json5EditError)return;throw e}}function keyLine(e,t,n){let r=n.some(e=>/^\d+$/.test(e))?elementPathLine(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=findKeyOccurrence(e,i,t);if(n===-1)return a===void 0?void 0:lineFromOffset(e,a);i=n,a=n}return a===void 0?void 0:lineFromOffset(e,a)}function elementPathLine(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:entryOf$2(r,e)?.value;if(n===void 0)break;a||=t,r=n,i=n}return i===void 0||!a?void 0:lineFromOffset(e,i.span.start)}function findKeyOccurrence(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 lineFromOffset(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function editabilityNotice(e,t){try{return parseDocument(t),null}catch(n){if(!(n instanceof Json5EditError))throw n;return`${e}:${lineFromOffset(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function formatIssues(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(`
|
|
78
|
-
`)}function requireString(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 ${describeType(i)}`,line:findKeyLine(e.source,[...t.split(`.`),r])}),null)}function optionalTypedDefault(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 ${describeType(i)}`,line:findKeyLine(e.source,[...t.split(`.`),`default`])});return}return i}}function optionalStringField(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 ${describeType(i)}`,line:findKeyLine(e.source,[...t.split(`.`),r])});return}return i}}function validatePaletteName(e,t,n){let r=optionalStringField(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${retiredThemeNote(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:findKeyLine(e.source,[...t.split(`.`),`palette`])});return}return r}}function optionalEnum(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 ${describeValue(a)}`,line:findKeyLine(e.source,[...t.split(`.`),r])});return}return a}}function isPlainObject$2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function describeType(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function describeValue(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function record(e,t,n,r){return isPlainObject$2(r)?(rejectUnknownKeys(e,n,r,t.noun,new Set(Object.keys(t.fields)),refuseRemoved(e,t.removed??{},n,r)),fields(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${describeType(r)}`,line:findKeyLine(e.source,n.split(`.`))}),null)}function refuseRemoved(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)reject(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function fields(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 EMPTY_PATHS=new Set;function rejectUnknownKeys(e,t,n,r,i,a=EMPTY_PATHS){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:findKeyLine(e.source,[...t.split(`.`),o])})}function reject(e,t,n){return e.issues.push({path:t,message:n,line:findKeyLine(e.source,t.split(`.`))}),null}function oneOfPresent(e,t,n,r){if(!isPlainObject$2(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${describeType(r)}`,line:findKeyLine(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:findKeyLine(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:findKeyLine(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:findKeyLine(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function taggedUnion(e,t,n,r){if(!isPlainObject$2(r))return e.issues.push({path:n,message:`${n} must be an object, got ${describeType(r)}`,line:findKeyLine(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 ${describeType(i)}`,line:findKeyLine(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:findKeyLine(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 rejectUnknownKeys(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function armFacets(e,t,n){return{json:withConst(objectJson(n),e,t),keys:new Set([e,...Object.keys(n)])}}function lazy(e){return(...t)=>e()(...t)}function refine(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:findKeyLine(n.source,o.split(`.`))}),null}return a}}function optionalStringSpec(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>optionalStringField(e,t,r,n)}}function optionalBooleanSpec(){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 ${describeType(i)}`,line:findKeyLine(e.source,[n])});return}return i}}}}function optionalIntSpec(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 ${describeValue(o)}`,line:findKeyLine(e.source,[i])});return}return o}}}}function optionalNumberSpec(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 ${describeValue(a)}`,line:findKeyLine(e.source,[r])});return}return a}}}}function paletteSpec(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>validatePaletteName(e,t,r)}}function requireStringSpec(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>requireString(e,t,r,n)??void 0}}function optionalEnumSpec(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>optionalEnum(t,n,i,r,e)}}function objectJson(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 recordJson(e){return objectJson(e.fields)}function withConst(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function taggedUnionJson(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function oneOfPresentJson(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const control=(e,t,{previews:n=[],shown:r=`true`}={})=>({label:e,place:t,previews:n,shown:r}),enumValues=(e,t,n={})=>({spec:optionalEnumSpec(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e,...n}}}),markTrials=e=>t=>e.includes(t)?`🧪 ${t}`:t,boolValues={spec:optionalBooleanSpec(),domain:`bool`,parse:parseSessionBoolean},intValues=e=>({spec:optionalIntSpec(e),domain:e,parse:t=>parseSessionInt(t,e)});function enumSetting(e,t,n,r={}){return{kind:`session`,...enumValues(e,r.optionDomain,{library:r.library,labelOf:r.labelOf}),floor:t,control:n,themeDefault:r.themeDefault??!1}}function boolSetting(e,t){return{kind:`session`,...boolValues,floor:e,control:t,themeDefault:!1}}function intSetting(e,t,n){return{kind:`session`,...intValues(e),floor:t,control:n,themeDefault:!1}}function selection(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const text=e=>({kind:`text`,spec:e}),colorCompatibilitySpec={required:!1,json:{enum:[...COLOR_COMPATIBILITIES]},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: ${COLOR_COMPATIBILITIES.join(`, `)}`,line:findKeyLine(e.source,[...t.split(`.`),n])});return}return optionalEnum(e,t,r,n,COLOR_COMPATIBILITIES)}},paletteOrRuleSpec={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=optionalStringField(e,t,r,n);return isExpression(i)?i:validatePaletteName(e,t,r)}},effectOrRuleSpec={required:!1,json:{anyOf:[{enum:[...EFFECT_NAMES]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&isExpression(i)?i:optionalEnum(e,t,r,n,EFFECT_NAMES)}},MENU_GLYPH=/^[^\r\n]*\S[^\r\n]*$/u,CLOSE_GLYPH=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),menuGlyphSpec={required:!1,json:{type:`string`,pattern:MENU_GLYPH.source,not:{pattern:CLOSE_GLYPH.source}},parse:(e,t,n,r)=>{let i=optionalStringField(e,t,r,n);if(i===void 0||MENU_GLYPH.test(i)&&!CLOSE_GLYPH.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:findKeyLine(e.source,[...t.split(`.`),n])})}},LANE_ROWS=Object.fromEntries(TOGGLED_LANES.map(e=>[LANES[e].switch.setting,boolSetting(!1,control(LANES[e].label,`toggles`))])),RENDERER_DESCRIPTIONS={claude:`Claude Code's status line`,tmux:`the tmux status line, while this pane is shown`},RENDERER_LIBRARY={groups:[{id:`renderer`,label:`draw the bar in`}],entry:e=>({group:`renderer`,description:RENDERER_DESCRIPTIONS[e]})},GLOBAL_FIELDS={palette:selection(`theme`,paletteOrRuleSpec,{themes:`themes`},control(`🎨 theme`,`door`)),preset:selection(`preset`,optionalStringSpec(),{from:`presets`},control(`▦ preset`,`door`,{previews:[`layout`,`presetDelete`]})),style:selection(`style`,optionalStringSpec(),{from:`styles`},control(`◐ style`,`gear`,{previews:[`palette`]}),{themeDefault:!0}),effect:selection(`effect`,effectOrRuleSpec,{from:EFFECT_NAMES},control(`✨ effect`,`look`)),endcaps:enumSetting(ENDCAPS_SHAPES,`powerline`,control(`✦ endcaps`,`look`),{optionDomain:`endcaps`}),variation:enumSetting(VARIATION_NAMES,`accent`,control(`🎼 variation`,`gear`,{previews:[`layout`]}),{optionDomain:`variations`,labelOf:markTrials(TRIAL_VARIATION_NAMES),themeDefault:!0}),shade:enumSetting(SHADE_NAMES,`middle`,control(`🔆 shade`,`gear`,{previews:[`layout`]}),{optionDomain:`shades`,labelOf:markTrials(TRIAL_SHADE_NAMES),themeDefault:!0}),transitions:boolSetting(!1,control(`fade in/out`,`look`)),animationSpeed:enumSetting(ANIMATION_SPEED_NAMES,`1x`,control(`speed`,`look`)),autoWrap:boolSetting(!0,control(`wrap`,`config`)),padding:intSetting({...PADDING_RANGE,step:1},1,control(`padding`,`config`)),updateNotice:boolSetting(!0,control(`update notice`,`config`)),menuTimeout:intSetting(MENU_TIMEOUT_RANGE,120,control(`menu timeout`,`config`)),renderer:enumSetting(RENDERERS$1,`claude`,control(`renderer`,`config`,{shown:IN_TMUX}),{optionDomain:`renderers`,library:RENDERER_LIBRARY}),...LANE_ROWS,colorCompatibility:{kind:`config`,...enumValues(COLOR_COMPATIBILITIES,`colorCompatibilities`),spec:colorCompatibilitySpec,floor:`truecolor`},default_empty_value:text(optionalStringSpec()),default_separator:text(optionalStringSpec()),menuGlyph:text(menuGlyphSpec)},ROWS=Object.entries(GLOBAL_FIELDS),VALUED_FIELDS=ROWS.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),CONTROLLED_FIELDS=ROWS.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),THEME_DEFAULT_FIELDS=ROWS.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),NAMED_DOMAINS=ROWS.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function valuedRow(e){return GLOBAL_FIELDS[e]}const floorOf=e=>valuedRow(e).floor;function wireKindOf(e){let t=GLOBAL_FIELDS[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const effectiveVarOf=e=>`${e}.effective`,nameOf$1=e=>{let t=GLOBAL_FIELDS[e];return t.kind===`selection`?t.sessionKey:e},SETTINGS=Object.fromEntries(CONTROLLED_FIELDS.map(e=>{let t=nameOf$1(e);return[t,{configKey:e,sessionKey:t,effectiveVar:effectiveVarOf(t),...GLOBAL_FIELDS[e].control}]})),SETTING_NAMES=Object.keys(SETTINGS),SETTING_PROJECTIONS=Object.values(SETTINGS),CONFIG_ONLY_PROJECTIONS=VALUED_FIELDS.filter(e=>GLOBAL_FIELDS[e].kind===`config`).map(e=>({configKey:e,effectiveVar:effectiveVarOf(e)})),CONFIG_ONLY_KEYS=new Set(CONFIG_ONLY_PROJECTIONS.map(e=>e.configKey)),CONFIG_KEY_TO_EFFECTIVE_VAR=new Map([...SETTING_PROJECTIONS,...CONFIG_ONLY_PROJECTIONS].map(e=>[e.configKey,e.effectiveVar])),SESSION_KEY_TO_EFFECTIVE_VAR=new Map(SETTING_PROJECTIONS.map(e=>[e.sessionKey,e.effectiveVar]));function perSetting(e){return Object.fromEntries(SETTING_NAMES.map(t=>[t,e(t)]))}const SESSION_KEY_TO_SETTING=new Map(SETTING_NAMES.map(e=>[SETTINGS[e].sessionKey,e]));function effectiveInput(e,t){let n=GLOBAL_FIELDS[e],r=wireKindOf(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 EFFECTIVE_INPUTS=Object.fromEntries([...CONFIG_KEY_TO_EFFECTIVE_VAR].map(([e,t])=>[t,effectiveInput(e,t)])),LANE_FEED_TYPES={subscribers:`number`,fps:`number`,shown:`boolean`},LANE_FEED_FIELDS=Object.keys(LANE_FEED_TYPES),TERM_COLS_FLOOR=80,PAYLOAD_INPUTS={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},"session.id":{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`},config_path:{kind:`input`,path:`configPath`,default:``},...EFFECTIVE_INPUTS,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(LANE_NAMES.flatMap(e=>LANE_FEED_FIELDS.map(t=>[laneFeedVar(e,t),{kind:`input`,path:laneFeedVar(e,t),type:LANE_FEED_TYPES[t],default:UNFOLLOWED[t]}]))),[drawingVar(`by`)]:{kind:`input`,path:drawingVar(`by`),default:ANSWERING.by},[drawingVar(`fps`)]:{kind:`input`,path:drawingVar(`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:``}},DRAW_PROJECTIONS={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 drawProjectionAt(e){let t=e.split(`.`,1)[0];return Object.hasOwn(DRAW_PROJECTIONS,t)?t:void 0}const SLOT_PATHS=Object.fromEntries(EXPRESSION_SLOTS.map(e=>[e,CONFIG_KEY_TO_EFFECTIVE_VAR.get(e)]));function slotAt(e){return EXPRESSION_SLOTS.find(t=>SLOT_PATHS[t]===e)}function reservedNamespaceOf(e){let t=ident(e);return RESERVED_NAMESPACES.find(e=>t.startsWith(ident(e)))}function reservedNamespaceCollisions(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:findKeyLine(e.source,[`root`])})}function pluginScopeCollisions(e,t,n){for(let r of[`variables`,`actions`,`helpers`,`segments`])for(let i of Object.keys(t[r]??{})){let t=scopeOf(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:findKeyLine(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=()=>({path:`segments.${r}.vars.${t}`,line:findKeyLine(e.source,[`segments`,r,`vars`,t])});if(isPayloadInput(i)){e.issues.push({...a(),message:`segment "${r}"'s var "${t}" is named "${i}", ${PAYLOAD_OWNED} — rename the var or the segment`});continue}let o=scopeOf(i);o===void 0||n.has(r)||e.issues.push({...a(),message:`segment "${r}"'s var "${t}" is named "${i}", in "${o}", the namespace plugins own — rename the var or the segment`})}}const PAYLOAD_OWNED=`supplied by the daemon's payload to every config`;function payloadDeclarationNotices(e,t,n){let r=keyLocator(t);return n.filter(isPayloadInput).map(t=>{let n=r([`variables`,t]);return`${n===void 0?e:`${e}:${n}`}: "${t}" is ${PAYLOAD_OWNED}, so this declaration is ignored — remove it`})}function isPayloadInput(e){return Object.hasOwn(PAYLOAD_INPUTS,e)}const EDIT_MODE_KEY=`edit.mode`,EDIT_CONFIGURE_KEY=`edit.configure`,EDIT_TOGGLE_ACTION=`edit.toggle`,EDIT_UNCONFIGURE_ACTION=`edit.unconfigure`,EDIT_MODE_ARRANGE=`arrange`,PLACEMENT_DRAFT_NS=`${EDIT_NS}draft.`;function configureMember(e,t){return`${e}:${t}`}const EDIT_MODE_REF={variable:EDIT_MODE_KEY,key:EDIT_MODE_KEY,member:EDIT_MODE_ARRANGE},EDIT_MODE_GATE=disclosureGate(EDIT_MODE_REF);function referencesEditToggle(e){try{return SYNTAX_ENGINE.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function fileWantsEditMode(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`&&referencesEditToggle(t))return!0}return!1}function synthesizeEditModeToggle(e,t){if(reservedNamespaceCollisions(e,t,EDIT_NS,`edit mode`),!fileWantsEditMode(t))return;let{variables:n,actions:r}=editModeArtifacts();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function editModeArtifacts(){return{variables:{[EDIT_MODE_KEY]:{...disclosureStateVar(EDIT_MODE_KEY,DISCLOSURE_CLOSED),within:[SETTINGS_REF]},[EDIT_CONFIGURE_KEY]:{...disclosureStateVar(EDIT_CONFIGURE_KEY,DISCLOSURE_CLOSED),within:[EDIT_MODE_REF]}},actions:{[EDIT_TOGGLE_ACTION]:disclosureCycleAction(EDIT_MODE_KEY,EDIT_MODE_ARRANGE),[EDIT_UNCONFIGURE_ACTION]:{set:EDIT_CONFIGURE_KEY,to:DISCLOSURE_CLOSED}}}}const baseCache=new Map;function paletteForThemeName(e){let t=basePaletteFor(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 placementPalette(e,t){return e===`bar`?t:paletteForThemeName(e)}function basePaletteFor(e){let t=baseCache.get(e);if(t!==void 0)return t;let n=getThemePalette(e);return n===null?null:(baseCache.set(e,n),n)}function transposedPalette(e,t){return TRANSPOSED(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>transposePalette(e,t))}const TRANSPOSED=memoPerPalette();function namedTheme(e){let t=basePaletteFor(e);return t===null?null:{kind:`decided`,name:e,value:t}}function decideThemeName(e,t,n){let r=namedTheme(e);return r===null?(n(ruleFloorMessage(t,`palette`,`"${e}" names no installed theme${retiredThemeNote(e)}`)),themeFloor()):r}function resolveThemeSelection(e,t,n){return resolveSelection(e,t,n,themeFloor(),namedTheme)}function themeFloor(){return{kind:`decided`,name:THEME_FLOOR,value:paletteForThemeName(THEME_FLOOR)}}const NO_THEME_DEFAULT=Object.freeze({});function themeDefaultsOf(e,t){return e.kind===`decided`?t[e.name]??NO_THEME_DEFAULT:NO_THEME_DEFAULT}function underThemeDefault(e,t){return{...e,...Object.fromEntries(THEME_DEFAULT_FIELDS.map(n=>[n,e[n]??t[n]]))}}const laneSwitches=(e,t)=>perLane(n=>{let{setting:r,on:i,inTmux:a}=LANES[n].switch;return e[r]===i&&(t||!a)});function resolveValued(e,t,n,r){let i=valuedRow(e);return effectiveGlobal(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function presetOf(e,t){return effectivePresetName(t(`preset`),e.globals.preset,e.presets)}function resolveEffectiveGlobals(e,t,n){let r=presetOf(e,t),i=presetGlobals(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=resolveThemeSelection(a.palette,t(`theme`),i.palette),s=underThemeDefault(i,themeDefaultsOf(o,e.themeDefaults));return{...Object.fromEntries(VALUED_FIELDS.map(e=>[e,resolveValued(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:resolveStyleSelection(a.style,t(`style`),s.style,e.styles),effect:resolveEffectSelection(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}const busy=e=>({kind:`busy`,what:e});var DoctorBusy=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};async function seen(e){let t=await e;if(t.kind===`busy`)throw new DoctorBusy(t.what);return t}function asked(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const readStores=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function oneAskPerClick(e){let t=new Map,n=(e,n)=>{let r=JSON.stringify(e),i=t.get(r)??n();return t.set(r,i),i};return{...e,probeTmux:t=>n([`tmux`,t],()=>e.probeTmux(t)),remoteLogin:t=>n([`remote`,t],()=>e.remoteLogin(t)),fontInUse:(t,r,i)=>n([`font`,t,r,i],()=>e.fontInUse(t,r,i))}}async function transcriptReads(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:await Promise.all([...n].map(async([t,n])=>({path:t,answered:n,read:await e.transcript(t)})))}}function configFacts(e,t){let n={layers:e.layers,target:t,warnings:e.warning===null?[]:e.warning.split(`
|
|
78
|
+
`)}function requireString(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 ${describeType(i)}`,line:findKeyLine(e.source,[...t.split(`.`),r])}),null)}function optionalTypedDefault(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 ${describeType(i)}`,line:findKeyLine(e.source,[...t.split(`.`),`default`])});return}return i}}function optionalStringField(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 ${describeType(i)}`,line:findKeyLine(e.source,[...t.split(`.`),r])});return}return i}}function validatePaletteName(e,t,n){let r=optionalStringField(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${retiredThemeNote(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:findKeyLine(e.source,[...t.split(`.`),`palette`])});return}return r}}function optionalEnum(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 ${describeValue(a)}`,line:findKeyLine(e.source,[...t.split(`.`),r])});return}return a}}function isPlainObject$2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function describeType(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function describeValue(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function record(e,t,n,r){return isPlainObject$2(r)?(rejectUnknownKeys(e,n,r,t.noun,new Set(Object.keys(t.fields)),refuseRemoved(e,t.removed??{},n,r)),fields(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${describeType(r)}`,line:findKeyLine(e.source,n.split(`.`))}),null)}function refuseRemoved(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)reject(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function fields(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 EMPTY_PATHS=new Set;function rejectUnknownKeys(e,t,n,r,i,a=EMPTY_PATHS){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:findKeyLine(e.source,[...t.split(`.`),o])})}function reject(e,t,n){return e.issues.push({path:t,message:n,line:findKeyLine(e.source,t.split(`.`))}),null}function oneOfPresent(e,t,n,r){if(!isPlainObject$2(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${describeType(r)}`,line:findKeyLine(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:findKeyLine(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:findKeyLine(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:findKeyLine(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function taggedUnion(e,t,n,r){if(!isPlainObject$2(r))return e.issues.push({path:n,message:`${n} must be an object, got ${describeType(r)}`,line:findKeyLine(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 ${describeType(i)}`,line:findKeyLine(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:findKeyLine(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 rejectUnknownKeys(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function armFacets(e,t,n){return{json:withConst(objectJson(n),e,t),keys:new Set([e,...Object.keys(n)])}}function lazy(e){return(...t)=>e()(...t)}function refine(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:findKeyLine(n.source,o.split(`.`))}),null}return a}}function optionalStringSpec(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>optionalStringField(e,t,r,n)}}function optionalBooleanSpec(){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 ${describeType(i)}`,line:findKeyLine(e.source,[n])});return}return i}}}}function optionalIntSpec(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 ${describeValue(o)}`,line:findKeyLine(e.source,[i])});return}return o}}}}function optionalNumberSpec(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 ${describeValue(a)}`,line:findKeyLine(e.source,[r])});return}return a}}}}function paletteSpec(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>validatePaletteName(e,t,r)}}function requireStringSpec(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>requireString(e,t,r,n)??void 0}}function optionalEnumSpec(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>optionalEnum(t,n,i,r,e)}}function objectJson(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 recordJson(e){return objectJson(e.fields)}function withConst(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function taggedUnionJson(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function oneOfPresentJson(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const control=(e,t,{previews:n=[],shown:r=`true`}={})=>({label:e,place:t,previews:n,shown:r}),enumValues=(e,t,n={})=>({spec:optionalEnumSpec(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e,...n}}}),markTrials=e=>t=>e.includes(t)?`🧪 ${t}`:t,boolValues={spec:optionalBooleanSpec(),domain:`bool`,parse:parseSessionBoolean},intValues=e=>({spec:optionalIntSpec(e),domain:e,parse:t=>parseSessionInt(t,e)});function enumSetting(e,t,n,r={}){return{kind:`session`,...enumValues(e,r.optionDomain,{library:r.library,labelOf:r.labelOf}),floor:t,control:n,themeDefault:r.themeDefault??!1}}function boolSetting(e,t){return{kind:`session`,...boolValues,floor:e,control:t,themeDefault:!1}}function intSetting(e,t,n){return{kind:`session`,...intValues(e),floor:t,control:n,themeDefault:!1}}function selection(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const text=e=>({kind:`text`,spec:e}),colorCompatibilitySpec={required:!1,json:{enum:[...COLOR_COMPATIBILITIES]},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: ${COLOR_COMPATIBILITIES.join(`, `)}`,line:findKeyLine(e.source,[...t.split(`.`),n])});return}return optionalEnum(e,t,r,n,COLOR_COMPATIBILITIES)}},paletteOrRuleSpec={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=optionalStringField(e,t,r,n);return isExpression(i)?i:validatePaletteName(e,t,r)}},effectOrRuleSpec={required:!1,json:{anyOf:[{enum:[...EFFECT_NAMES]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&isExpression(i)?i:optionalEnum(e,t,r,n,EFFECT_NAMES)}},MENU_GLYPH=/^[^\r\n]*\S[^\r\n]*$/u,CLOSE_GLYPH=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),menuGlyphSpec={required:!1,json:{type:`string`,pattern:MENU_GLYPH.source,not:{pattern:CLOSE_GLYPH.source}},parse:(e,t,n,r)=>{let i=optionalStringField(e,t,r,n);if(i===void 0||MENU_GLYPH.test(i)&&!CLOSE_GLYPH.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:findKeyLine(e.source,[...t.split(`.`),n])})}},LANE_ROWS=Object.fromEntries(TOGGLED_LANES.map(e=>[LANES[e].switch.setting,boolSetting(!1,control(LANES[e].label,`toggles`))])),RENDERER_DESCRIPTIONS={claude:`Claude Code's status line`,tmux:`the tmux status line, while this pane is shown`},RENDERER_LIBRARY={groups:[{id:`renderer`,label:`draw the bar in`}],entry:e=>({group:`renderer`,description:RENDERER_DESCRIPTIONS[e]})},GLOBAL_FIELDS={palette:selection(`theme`,paletteOrRuleSpec,{themes:`themes`},control(`🎨 theme`,`door`)),preset:selection(`preset`,optionalStringSpec(),{from:`presets`},control(`▦ preset`,`door`,{previews:[`layout`,`presetDelete`]})),style:selection(`style`,optionalStringSpec(),{from:`styles`},control(`◐ style`,`gear`,{previews:[`palette`]}),{themeDefault:!0}),effect:selection(`effect`,effectOrRuleSpec,{from:EFFECT_NAMES},control(`✨ effect`,`look`)),endcaps:enumSetting(ENDCAPS_SHAPES,`powerline`,control(`✦ endcaps`,`look`),{optionDomain:`endcaps`}),variation:enumSetting(VARIATION_NAMES,`accent`,control(`🎼 variation`,`gear`,{previews:[`layout`]}),{optionDomain:`variations`,labelOf:markTrials(TRIAL_VARIATION_NAMES),themeDefault:!0}),shade:enumSetting(SHADE_NAMES,`middle`,control(`🔆 shade`,`gear`,{previews:[`layout`]}),{optionDomain:`shades`,labelOf:markTrials(TRIAL_SHADE_NAMES),themeDefault:!0}),transitions:boolSetting(!1,control(`fade in/out`,`look`)),animationSpeed:enumSetting(ANIMATION_SPEED_NAMES,`1x`,control(`speed`,`look`)),autoWrap:boolSetting(!0,control(`wrap`,`config`)),padding:intSetting({...PADDING_RANGE,step:1},1,control(`padding`,`config`)),updateNotice:boolSetting(!0,control(`update notice`,`config`)),menuTimeout:intSetting(MENU_TIMEOUT_RANGE,120,control(`menu timeout`,`config`)),renderer:enumSetting(RENDERERS$1,`claude`,control(`renderer`,`config`,{shown:IN_TMUX}),{optionDomain:`renderers`,library:RENDERER_LIBRARY}),...LANE_ROWS,colorCompatibility:{kind:`config`,...enumValues(COLOR_COMPATIBILITIES,`colorCompatibilities`),spec:colorCompatibilitySpec,floor:`truecolor`},default_empty_value:text(optionalStringSpec()),default_separator:text(optionalStringSpec()),menuGlyph:text(menuGlyphSpec)},ROWS=Object.entries(GLOBAL_FIELDS),VALUED_FIELDS=ROWS.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),CONTROLLED_FIELDS=ROWS.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),THEME_DEFAULT_FIELDS=ROWS.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),NAMED_DOMAINS=ROWS.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function valuedRow(e){return GLOBAL_FIELDS[e]}const floorOf=e=>valuedRow(e).floor;function wireKindOf(e){let t=GLOBAL_FIELDS[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const effectiveVarOf=e=>`${e}.effective`,nameOf$1=e=>{let t=GLOBAL_FIELDS[e];return t.kind===`selection`?t.sessionKey:e},SETTINGS=Object.fromEntries(CONTROLLED_FIELDS.map(e=>{let t=nameOf$1(e);return[t,{configKey:e,sessionKey:t,effectiveVar:effectiveVarOf(t),...GLOBAL_FIELDS[e].control}]})),SETTING_NAMES=Object.keys(SETTINGS),SETTING_PROJECTIONS=Object.values(SETTINGS),CONFIG_ONLY_PROJECTIONS=VALUED_FIELDS.filter(e=>GLOBAL_FIELDS[e].kind===`config`).map(e=>({configKey:e,effectiveVar:effectiveVarOf(e)})),CONFIG_ONLY_KEYS=new Set(CONFIG_ONLY_PROJECTIONS.map(e=>e.configKey)),CONFIG_KEY_TO_EFFECTIVE_VAR=new Map([...SETTING_PROJECTIONS,...CONFIG_ONLY_PROJECTIONS].map(e=>[e.configKey,e.effectiveVar])),SESSION_KEY_TO_EFFECTIVE_VAR=new Map(SETTING_PROJECTIONS.map(e=>[e.sessionKey,e.effectiveVar]));function perSetting(e){return Object.fromEntries(SETTING_NAMES.map(t=>[t,e(t)]))}const SESSION_KEY_TO_SETTING=new Map(SETTING_NAMES.map(e=>[SETTINGS[e].sessionKey,e]));function effectiveInput(e,t){let n=GLOBAL_FIELDS[e],r=wireKindOf(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 EFFECTIVE_INPUTS=Object.fromEntries([...CONFIG_KEY_TO_EFFECTIVE_VAR].map(([e,t])=>[t,effectiveInput(e,t)])),LANE_FEED_TYPES={subscribers:`number`,fps:`number`,shown:`boolean`},LANE_FEED_FIELDS=Object.keys(LANE_FEED_TYPES),TERM_COLS_FLOOR=80,PAYLOAD_INPUTS={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},"session.id":{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`},config_path:{kind:`input`,path:`configPath`,default:``},...EFFECTIVE_INPUTS,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(LANE_NAMES.flatMap(e=>LANE_FEED_FIELDS.map(t=>[laneFeedVar(e,t),{kind:`input`,path:laneFeedVar(e,t),type:LANE_FEED_TYPES[t],default:UNFOLLOWED[t]}]))),[drawingVar(`by`)]:{kind:`input`,path:drawingVar(`by`),default:ANSWERING.by},[drawingVar(`fps`)]:{kind:`input`,path:drawingVar(`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:``}},DRAW_PROJECTIONS={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 drawProjectionAt(e){let t=e.split(`.`,1)[0];return Object.hasOwn(DRAW_PROJECTIONS,t)?t:void 0}const SLOT_PATHS=Object.fromEntries(EXPRESSION_SLOTS.map(e=>[e,CONFIG_KEY_TO_EFFECTIVE_VAR.get(e)]));function slotAt(e){return EXPRESSION_SLOTS.find(t=>SLOT_PATHS[t]===e)}function reservedNamespaceOf(e){let t=ident(e);return RESERVED_NAMESPACES.find(e=>t.startsWith(ident(e)))}function reservedNamespaceCollisions(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:findKeyLine(e.source,[`root`])})}function pluginScopeCollisions(e,t,n){for(let r of[`variables`,`actions`,`helpers`,`segments`])for(let i of Object.keys(t[r]??{})){let t=scopeOf$1(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:findKeyLine(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=()=>({path:`segments.${r}.vars.${t}`,line:findKeyLine(e.source,[`segments`,r,`vars`,t])});if(isPayloadInput(i)){e.issues.push({...a(),message:`segment "${r}"'s var "${t}" is named "${i}", ${PAYLOAD_OWNED} — rename the var or the segment`});continue}let o=scopeOf$1(i);o===void 0||n.has(r)||e.issues.push({...a(),message:`segment "${r}"'s var "${t}" is named "${i}", in "${o}", the namespace plugins own — rename the var or the segment`})}}const PAYLOAD_OWNED=`supplied by the daemon's payload to every config`;function payloadDeclarationNotices(e,t,n){let r=keyLocator(t);return n.filter(isPayloadInput).map(t=>{let n=r([`variables`,t]);return`${n===void 0?e:`${e}:${n}`}: "${t}" is ${PAYLOAD_OWNED}, so this declaration is ignored — remove it`})}function isPayloadInput(e){return Object.hasOwn(PAYLOAD_INPUTS,e)}const EDIT_MODE_KEY=`edit.mode`,EDIT_CONFIGURE_KEY=`edit.configure`,EDIT_TOGGLE_ACTION=`edit.toggle`,EDIT_UNCONFIGURE_ACTION=`edit.unconfigure`,EDIT_MODE_ARRANGE=`arrange`,PLACEMENT_DRAFT_NS=`${EDIT_NS}draft.`;function configureMember(e,t){return`${e}:${t}`}const EDIT_MODE_REF={variable:EDIT_MODE_KEY,key:EDIT_MODE_KEY,member:EDIT_MODE_ARRANGE},EDIT_MODE_GATE=disclosureGate(EDIT_MODE_REF);function referencesEditToggle(e){try{return SYNTAX_ENGINE.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function fileWantsEditMode(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`&&referencesEditToggle(t))return!0}return!1}function synthesizeEditModeToggle(e,t){if(reservedNamespaceCollisions(e,t,EDIT_NS,`edit mode`),!fileWantsEditMode(t))return;let{variables:n,actions:r}=editModeArtifacts();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function editModeArtifacts(){return{variables:{[EDIT_MODE_KEY]:{...disclosureStateVar(EDIT_MODE_KEY,DISCLOSURE_CLOSED),within:[SETTINGS_REF]},[EDIT_CONFIGURE_KEY]:{...disclosureStateVar(EDIT_CONFIGURE_KEY,DISCLOSURE_CLOSED),within:[EDIT_MODE_REF]}},actions:{[EDIT_TOGGLE_ACTION]:disclosureCycleAction(EDIT_MODE_KEY,EDIT_MODE_ARRANGE),[EDIT_UNCONFIGURE_ACTION]:{set:EDIT_CONFIGURE_KEY,to:DISCLOSURE_CLOSED}}}}const baseCache=new Map;function paletteForThemeName(e){let t=basePaletteFor(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 placementPalette(e,t){return e===`bar`?t:paletteForThemeName(e)}function basePaletteFor(e){let t=baseCache.get(e);if(t!==void 0)return t;let n=getThemePalette(e);return n===null?null:(baseCache.set(e,n),n)}function transposedPalette(e,t){return TRANSPOSED(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>transposePalette(e,t))}const TRANSPOSED=memoPerPalette();function namedTheme(e){let t=basePaletteFor(e);return t===null?null:{kind:`decided`,name:e,value:t}}function decideThemeName(e,t,n){let r=namedTheme(e);return r===null?(n(ruleFloorMessage(t,`palette`,`"${e}" names no installed theme${retiredThemeNote(e)}`)),themeFloor()):r}function resolveThemeSelection(e,t,n){return resolveSelection(e,t,n,themeFloor(),namedTheme)}function themeFloor(){return{kind:`decided`,name:THEME_FLOOR,value:paletteForThemeName(THEME_FLOOR)}}const NO_THEME_DEFAULT=Object.freeze({});function themeDefaultsOf(e,t){return e.kind===`decided`?t[e.name]??NO_THEME_DEFAULT:NO_THEME_DEFAULT}function underThemeDefault(e,t){return{...e,...Object.fromEntries(THEME_DEFAULT_FIELDS.map(n=>[n,e[n]??t[n]]))}}const laneSwitches=(e,t)=>perLane(n=>{let{setting:r,on:i,inTmux:a}=LANES[n].switch;return e[r]===i&&(t||!a)});function resolveValued(e,t,n,r){let i=valuedRow(e);return effectiveGlobal(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function presetOf(e,t){return effectivePresetName(t(`preset`),e.globals.preset,e.presets)}function resolveEffectiveGlobals(e,t,n){let r=presetOf(e,t),i=presetGlobals(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=resolveThemeSelection(a.palette,t(`theme`),i.palette),s=underThemeDefault(i,themeDefaultsOf(o,e.themeDefaults));return{...Object.fromEntries(VALUED_FIELDS.map(e=>[e,resolveValued(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:resolveStyleSelection(a.style,t(`style`),s.style,e.styles),effect:resolveEffectSelection(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}const busy=e=>({kind:`busy`,what:e});var DoctorBusy=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};async function seen(e){let t=await e;if(t.kind===`busy`)throw new DoctorBusy(t.what);return t}function asked(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const readStores=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function oneAskPerClick(e){let t=new Map,n=(e,n)=>{let r=JSON.stringify(e),i=t.get(r)??n();return t.set(r,i),i};return{...e,probeTmux:t=>n([`tmux`,t],()=>e.probeTmux(t)),remoteLogin:t=>n([`remote`,t],()=>e.remoteLogin(t)),fontInUse:(t,r,i)=>n([`font`,t,r,i],()=>e.fontInUse(t,r,i))}}async function transcriptReads(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:await Promise.all([...n].map(async([t,n])=>({path:t,answered:n,read:await e.transcript(t)})))}}function configFacts(e,t){let n={layers:e.layers,target:t,warnings:e.warning===null?[]:e.warning.split(`
|
|
79
79
|
`)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const readSettings=e=>asked(()=>readSettingsChain(e));function settingsChains(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:claudeSettingsPath(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:readSettings(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 tmuxFacts(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:await seen(e.probeTmux(t))}}function terminalIdentity(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:identifyFromEnv(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:identifyInTmux(t),tmuxClient:t}}}}async function terminalFacts(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(isBundling(s))return{kind:`bundling`,name:s,version:c};if(!isConfigured(s))return{kind:`unread`,name:s,version:c};let{ITERM_PROFILE:l,...u}=o??{},d=a===null?{kind:`ok`,value:n.ssh===!0}:await seen(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 seen(e.fontInUse({name:s,version:c},a===null?o??{}:u,r))}}async function need(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:await t()}}async function segmentDataFacts(e,t,n,r){return{pullRequests:await need(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:await need(t.rateLimits,()=>r)}}async function gatherFacts(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=resolveEffectiveGlobals(d.config,r,()=>!1),p=await tmuxFacts(e,t.tmux),m=terminalIdentity(p,t.terminalEnv),h=[...new Set([...stripPrivateGlyphs(f),...privateGlyphsIn(JSON.stringify(d.config))])].join(``),[g,_,v]=await Promise.all([h===``?{kind:`none`}:terminalFacts(e,m,t,h).then(e=>({kind:`glyphs`,glyphs:h,terminal:e})),e.daemons(),segmentDataFacts(e,dataNeeds(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:configFacts(d,n.target),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:v,transcripts:await transcriptReads(e,o),claudeSettings:settingsChains({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:claudeSettingsPath(claudeConfigDir(t.claudeConfigDir,e.home))},c.kind===`ok`?c.value:[])}}function applyFix(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;writeAtomic(e,setValue(readClaudeSettingsText(e),t.path,JSON.stringify(t.value),JSON_DIALECT));let r=e=>({...e,sources:readSettings(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||laterIdentity(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 DEBUG_WHATS=[`vars`,`segments`,`config`];function isDebugWhat(e){return typeof e==`string`&&DEBUG_WHATS.includes(e)}const stay=e=>({resp:e,exitAfterFlush:null,settled:NOTHING_TO_SETTLE}),replied=e=>({kind:`reply`,...e}),REPLY_KINDS={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},refuse=(e,t)=>replied(stay({ok:!1,error:t,code:e,daemonV:3}));function subscription(e){let t=parseSessionId(e.sessionId);if(!t.ok)return refuse(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return refuse(`VERSION_MISMATCH`,`this client's subscribe names no lane (${LANE_NAMES.join(`, `)}): it predates the lane toggles — update it`);let n=parseLane(e.lane);return n===null?refuse(`BAD_REQUEST`,`subscribe needs a lane, one of ${LANE_NAMES.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function handleRequest(e,t,n,r,i){if(t.kind===`url`)return urlClick(e,t.frame,n,r,i);let a=t.req;return!a||typeof a!=`object`||typeof a.v!=`number`?refuse(`BAD_REQUEST`,`malformed request`):a.v===3?a.kind===`subscribe`?subscription(a):typeof a.kind!=`string`||!Object.hasOwn(REPLY_KINDS,a.kind)?refuse(`BAD_REQUEST`,`unknown kind`):replied(await replyTo(e,a,n,r,i)):(a.v>3?e.log(`info`,`version mismatch: client=${a.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):e.log(`info`,`version mismatch: client=${a.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${a.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:a.v>3?0:null,settled:NOTHING_TO_SETTLE})}async function replyTo(e,t,n,r,i){let{stats:a,clock:o,frameFeeds:s,renderer:c,payloadProviders:{gitProvider:l,usageStore:u},fileEvents:d,runs:f,sourceRuns:p,menuIdle:m,tmuxStatusLines:h,watcherRegistry:g,limits:_,handlerProbes:v,renderSightings:y,bundle:b,sourceDigest:x,doctorStores:S}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,settled:NOTHING_TO_SETTLE};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return stay(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`){let{stats:t}=await c.ask({kind:`stats`},instantAt(o));return stay({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:sourceSnapshots(e,t.renderCache),fileEvents:d.stats(),sourceRuns:p.stats(),runs:f.stats(),transcriptReads:transcriptReads$1(),...t,collector:e.collector.stats(),menuIdle:m.getStats(),frameFeeds:s.getStats(),tmuxStatus:h.stats(),watchersActive:g.size(),dirWatchesActive:g.dirWatches(),nextRestartReason:_.describeNextRestart(),handlerProbes:v.list(),clients:y.list(instantAt(o)),bundle:b,sourceDigest:x,daemon:_.serving(),doctorStores:readStores(S)})})}if(t.kind===`render`){let c=new Date(o.now()),l=instantOf(c),u=o.monotonic(),d=spanMs(r.at,u),f=[];a.requestsTotal++;let p=r.id,m=checkRenderRequest(t,a,e.log,e.home),h=(t,n)=>y.see(t.hookData.session_id,{client:t.hints.client??null,termCols:t.hints.termCols??null,rateLimits:t.rateLimits,claudeConfigDir:claudeConfigDir(t.hints.claudeConfigDir,e.home),projectDir:t.requested.projectDir,transcript:transcriptSaid(t.hookData),frame:n},l,p);m.ok&&(h(m.req,`drawing`),s.note(m.req.hookData.session_id,m.req,p),e.declaredStatusLines.arrived(m.req.hookData.session_id));let g=t=>{t.outcome.kind!==`ok`&&a.requestsErrored++,noteFacts(f,{req:String(r.id),timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let s=elapsedMs(o,u);a.recordTook(s);let{level:c,line:l}=requestEvent(`render`,f,t.outcome,s);return e.log(c,l),{resp:t.resp,exitAfterFlush:null,settled:t.settled}};if(!m.ok)return g(refusedRender(m.problems));let _=await answerStatusline(e.renderer,e.collector,e.menuIdle,s,o,m.req,p,l,u+waitBudgetMs(m.req.deadline,r.at,{epochMs:c.getTime(),monoMs:u}),f).catch(e=>{let t=renderFailure(failureOf(e));return{outcome:t,resp:failedWith(t.message),seen:`failed`,settled:NOTHING_TO_SETTLE}});noteFacts(f,cacheTallyFacts(e.payloadProviders));try{return h(m.req,_.seen),g(_)}catch(e){throw _.settled(!1),e}}if(t.kind===`click`)return stay(await clickEvent(e,r,n,i,(n,r)=>clickOutcome(e,t,n,r)));if(t.kind===`debug`){if(!isDebugWhat(t.what))return stay({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${DEBUG_WHATS.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let{snapshot:e}=await c.ask({kind:`debug`,what:t.what},instantAt(o));return stay({ok:!0,debug:e})}throw Error(`no reply for request ${inspect(t)}`)}function sourceSnapshots(e,t){let{payloadProviders:{gitProvider:n,tmuxService:r,usageStore:i,managedStorage:a,hostService:o,transcriptLanes:s},refreshLedger:c}=e,l=n.getStats(),u=r.getStats(),d=i.scanStats(),f=a.stats();return{records:c.snapshot(),homes:{daemon:1,configDir:d.entries,repo:l.size,directory:t.size,session:i.getStats().size,view:t.views,pane:u.entries},held:{git:l.held,tmux:u.held,host:o.held(),today:d.held,pluginStorage:f.held,transcript:s.stats().held},pluginStorage:{folders:f.folders,faults:f.faults,lost:f.lost}}}async function clickEvent(e,t,n,r,i){let{clock:a}=e,o=a.monotonic(),s=[[`req`,String(t.id)],[`queued`,`${spanMs(t.at,o)}ms`]],c=await i(s,{id:t.id,gone:()=>n()||r()}).catch(failureOf);noteFacts(s,{timedOut:n()?`Y`:`N`,clientLeft:r()?`Y`:`N`});let{level:l,line:u}=requestEvent(`click`,s,c,elapsedMs(a,o));return e.log(l,u),clickReply(c)}async function clickOutcome(e,t,n,r){noteFacts(n,{via:`cli`});let{url:i}=t;return typeof i==`string`?ranClick(e,parseClick(i,{kind:`cli`},e.linkSigner),n,r):badRequest(`a click's url is a string, got ${typeof i}`)}function readUrlFrame(e,t){let{urlV:n,url:r}=e;return typeof n!=`number`||!URL_FRAME_VERSIONS.has(n)?{kind:`refused`,problem:`the URL handler's frame version ${inspect(n)} is not one this daemon speaks (${[...URL_FRAME_VERSIONS].join(`, `)})`}:typeof r==`string`?parseClick(r,{kind:`forwarder`,urlV:n},t):{kind:`refused`,problem:`the URL handler's frame carries no url string`}}function urlClick(e,t,n,r,i){let a=readUrlFrame(t,e.linkSigner);return{kind:`url`,awaitsVerdict:awaitsVerdict(t.urlV),verdict:a.kind===`refused`?clickReply(badRequest(a.problem)):{ok:!0,output:``},land:()=>clickEvent(e,r,n,i,async(n,r)=>(noteFacts(n,{via:`forwarder`,urlV:String(t.urlV)}),ranClick(e,a,n,r))).then(()=>{})}}async function ranClick(e,t,n,r){switch(t.kind){case`refused`:return badRequest(t.problem);case`probe`:return noteFacts(n,{verb:VERB_DOCTOR_PROBE,nonce:t.nonce}),e.handlerProbes.arrive({nonce:t.nonce,delivery:t.delivery}),{kind:`ok`};case`status-line`:return noteFacts(n,{verb:VERB_TMUX_STATUS_CLICK}),statusLineClick(e,t.value,n,r);case`link`:return noteFacts(n,{link:t.link}),handleClick(e,t.verb,t.value,{via:`link`,delivery:t.delivery},n,r)}}const VERB_FACT={link:`verb`,"tmux-status":`linkVerb`};async function handleClick(e,t,n,r,i,a){try{var o=_usingCtx();noteFacts(i,{[VERB_FACT[r.via]]:t});let s=clickSessionOf(t,n);s===null?noteFacts(i,{sid:`-`}):s.ok&&(noteFacts(i,{sid:s.id}),e.collector.clicked(s.id));let c=o.u(e.clicks.hold(a)),l=await e.renderer.answer({kind:`event`,at:instantAt(e.clock),event:{kind:`click`,verb:t,value:n,session:s,arrival:r,id:a.id,latest:s?.ok?e.frameFeeds.latest(s.id):null}});if(i.push(...l.record),l.kind===`threw`)return l.failure;let u=l.settled.find(e=>e.kind!==`ok`&&e.kind!==`skipped`);return u===void 0?{kind:`ok`}:clickFailure(u)}catch(e){o.e=e}finally{o.d()}}function clickFailure(e){return{kind:CLICK_FAILURE[e.kind],message:e.reason,detail:e.reason}}const CLICK_FAILURE={refused:`bad-request`,failed:`threw`,closing:`closing`};function clickReply(e){switch(e.kind){case`ok`:return{ok:!0,output:``};case`bad-request`:return{ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3};case`threw`:case`closing`:case`abandoned`:case`down`:return failedWith(e.message)}}async function statusLineClick(e,t,n,r){let{tmuxStatusLines:i}=e,a=i.linkAt(t);if(a.kind===`refused`)return badRequest(a.reason);if(noteFacts(n,{link:unprovenLink(a.url)}),isBarLink(a.url)){let t=openClick(a.url,e.linkSigner);return t.kind===`refused`?badRequest(t.problem):handleClick(e,t.verb,t.value,{via:`tmux-status`},n,r)}return await clickHandoff(e.launcher,{bin:process$1.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[a.url],category:`click.open`},`opening ${a.url}`,e.log,CLICK_PROGRAM_TIMEOUT_MS,e.tmp),{kind:`ok`}}const refusedRender=e=>({outcome:badRequest(...e),resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},settled:NOTHING_TO_SETTLE});function actsDir(e,t){let n=createHash(`sha256`).update(t).digest(`hex`).slice(0,16);return path.join(e,`update-act`,n)}function judgeAct(e){if(e===null)return IDLE;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 filesOf=e=>({stdout:path.join(e,`stdout`),stderr:path.join(e,`stderr`),status:path.join(e,`status`)}),recordOf$1=e=>path.join(e,`record.json`);function actNumbers(e){let t;try{t=fs.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)}const TAIL_BYTES=4096;function lastLineOf(e){let t=readTailSync(e,TAIL_BYTES);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 removeAct(e,t){let n=path.join(e,`.removed-${t}-${process.pid}`);try{fs.renameSync(path.join(e,String(t)),n)}catch(e){if(e.code===`ENOENT`)return;throw e}fs.rmSync(n,{recursive:!0,force:!0})}const bootedAt=e=>e.now()-os.uptime()*1e3;async function isRecordedJob(e,t,n,r){if(e.started<=r||!n.jobGroupAlive(e.pid))return!1;let i=await t(e.pid);return e.startTime===null||i.kind===`unavailable`||i.token===e.startTime}function readRecord(e){try{return JSON.parse(fs.readFileSync(recordOf$1(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}const sameJob=(e,t)=>e.pid===t.pid&&e.startTime===t.startTime;function makeActReader(e,t,n,r){let i=null;async function a(a){let o=path.join(e,String(a)),s=readRecord(o);if(s===null)return null;if((i===null||!sameJob(i.record,s))&&(i={record:s,ours:await isRecordedJob(s,t,n,bootedAt(r)),final:null}),i.final!==null)return i.final;i.ours=i.ours&&n.jobGroupAlive(s.pid);let c=filesOf(o),l=readJobEnd(c.status),u=l===null?null:lastLineOf(c.stderr)??lastLineOf(c.stdout);if(!fs.existsSync(o))return null;let d={act:a,record:s,alive:i.ours,end:l,lastLine:u};return d.alive||(i.final=d),d}return{async read(){let t=null;for(;;){let n=actNumbers(e).at(-1);if(n===void 0)return null;if(n===t)throw Error(`${path.join(e,String(n))}: an act with no record`);let r=await a(n);if(r!==null)return r;t=n}}}}function stakeClaim(e,t,n){fs.mkdirSync(e,{recursive:!0});let r=fs.mkdtempSync(path.join(e,`.claim-`));try{return fs.writeFileSync(recordOf$1(r),JSON.stringify(n)),fs.renameSync(r,t),!0}catch(e){let t=e.code;if(t===`ENOTEMPTY`||t===`EEXIST`)return!1;throw e}finally{fs.rmSync(r,{recursive:!0,force:!0})}}async function claimAct(e,t,n,r,i,a,o,s){let c=(n??0)+1,l=path.join(t,String(c)),u=e.launchJobSync(i,filesOf(l));if(!u.ok)throw Error(`apply-update: ${u.error}`);let d=!1;try{let e=await s(u.pid);if(!stakeClaim(t,l,{identity:r,pid:u.pid,startTime:e.kind===`start`?e.token:null,started:o,deadline:o+a}))return CLAIMED_FIRST;if(actNumbers(t).some(e=>e>c))return removeAct(t,c),CLAIMED_FIRST;d=!0}finally{d?u.release():u.withdraw()}for(let e of actNumbers(t).filter(e=>e<c))removeAct(t,e);return{ok:!0,act:c}}const CLAIMED_FIRST={ok:!1,reason:`another act claimed this bundle first`};function endOverdue(e,t,n){let r=filesOf(path.join(e,String(t.act))).status;return n.endJob(t.record.pid,r,{kind:`timeout`})}function isJsonValue(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(isJsonValue);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(isJsonValue)}default:return!1}}function toDocument(e){if(Array.isArray(e))return Object.freeze(e.map(toDocument));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]=toDocument(r);return Object.freeze(t)}return e}function typeOf(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 toString(e){return typeof e==`string`?e:String(e)}function toNumber(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 toBool(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 PendingValueError=class extends Error{constructor(e,t){super(t),this.variable=e}};function readPending(e){return e instanceof PendingValueError?e:e instanceof Error&&e.cause!==void 0?readPending(e.cause):void 0}function restamp(e,t,n){if(t.kind===`pending`)return pendingOf(t.why);if(e!==void 0&&e.kind!==`pending`){let{at:n,...r}=e;if((0,import_dist$1.compareStructural)(r,t))return e}return{...t,at:n}}var KeyedSerialQueue=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)})}};const DIAGNOSTIC_LEVELS={error:{rank:0,glyph:`⚠`,colors:DIAGNOSTIC_ERROR_COLORS},warning:{rank:1,glyph:`⚠`,colors:DIAGNOSTIC_WARNING_COLORS},info:{rank:2,glyph:`ℹ`,colors:DIAGNOSTIC_INFO_COLORS}},ERROR_SEVERITY={level:`error`,glyph:DIAGNOSTIC_LEVELS.error.glyph},WARNING_SEVERITY={level:`warning`,glyph:DIAGNOSTIC_LEVELS.warning.glyph},UPDATE_SEVERITY={level:`info`,glyph:`⬆`},APPROVAL_SEVERITY={level:`info`,glyph:`🔒`},HANDOFF_SEVERITY={level:`info`,glyph:`🧪`},colorsOf=e=>DIAGNOSTIC_LEVELS[e.level].colors;function diagnosticSpan(e,t){return{text:sanitizeText(e),link:t}}function collectDiagnostics(e,t,n,r,i){let a=new Set,o=(e,t)=>{let n=plainMessage(e,t);for(let e of n)a.add(e);return n},s=[...n.flatMap(e=>o(e,ERROR_SEVERITY)),...r,...i.flatMap(e=>o(e,WARNING_SEVERITY))].sort((e,t)=>rankOf(e)-rankOf(t)),c=copyKeys(s);return s.map((n,r)=>a.has(n)?{...n,lines:[[diagnosticSpan(n.lines[0][0].text,copyLink(e,t,c[r],r+1))],...n.lines.slice(1)]}:n)}function plainMessage({about:e,text:t,copy:n},r){let[i,...a]=t.split(/\r\n|\r|\n/).map(e=>diagnosticSpan(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 copyKeys(e){return stopsOf(e).map(e=>String(e*PAGES+1))}function copyLink(e,t,n,r){return effectsUrl([{verb:VERB_COPY_DIAGNOSTIC,args:[e,t,n]}],`copy diagnostic ${r}`)}const rankOf=e=>DIAGNOSTIC_LEVELS[e.severity.level].rank;function worstLevel(e){return e[0]?.severity.level??null}const IDENTITY_BITS=32,OCCURRENCES=256,PAGES=4096;function identityOf(e){let t=createHash(`sha256`).update(`${e.severity.level}\0${e.severity.glyph}\0${e.about}`).digest(`hex`);return Number.parseInt(t.slice(0,IDENTITY_BITS/4+1),16)%2**IDENTITY_BITS}function stopsOf(e){let t=new Map;return e.map(e=>{let n=identityOf(e),r=t.get(n)??0;return t.set(n,r+1),n*OCCURRENCES+Math.min(r,OCCURRENCES-1)})}function viewerKey(e,t,n){return String(stopsOf(e)[t]*PAGES+n+1)}const INDICATOR_CAP=9;function diagnosticsProjection(e){let t=worstLevel(e),n=e.length,{glyph:r,colors:i}=DIAGNOSTIC_LEVELS[t??`info`];return{label:t===null?``:`${r} ${n>9?`9+`:n}`,fg:i.fg,bg:i.bg,open:e.length===0?`0`:viewerKey(e,0,0)}}function viewedIndex(e,t){let n=Number(e)-1,r=stopsOf(t).indexOf(Math.floor(n/PAGES));return e===null||r===-1?null:{index:r+1,page:n%PAGES}}const MAX_VIEWER_ROWS=20;function viewerRowCap(e,t){return Math.min(20,e??20,...t)}function viewerRows(e,t,n,r,i){let{index:a}=t,o=e[a-1],s=viewerOptions(i),c=channelRows(o,s,[]),l=colorsOf(o.severity),u=new Style({bgcolor:l.bg,color:l.fg}),d=(e,t)=>cell$1(e,t===null?u:u.withLink(t)),f=(t,r)=>r===null?d(` `,null):d(t,viewerLink(n,viewerKey(e,r.index-1,r.page),`show diagnostic ${r.index} of ${e.length} page ${r.page+1}`)),p=(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,u=t>1?`[${a}/${e.length} ${i+1}/${t}]`:`[${a}/${e.length}]`;return drawnRows$1([d(`✕`,viewerLink(n,`0`)),...l?[f(`‹`,o)]:[],d(u,null),...l?[f(`›`,c)]:[],d(`⧉ copy`,copyLink(n,r,viewerKey(e,a-1,0),a))],s)},m=1;for(;;){let e=Math.max(1,i.rows-m),n=Math.min(PAGES,Math.ceil(c.length/e)),r=Math.min(t.page,n-1),a=p(n,r);if(a.length>m){m=a.length;continue}let o=c.slice(r*e,(r+1)*e),l=c.length-(r+1)*e,u=r===n-1&&l>0?[...o.slice(0,-1),...drawnRows$1([d(`… ${l+1} more rows: ⧉ copy has them all`,null)],{...s,wrap:!1})]:o;return[...a,...u]}}function handoffRows(e,t,n,r){let{label:i,fg:a,bg:o,open:s}=diagnosticsProjection(t),c=i===``?[]:[cell$1(i,new Style({bgcolor:o,color:a}).withLink(viewerLink(n,s)))];return channelRows(e,viewerOptions(r),c)}function viewerLink(e,t,n){return effectsUrl([{verb:VERB_SET_STATE,args:[e,DIAGNOSTICS_VIEWING,t]}],n)}function viewerOptions(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,colorCompatibility:e.colorCompatibility}}const cell$1=(e,t)=>new RichText(`${e} `,{style:t,end:``,overflow:`ignore`}),drawnRows$1=(e,t)=>drawStripCells(e,t).lines.map(e=>({kind:`diagnostic`,runs:e})),ISSUE_INDENT=` `;function channelRows(e,t,n){let r=colorsOf(e.severity),i=new Style({bgcolor:r.bg,color:r.fg}),a=e=>e===null?i:i.withLink(e),o=asCellCol(Math.max(2,t.width-1));return e.lines.flatMap((r,s)=>{let c=cell$1(s===0?e.severity.glyph:ISSUE_INDENT,i),l=r.flatMap(e=>e.text.split(` `).flatMap(e=>chopCells(e,o)).map(t=>cell$1(t,a(e.link)))),u=s===0?n:[];return drawnRows$1([c,...l,...u],t)})}const _GLOBAL_OPTION_DOMAINS=new Map;function registerBuiltinDomain(e,t,n={}){_GLOBAL_OPTION_DOMAINS.set(e,{permanent:!0,resolve:t,...n})}registerBuiltinDomain(`themes`,()=>listResolvablePaletteNames(),{paletteOf:e=>paletteForThemeName(e)});const PLACEMENT_THEMES=`placementThemes`;registerBuiltinDomain(PLACEMENT_THEMES,placementThemeNames,{paletteOf:(e,t)=>placementPalette(e,t.palette)});for(let{name:e,members:t,library:n,labelOf:r}of NAMED_DOMAINS)registerBuiltinDomain(e,()=>t,{library:n,labelOf:r});function perConfigDomainsFor(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>transposedPalette(n.basePalette,e.styles[t])}],[`presets`,{members:presetNames(e.presets)}]])}function knownOptionDomainNames(e){return[...new Set([..._GLOBAL_OPTION_DOMAINS.keys(),...e.keys()])]}function resolveOptionDomain(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=_GLOBAL_OPTION_DOMAINS.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf,library:r.library,labelOf:r.labelOf};throw Error(unknownOptionDomain(e,t))}const RENAMED_OPTION_DOMAINS=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function unknownOptionDomain(e,t){let n=RENAMED_OPTION_DOMAINS.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${knownOptionDomainNames(t).join(`, `)})`}function menuMember(e){return e}function menuStateKey(e,t,n){return n===void 0?MENU_NS+ident(e)+`.`+ident(t):sharedMenuStateKey(n)}function sharedMenuStateKey(e){return MENU_NS+ident(e)}function menuActionName(e,t){return e+`.`+t}function menuPageKey(e){return MENU_PAGE_NS+e}const MENU_OPTION_NAMES=[`closeOnPick`,`paged`,`key`,`distribution`],isMenuOptionName=e=>MENU_OPTION_NAMES.includes(e),MENU_OPTIONS_VOCABULARY=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${DISTRIBUTION_NAMES.map(e=>`"${e}"`).join(`, `)}; default "${DEFAULT_DISTRIBUTION}")`;function parseMenuOptions(e){for(let t of Object.keys(e))if(!isMenuOptionName(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${MENU_OPTIONS_VOCABULARY}`);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&&!isDistributionName(r))throw Error(`{{ menu }} option "distribution" must be one of: ${DISTRIBUTION_NAMES.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:placedBy(r)}}const optionsOf=e=>`from`in e?e.from:e.themes;function controlDomainAdmits(e,t,n){return e===`bool`?parseSessionBoolean(t)!==null:`min`in e?parseSessionInt(t,e)!==null:resolveOptionDomain(optionsOf(e),n).members.includes(t)}const LISTED_MEMBERS=8,SAMPLED_MEMBERS=3;function describeControlDomain(e,t){if(e===`bool`)return BOOLEAN_MEMBERS.join(` or `);if(!(`min`in e)){let n=optionsOf(e),{members:r}=resolveOptionDomain(n,t),i=r.map(e=>JSON.stringify(e));if(r.length<=LISTED_MEMBERS)return`one of ${i.join(`, `)}`;let a=typeof n==`string`?` "${n}"`:``;return`one of the ${r.length}${a} names, such as ${i.slice(0,SAMPLED_MEMBERS).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function controlDeclOf(e){return{label:e.label,domain:controlDomainOf(e.domain)}}function controlDomainOf(e){return e===`theme`?{themes:PLACEMENT_THEMES}:e===`bool`||`min`in e?e:{from:e}}function settingControl(e,t,n,r,i){let a=escapeTemplateLiteral(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...BOOLEAN_MEMBERS]}},variables:{}};if(`from`in o)return optionPicker(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 optionPicker(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 optionPicker(e,t,n,r,i){let a={variable:n,key:n,member:t},o=menuActionName(n,t),s=`${t}.open`,c=menuPageKey(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]:disclosureCycleAction(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:disclosureStateVar(n,DISCLOSURE_CLOSED),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const TABS=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],TAB_LABEL=Object.fromEntries(TABS.map(e=>[e.member,e.label])),SUBMENUS={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},SUBMENU_NAMES=Object.keys(SUBMENUS),PLACE=perSetting(e=>SETTINGS[e].place),isSubmenu=e=>Object.hasOwn(SUBMENUS,e),within$2=(e,t)=>e===t||isSubmenu(e)&&within$2(PLACE[SUBMENUS[e].beside],t),placePath=e=>isSubmenu(e)?`${placePath(PLACE[SUBMENUS[e].beside])} › ${SUBMENUS[e].trigger}`:e===`door`?`first line`:TAB_LABEL[e],settingMenuPath=e=>placePath(PLACE[e]),settingsByPlace=()=>[`door`,...TABS.map(e=>e.member)].flatMap(e=>[e,...SUBMENU_NAMES.filter(t=>within$2(t,e))]).map(e=>({path:placePath(e),names:SETTING_NAMES.filter(t=>PLACE[t]===e)})).filter(({names:e})=>e.length>0),laneOffReason=e=>{let{setting:t,on:n,inTmux:r}=LANES[e].switch;return`${LANES[e].label} is off — turn it on in the settings menu's ${settingMenuPath(t)}, or set globals.${t}: ${JSON.stringify(n)}${r?`; it runs only for a session inside a tmux pane`:``}`},GLOBALS_FIELDS=Object.fromEntries(Object.entries(GLOBAL_FIELDS).map(([e,t])=>[e,t.spec]));function settingControlDomain(e){return rangedDomain(GLOBAL_FIELDS[e])}function rangedDomain(e){return`optionDomain`in e&&e.optionDomain!==void 0?{from:e.optionDomain.name}:e.domain}function fragmentRejection(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:findKeyLine(e.source,[...n.split(`.`),r])})}}}function nestedPresetSpec(e){return fragmentRejection(`${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 nestedMenuGlyphSpec(e){return fragmentRejection(`${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 nameOnlySpec(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&isExpression(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:findKeyLine(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const REMOVED_GLOBALS={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 ${settingMenuPath(`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."},GLOBALS_SCHEMA={noun:`globals key`,fields:GLOBALS_FIELDS,removed:REMOVED_GLOBALS},PRESET_FRAGMENT_REJECTIONS={preset:nestedPresetSpec(`a preset`),menuGlyph:nestedMenuGlyphSpec(`a preset`)},PRESET_GLOBALS_SCHEMA={noun:`preset globals key`,fields:{...GLOBALS_FIELDS,...PRESET_FRAGMENT_REJECTIONS},removed:REMOVED_GLOBALS};function isPresetGlobalsField(e){return isGlobalsField(e)&&!(e in PRESET_FRAGMENT_REJECTIONS)}const EDIT_GLOBALS_WHY=`is decided later than any rule could be settled`,EDIT_GLOBALS_SCHEMA={noun:`editGlobals key`,removed:REMOVED_GLOBALS,fields:{...GLOBALS_FIELDS,preset:nestedPresetSpec(`the editGlobals fragment`),menuGlyph:nestedMenuGlyphSpec(`the editGlobals fragment`),palette:nameOnlySpec(GLOBALS_FIELDS.palette,`the editGlobals fragment`,EDIT_GLOBALS_WHY),style:nameOnlySpec(GLOBALS_FIELDS.style,`the editGlobals fragment`,EDIT_GLOBALS_WHY),effect:nameOnlySpec(GLOBALS_FIELDS.effect,`the editGlobals fragment`,EDIT_GLOBALS_WHY)}},THEME_DEFAULT_SCHEMA={noun:`theme default key`,fields:{...Object.fromEntries(THEME_DEFAULT_FIELDS.map(e=>[e,GLOBALS_FIELDS[e]])),style:nameOnlySpec(GLOBALS_FIELDS.style,`a theme's default`,`is the look that theme wears by name`)}};function validateThemeDefaults(e,t){if(!isPlainObject$2(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${describeType(t)}`,line:findKeyLine(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${retiredThemeNote(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:findKeyLine(e.source,[`themeDefaults`,r])});continue}let a=record(e,THEME_DEFAULT_SCHEMA,t,i);a!==null&&(n[r]=a)}return n}function validateGlobals(e,t,n){return n===void 0?{}:record(e,GLOBALS_SCHEMA,t,n)??{}}function validatePresetGlobals(e,t,n){return record(e,PRESET_GLOBALS_SCHEMA,t,n)??{}}function presetGlobalsJson(){return recordJson(PRESET_GLOBALS_SCHEMA)}function validateEditGlobals(e,t,n){return record(e,EDIT_GLOBALS_SCHEMA,t,n)??{}}const GLOBALS_FIELD_NAMES=new Set(Object.keys(GLOBALS_FIELDS));function isGlobalsField(e){return GLOBALS_FIELD_NAMES.has(e)}function removedGlobalPointer(e){return Object.hasOwn(REMOVED_GLOBALS,e)?REMOVED_GLOBALS[e]:void 0}function listGlobalsFieldNames(){return[...GLOBALS_FIELD_NAMES]}const NUMERIC_GLOBALS_FLOORS=new Map(Object.entries(GLOBAL_FIELDS).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function numericGlobalsSeeds(e){let t=new Map;for(let[n,r]of NUMERIC_GLOBALS_FLOORS){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const SEGMENT_PALETTE_KEY=/^segments\.([^.]+)\.palette$/,PRESET_ROOT_KEY=/^presets\.(.+)\.root$/,PRESET_GLOBALS_KEY=/^presets\.(.+)\.globals\.([^.]+)$/,THEME_DEFAULT_KEY=/^themeDefaults\.(.+)\.([^.]+)$/;function presetRootKey(e){return`presets.${e}.root`}function themeDefaultKey(e,t){return`themeDefaults.${e}.${t}`}const isThemeDefaultField=e=>THEME_DEFAULT_FIELDS.includes(e);function presetGlobalsKey(e,t){return`presets.${e}.globals.${t}`}function parsePersistTarget(e){if(isGlobalsField(e))return{scope:`globals`,field:e};let t=SEGMENT_PALETTE_KEY.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=PRESET_GLOBALS_KEY.exec(e);if(n&&isPresetGlobalsField(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=THEME_DEFAULT_KEY.exec(e);if(r&&isThemeDefaultField(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=PRESET_ROOT_KEY.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function persistPath(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 SEGMENT_GROUPS=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],OTHER_GROUP=`other`,LIBRARY_GROUPS=[...SEGMENT_GROUPS,OTHER_GROUP],GROUP_LABELS={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},HELP_GLYPH_CLOSED=`(?)`;function declareHelp(e,t,n,r){let i={variable:e,key:e,member:DISCLOSURE_OPEN};return r.variables[e]={...disclosureStateVar(e,DISCLOSURE_CLOSED),...n.length>0&&{within:n}},r.actions[e]=disclosureCycleAction(e,DISCLOSURE_OPEN),r.segments[e]={template:disclosureTrigger(e,`(?)`,`✕`),...gateOf$1(n)},disclosureNode(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 gateOf$1(e){let[t,...n]=e;return t===void 0?{}:{when:disclosureGate(t,...n)}}const NO_FILL=`none`;function groundOf(e){return resolveColorRef(e,`background`)}var ColorSpecError=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function resolveSegmentColors(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=evalToPlainText(n,i),l=c!==NO_FILL,u=l?c===void 0?o:resolveRef(a,c,`bg`):groundOf(a);e.bg=u;let d=evalToPlainText(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:textOn(a,e,t))(u):void 0:resolveRef(a,d,`fg`);return new Style({...l&&{bgcolor:ColorSpec.fromRgba(u)},...f!==void 0&&{color:ColorSpec.fromRgba(f)}})}function evalToPlainText(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function resolveRef(e,t,n){try{return resolveColorRef(e,t)}catch(e){throw e instanceof ColorRefError?new ColorSpecError(t,n,e.message):e}}const CONFIGURE_GLYPH=`🔧`,NODE_FLAGS={help:[`-h`,`--help`],version:[`-V`,`--version`]},LANE_PLACES=[...new Set(Object.values(LANES).map(e=>settingMenuPath(e.switch.setting)))].join(` or `),FIELD_COLUMN=Math.max(...Object.values(SETTINGS).map(e=>e.configKey.length))+2,EDIT_MODE_HELP=[`✚ inserts`,`✖ removes`,`${CONFIGURE_GLYPH} configures`,`↺ resets layout`],LANE_HELP={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`]},HELP_TEXT=`
|
|
80
80
|
cc-candybar - Beautiful powerline statusline for Claude Code
|
|
81
81
|
|
|
@@ -182,10 +182,10 @@ Config tooling:
|
|
|
182
182
|
config [--json] The effective merged config. (All three query the
|
|
183
183
|
running daemon; none spawn one.)
|
|
184
184
|
|
|
185
|
-
`,QUIET_PCT=60,QUIET_MIN_CONTRAST=3,QUIET_TEXT=`readableOn (mix (color "foreground") (bgOf) ${QUIET_PCT}) (bgOf) 3`,DOCTOR_NS=`${SETTINGS_NS}doctor.`,VERDICT_OK=`ok`,VERDICT_FAILED=`failed`;function doctorReportKeys(e){let t=`${DOCTOR_NS}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function configFields({target:e}){return`configTarget=${e.source}`}function linkFields(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?sightingOf(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 terminalFeatureFields(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 installFields(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}=clientStanding(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const signedMb=e=>`${e>=0?`+`:``}${mb(e)}`;function daemonFields({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${otherDaemons(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`:`${unreadPostMortems(e.value,n).length}/${o.value.length}`,c=i.kind===`unmeasured`?`unmeasured`:`${measureOf(i.charge)}${i.charge.kind===`stand-in`?`(${signedMb(-i.charge.gap)})`:``}:${mb(i.charge.bytes)}`,l=i.kind===`unmeasured`?`-`:i.processes.map(e=>`${e.role}:${e.pid}:${e.sizes===null?`-`:mb(e.sizes.rss)}`).join(`,`);return`${r} memory=${c}/${mb(a)} processes=${l} postMortems=${s}`}function dataFields(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 frameFields(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>statusLineValue(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${valueOf$1(i)}`;let a=refreshedFrames(r.flatMap(e=>e.bars));return`frames=${FRAMES_SEEN.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${valueOf$1(i)}`}function statusLineValue(e){let t=statusLineOf(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 truecolorEnvFields(e){let t=envVarOf(e,TMUX_TRUECOLOR_VAR);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${valueOf$1(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function transcriptFields(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 nerdFontFields(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=glyphSighting(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 rowReason(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function doctorReportPairs(e){return e.flatMap(({check:e,verdict:t})=>{let n=doctorReportKeys(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:BOOLEAN_FALSE},{key:n.sighting,value:``}]:[{key:n.verdict,value:VERDICT_FAILED},{key:n.reason,value:rowReason(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?BOOLEAN_FALSE:BOOLEAN_TRUE},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const QUICK_ACTIONS={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function quickActions(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }} {{ action "${t(`copyResume`)}" "⎘ resume" }} {{ 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(QUICK_ACTIONS).map(([t,n])=>[`${e}${t}`,n]))}}const ARMED=`armed`,DISARMED=`disarmed`,CONFIRM_KEY_SUFFIX=`.armed`,isConfirmKey=e=>e.endsWith(CONFIRM_KEY_SUFFIX);function confirms(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 confirmStep(e,t,n){let r=`${e}${CONFIRM_KEY_SUFFIX}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${ARMED}")`,s=confirms(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:ARMED},[a]:{set:r,to:DISARMED},...s.actions},armed:o,variables:{[e]:{kind:`state`,key:r,default:DISARMED}},disarm:a}}const SLASH_LINE_PATTERN=`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`,SLASH_LINE=new RegExp(SLASH_LINE_PATTERN);function parseSlashLine(e){return typeof e==`string`&&SLASH_LINE.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 slashLine(e){let t=parseSlashLine(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const COMMANDS$1=[`/compact`,`/model`],CLEAR=`/clear`;function commandTray(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=confirmStep(`${e}clear`,{arm:CLEAR,confirm:`${CLEAR} ✓ confirm`},[{action:n,when:`true`}]);return{template:COMMANDS$1.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${IN_TMUX} }}`,actions:{...Object.fromEntries(COMMANDS$1.map(e=>[t(e),{slash:slashLine(e)}])),...r.actions,[n]:{slash:slashLine(CLEAR)}},variables:r.variables,disarm:r.disarm}}const AUTOCOMPACT_WINDOWS=Array.from({length:10},(e,t)=>(t+1)*1e5),LEAST=AUTOCOMPACT_WINDOWS[0],MOST=AUTOCOMPACT_WINDOWS[AUTOCOMPACT_WINDOWS.length-1];function autoCompactControls(e,t){let n=Math.min(t??MOST,MOST),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:AUTOCOMPACT_WINDOWS.filter(e=>e<r).at(-1)??0,higher:AUTOCOMPACT_WINDOWS.find(e=>e>r&&e<=n)??0}}function autocompactControl(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${IN_TMUX} }}{{ 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:slashLine(`/autocompact auto`)},...Object.fromEntries(AUTOCOMPACT_WINDOWS.map(t=>[`${e}${t}`,{slash:slashLine(`/autocompact ${t}`)}]))}}}const formatTokenCount=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 }}`,EDIT_SEG=`${SETTINGS_NS}edit`,TOOLBAR_SEG=`${SETTINGS_NS}toolbar`,TOOLBAR=quickActions(SETTINGS_NS),COMMANDS_SEG=`${SETTINGS_NS}commands`,COMMANDS=commandTray(`${COMMANDS_SEG}.`),AUTOCOMPACT_SEG=`${SETTINGS_NS}autocompact`,AUTOCOMPACT$1=autocompactControl(`${AUTOCOMPACT_SEG}.`,formatTokenCount),seg=e=>({kind:`segment`,name:e}),TAB_KEY=`${SETTINGS_NS}tab`,tabSeg=e=>`${TAB_KEY}.${e}`,tabToggle=e=>`${tabSeg(e)}.toggle`,tabRef=e=>({variable:TAB_KEY,key:TAB_KEY,member:e}),SAVE_SEG=`${SETTINGS_NS}save`,PRESET_SAVE=`${SETTINGS_NS}preset.save`,PRESET_DELETE=`${SETTINGS_NS}preset.delete`,PRESET_DELETE_GLYPH=`🚮`,controlSeg=e=>`${SETTINGS_NS}${e}`,controlApply=e=>`${SETTINGS_NS}apply.${e}`,controlReset=e=>`${SETTINGS_NS}reset.${e}`,THEME_DEFAULT_SEG=`${SETTINGS_NS}themeDefault.save`,THEME_DEFAULT_DIFFERS=`${SETTINGS_NS}themeDefault.differs`,THEME_DEFAULT_THEME=`${SETTINGS_NS}themeDefault.theme`,THEME_DEFAULT_CELL={when:`{{ .${THEME_DEFAULT_DIFFERS} }}`,template:`{{ action "${THEME_DEFAULT_SEG}" (printf "⤓ default for %s" .${THEME_DEFAULT_THEME}) }} {{ swatch "${controlApply(`theme`)}" .${THEME_DEFAULT_THEME} }}`},RESET_ALL_SEG=`${SETTINGS_NS}resetAll`,DOOR_TOGGLE=`${SETTINGS_ANCHOR}.toggle`,UNDO_ACTION=`${SETTINGS_NS}undo`,BACK_ACTION=`${SETTINGS_NS}back`,BACK_STEP=`${BACK_ACTION}.step`,BACK_COUNT=`${SETTINGS_NS}navigation.back`,BACK_SEG=BACK_ACTION,BACK_GLYPH=`◁`,BACK_CELL={template:`{{ if gt .${BACK_COUNT} 0 }}{{ action "${BACK_ACTION}" "${BACK_GLYPH}" }}{{ else }}{{ fg (${QUIET_TEXT}) "${BACK_GLYPH}" }}{{ end }}`},REDO_ACTION=`${SETTINGS_NS}redo`,DOCTOR_SEG=`${SETTINGS_NS}doctor`,DOCTOR_RUN_ACTION=`${DOCTOR_SEG}.run`,doctorFixAction=e=>`${DOCTOR_SEG}.fix.${e}`,doctorMarkAction=(e,t)=>`${DOCTOR_SEG}.mark.${e}.${t}`,doctorRowSeg=e=>`${DOCTOR_SEG}.${e}`,MARK_GLYPH={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},PICKER_KEY=sharedMenuStateKey(`${SETTINGS_NS}pickers`),submenuSeg=e=>`${SETTINGS_NS}${e}`,submenuToggle=e=>`${submenuSeg(e)}.toggle`,accordionOf=e=>isSubmenu(e)?sharedMenuStateKey(`${SETTINGS_NS}${e}Pickers`):PICKER_KEY,submenuRef=e=>{let t=accordionOf(PLACE[SUBMENUS[e].beside]);return{variable:t,key:t,member:e}},PREVIEWS={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${PRESET_DELETE}" (printf "${PRESET_DELETE_GLYPH} delete %s" .${SETTINGS.preset.effectiveVar}) }}`}},controlRow=(e,t)=>`${SETTINGS_NS}list.${e}.${t}`,controlResettable=e=>`${SETTINGS_NS}resettable.${e}`,DRIFT_MARK=` •`,anyResettable=e=>e.length===0?`false`:`(or ${e.map(e=>`(and (${e.shown}) .${controlResettable(e.name)})`).join(` `)})`,laneSettings=LANE_NAMES.map(e=>[LANES[e].switch.setting,e]),HELP_ARTIFACTS={variables:{},actions:{},segments:{}},HELP=Object.fromEntries(laneSettings.map(([e,t])=>[e,declareHelp(`${SETTINGS_NS}help.${e}`,LANE_HELP[t],[],HELP_ARTIFACTS)])),SPINNER=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],laneReadout=e=>{let t=t=>`.${laneFeedVar(e,t)}`,n=SPINNER.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if eq .${SETTINGS[LANES[e].switch.setting].effectiveVar} ${JSON.stringify(LANES[e].switch.on)} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},DIAGNOSTICS_INDICATOR=`{{ if .diagnostics.label }} {{ bg .diagnostics.bg (fg .diagnostics.fg (action "${DIAGNOSTICS_VIEWING}" .diagnostics.label .diagnostics.open)) }}{{ end }}`,FPS_SEG=`${SETTINGS_NS}fps`,POLLED=`polled`,AT_MOST=`≤`,FPS_UNIT=` fps`,RATE_WIDTH=7,FRAME_RATE=`{{ if eq .${drawingVar(`by`)} "feed" }}{{ printf "%${RATE_WIDTH-4}s" (printf "${AT_MOST}%d" (int .${drawingVar(`fps`)})) }}${FPS_UNIT}{{ else }}${POLLED.padStart(RATE_WIDTH)}{{ end }}`,TRAIL=Object.fromEntries(laneSettings.map(([e,t])=>[e,laneReadout(t)])),submenusBeside=e=>SUBMENU_NAMES.filter(t=>SUBMENUS[t].beside===e),menuControl=e=>{let t=SETTINGS[e],n=PLACE[e];return{...t,name:e,place:n,control:settingControl({label:t.label,domain:settingControlDomain(t.configKey)},t.sessionKey,t.effectiveVar,controlApply(e),accordionOf(n)),beneath:t.previews.map(e=>PREVIEWS[e]),help:[HELP[e]].filter(e=>e!==void 0),submenus:submenusBeside(e)}},CONTROLS=Object.keys(SETTINGS).map(menuControl),controlsIn=e=>CONTROLS.filter(t=>t.place===e),controlsUnder=e=>CONTROLS.filter(t=>within$2(t.place,e)),markedDisplay=e=>t=>`(print ${templateLiteral(t)} (ternary ${templateLiteral(DRIFT_MARK)} "" ${anyResettable(controlsUnder(e))}))`,controlsAt=e=>controlsIn(e).flatMap(e=>[controlNode(e),...e.help,...e.submenus.map(e=>disclosureNode(submenuSeg(e),submenuRef(e),placeBody(e),`drop`))].map(t=>({...t,when:`{{ ${e.shown} }}`}))),SETTINGS_WRITTEN_KEYS=new Set(CONTROLS.flatMap(e=>[e.sessionKey,e.configKey])),RESET_ALL=confirmStep(RESET_ALL_SEG,{arm:`⟲`,confirm:`⟲ reset all?`},CONTROLS.map(e=>({action:controlReset(e.name),when:e.shown}))),SAVE_COUNTS=[`unsaved`,`history.undo`,`history.redo`],saveCountVar=e=>`${SETTINGS_NS}${e}`,UNSAVED_VAR=saveCountVar(`unsaved`),counted=(e,t)=>({body:t,shown:`(gt .${saveCountVar(e)} 0)`}),SAVE_PARTS=[counted(`unsaved`,`{{ action "${SAVE_SEG}" (printf "💾 save %d" .${UNSAVED_VAR}) }}`),counted(`history.undo`,`{{ action "${UNDO_ACTION}" "↶" }}`),counted(`history.redo`,`{{ action "${REDO_ACTION}" "↷" }}`),{body:RESET_ALL.template,shown:`(or ${anyResettable(CONTROLS)} ${RESET_ALL.armed})`}],SAVE_CELL={when:`{{ or ${SAVE_PARTS.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+SAVE_PARTS.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},CONFIRMS=[{step:RESET_ALL,place:`door`},{step:COMMANDS,place:`session`}],disarms=e=>e.map(e=>e.step.disarm),DOOR_DISARMS=disarms(CONFIRMS),TAB_DISARMS=disarms(CONFIRMS.filter(e=>e.place!==`door`));function controlNode(e){let t=controlSeg(e.name);return e.control.kind===`inline`?seg(t):disclosureNode(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>seg(controlRow(e.name,n)))},`drop`)}function isSettingsAnchor(e){return e===SETTINGS_ANCHOR}function prependAnchor(e){let t=seg(SETTINGS_ANCHOR);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[prependAnchor(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 withAnchor(e){return countAnchors(e)>0?e:prependAnchor(e)}function countAnchors(e){let t=0;for(let n of walkNodes(e))n.kind===`segment`&&isSettingsAnchor(n.name)&&(t+=1);return t}function anchorUnderGate(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&isSettingsAnchor(e.name)||e.opens!==void 0&&anchorUnderGate(e.opens.body,!0):e.children.some(e=>anchorUnderGate(e,n))}const PLACE_BODY={door:{direction:`horizontal`,content:[seg(BACK_SEG)],after:[seg(EDIT_SEG),seg(SAVE_SEG)]},session:{direction:`vertical`,content:[seg(TOOLBAR_SEG),{kind:`container`,direction:`horizontal`,children:[seg(COMMANDS_SEG),seg(AUTOCOMPACT_SEG)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[seg(PRESET_SAVE)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[seg(DOCTOR_SEG),...CHECKS.map(e=>seg(doctorRowSeg(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[seg(THEME_DEFAULT_SEG)]},toggles:{direction:`horizontal`,content:[],after:[]}};function placeBody(e){let{direction:t,content:n,after:r}=PLACE_BODY[e];return{kind:`container`,direction:t,children:[...n,...controlsAt(e),...r]}}function expandAnchor(e){return e.kind===`segment`?isSettingsAnchor(e.name)?{kind:`container`,direction:`horizontal`,children:[disclosureNode(e.name,SETTINGS_REF,DOOR_BODY,`above`),seg(FPS_SEG)]}:e:expandContainer(e)}function doorBody(){return{kind:`container`,direction:`vertical`,children:[placeBody(`door`),{kind:`container`,direction:`horizontal`,children:TABS.map(({member:e})=>disclosureNode(tabSeg(e),tabRef(e),placeBody(e),`drop`))}]}}const DOOR_BODY=doorBody();function expandContainer(e){return{...e,children:e.children.map(e=>expandAnchor(e))}}function settingsArtifacts(e){let t={variables:{[SETTINGS_ANCHOR]:disclosureStateVar(SETTINGS_ANCHOR,DISCLOSURE_CLOSED),[DIAGNOSTICS_VIEWING]:{kind:`state`,key:DIAGNOSTICS_VIEWING,default:`0`}},actions:{[DOOR_TOGGLE]:disclosureCycleAction(SETTINGS_ANCHOR,SETTINGS_OPEN),[DIAGNOSTICS_VIEWING]:{set:DIAGNOSTICS_VIEWING,int:!0},[SETTINGS_ANCHOR]:{do:[DOOR_TOGGLE,...DOOR_DISARMS]},[DOCTOR_RUN_ACTION]:{doctor:`run`},...TOOLBAR.actions,...COMMANDS.actions,...AUTOCOMPACT$1.actions,[SAVE_SEG]:{save:!0},[UNDO_ACTION]:{undo:!0},[BACK_STEP]:{back:!0},[BACK_ACTION]:{do:[BACK_STEP,...DOOR_DISARMS]},[REDO_ACTION]:{redo:!0},[PRESET_SAVE]:{preset:`save`},[THEME_DEFAULT_SEG]:{themeDefault:`save`},[PRESET_DELETE]:{preset:`delete`,name:`{{ .${SETTINGS.preset.effectiveVar} }}`}},segments:{[SETTINGS_ANCHOR]:{template:`{{ $door := ${disclosureTriggerCall(SETTINGS_ANCHOR,templateLiteral(e),templateLiteral(`✖`))} }}{{ if ${disclosureTerm(SETTINGS_REF)} }}{{ fg (keptOn (roleTextOn "${DOOR_CLOSE_ROLE}" (bgOf)) (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+DIAGNOSTICS_INDICATOR},[FPS_SEG]:{template:FRAME_RATE},[TOOLBAR_SEG]:{template:TOOLBAR.template},[COMMANDS_SEG]:{template:COMMANDS.template,when:COMMANDS.when},[AUTOCOMPACT_SEG]:{template:AUTOCOMPACT$1.template,bg:AUTOCOMPACT$1.bg,when:AUTOCOMPACT$1.when},[BACK_SEG]:BACK_CELL,[SAVE_SEG]:SAVE_CELL,[THEME_DEFAULT_SEG]:THEME_DEFAULT_CELL,[PRESET_SAVE]:{template:`{{ action "${PRESET_SAVE}" "+ preset" }}`},[DOCTOR_SEG]:{template:`{{ action "${DOCTOR_RUN_ACTION}" "🩺 doctor" }}`},[EDIT_SEG]:{template:`{{ action "${EDIT_TOGGLE_ACTION}" "✎ arrange" "✎ done" }}`}}};t.variables[THEME_DEFAULT_DIFFERS]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[THEME_DEFAULT_THEME]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[BACK_COUNT]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of SAVE_COUNTS)t.variables[saveCountVar(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[TAB_KEY]=disclosureStateVar(TAB_KEY,DISCLOSURE_CLOSED);for(let{member:e,label:n}of TABS){t.actions[tabToggle(e)]=disclosureCycleAction(TAB_KEY,e),t.actions[tabSeg(e)]={do:[tabToggle(e),...TAB_DISARMS]};let r=markedDisplay(e);t.segments[tabSeg(e)]={template:`{{ ${disclosureTriggerCall(tabSeg(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,COMMANDS.variables,RESET_ALL.variables),declareSettingControls(t),declareDoctorRows(t),t}function declareDoctorRows(e){for(let t of CHECKS){let n=doctorReportKeys(t.name),r=doctorFixAction(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?GLYPH_MARKS:[];for(let n of i)e.actions[doctorMarkAction(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${doctorMarkAction(t.name,e)}" "${MARK_GLYPH[e]}" }}`).join(``);e.segments[doctorRowSeg(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} "${BOOLEAN_TRUE}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function declareSettingControls(e){for(let t of CONTROLS){Object.assign(e.actions,t.control.actions);let n=controlReset(t.name);e.actions[n]={reset:t.configKey},e.variables[controlResettable(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${controlResettable(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[controlSeg(t.name)]={template:`${t.control.template}${TRAIL[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[controlRow(t.name,r)]=n})}Object.assign(e.actions,RESET_ALL.actions),Object.assign(e.variables,HELP_ARTIFACTS.variables),Object.assign(e.actions,HELP_ARTIFACTS.actions),Object.assign(e.segments,HELP_ARTIFACTS.segments);for(let t of SUBMENU_NAMES){let n=submenuRef(t);e.actions[submenuToggle(t)]=disclosureCycleAction(n.key,n.member),e.segments[submenuSeg(t)]={template:`{{ action "${submenuToggle(t)}" ${markedDisplay(t)(SUBMENUS[t].trigger)} }}`}}}function ensureEditToggle(e){let{variables:t,actions:n}=editModeArtifacts();Object.assign(e.variables,t),Object.assign(e.actions,n)}function synthesizeSettingsMenu(e){let t=settingsArtifacts(e.globals.menuGlyph??`🍫`);ensureEditToggle(t);let n={...e.presets};for(let t of presetNames(e.presets)){let{node:r}=presetRoot(e,t),i=expandAnchor(withAnchor(r));n[t]={...presetByName(e.presets,t),root:i}}return{...e,variables:{...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const EDIT_LIVE_KEY=`${EDIT_NS}live`,EDIT_LIVE_DISPLAY=[`☐ live`,`☑ live`],EDIT_DONE_SEG=`${EDIT_NS}done`,EDIT_CANCEL_SEG=`${EDIT_NS}cancel`,EDIT_REWIND_ACTION=`${EDIT_NS}rewind`,EDIT_CHANGES_VAR=`${EDIT_NS}changes`,CHANGED=`(gt .${EDIT_CHANGES_VAR} 0)`,TO_KEEP=`(or ${CHANGED} (gt .${UNSAVED_VAR} 0))`,EDIT_LIVE_REF={variable:EDIT_LIVE_KEY,key:EDIT_LIVE_KEY,member:DISCLOSURE_OPEN};function configuringVar(e){return`${EDIT_NS}configuring.p${e}`}function namesView(e){return`and ${disclosureTerm(EDIT_MODE_REF)} (not ${disclosureTerm(EDIT_LIVE_REF)}) (ne .${configuringVar(e)} "true")`}function configuringDecl(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${EDIT_CONFIGURE_KEY} "${escapeTemplateLiteral(e)}")`).join(` `)} false }}`}}function inNamesView(e,t,n){return`{{ if ${namesView(e)} }}${t}{{ else }}${n}{{ end }}`}const PRESET_CUSTOMIZED_VAR=`preset.customized`,CUSTOMIZED_BANNER_GATE=`{{ and ${disclosureTerm(EDIT_MODE_REF)} .${PRESET_CUSTOMIZED_VAR} }}`,isChromeExempt=isReservedName;function configOptionDomains(e){return new Map([...perConfigDomainsFor(e),...addableSegmentDomains(e)])}const ADDABLE_DOMAIN=`${EDIT_NS}addable`;function addableSegmentDomains(e){return new Map([[ADDABLE_DOMAIN,{members:Object.keys(e.segments).filter(e=>!isChromeExempt(e)),library:{groups:LIBRARY_GROUPS.map(e=>({id:e,label:GROUP_LABELS[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function chromeCell(e,t,n){return n.segments[e]={template:t,when:EDIT_MODE_GATE,bg:NO_FILL},{kind:`segment`,name:e}}function removeTerm(e,t,n){let r=`${EDIT_NS}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${TEXT_MIN_CONTRAST}`}) (action "${r}" "✖") }}`}function inArrangeMode(e){return`{{ if ${disclosureTerm(EDIT_MODE_REF)} }}${e}{{ end }}`}function shownWhile(e,t){return e.reduce((e,t)=>`{{ if and ${disclosureTerm(EDIT_MODE_REF)} ${disclosureTerm(t)} }}true{{ else }}${e}{{ end }}`,t)}function configureRefsIn(e){return e.flatMap(e=>[...walkNodes(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function placementDraftKey(e,t,n){return`${PLACEMENT_DRAFT_NS}${e}.${t}.${n}`}function configureParts(e,t,n,r){let i=placementId(n),a=`${EDIT_NS}${e.presetIdent}`,o=configureMember(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=sharedMenuStateKey(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:DISCLOSURE_CLOSED},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:EDIT_CONFIGURE_KEY,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=placementDraftKey(e.presetIdent,i,r),l=`${PLACEMENT_DRAFT_NS}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:settingSpelling(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=settingControl(controlDeclOf(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 disclosureNode(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${CONFIGURE_GLYPH}" }}`,ref:{variable:EDIT_CONFIGURE_KEY,key:EDIT_CONFIGURE_KEY,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const LABEL_NS=`${EDIT_NS}label:`;function arrangedSegment(e){if(e.startsWith(LABEL_NS)){let t=e.slice(LABEL_NS.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function labelChrome(e,t,n,r){let i=placementId(e),a=labelSegment(n,i,e,t,i),o=Object.fromEntries(IMPLIED_SETTINGS.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...disclosureNode(a,r.ref,r.body,`drop`,shownWhile([r.ref],`{{ ${namesView(n.presetIdent)} }}`)),...Object.keys(o).length>0&&{settings:o},drafts:Object.fromEntries(IMPLIED_SETTINGS.map(e=>[e,r.drafts[e]]))}}function labelSegment(e,t,n,r,i){let a=`${LABEL_NS}${t}:${n.name}`;return e.artifacts.segments[a]={template:`{{ "${escapeTemplateLiteral(i)}" }}`,...r.palette!==void 0&&{palette:r.palette}},a}function editableUnit(e,t,n,r){let i=placementId(e),a=n?[insertTerm(r,String(r.posCounter.n++),i,`before`)]:[],o=String(r.posCounter.n++),s=insertTerm(r,o,i,`after`),c=removeTerm(r,o,i),l=r.segments[e.name],u=configureParts(r,o,e,settingsOf(l)),d=inArrangeMode(c),f=inArrangeMode(u.term);return[...a.map(e=>chromeCell(e.host,e.template,r.artifacts)),{...labelChrome(e,l,r,u),lead:d,trail:f},{...t,when:inNamesView(r.presetIdent,`false`,e.when??`true`),lead:d,trail:f,drafts:u.drafts},chromeCell(s.host,s.template,r.artifacts)]}function fileLabel(e){return path.join(path.basename(path.dirname(e)),path.basename(e))}function insertedUnit(e,t,n,r){let i=r.segments[e.name],a=placementId(e);return[{kind:`segment`,name:labelSegment(r,`${a}/${r.presetIdent}`,e,i,`${a} · ${fileLabel(t.file)} ${t.entry}`),when:`{{ ${namesView(r.presetIdent)} }}`},{...n,when:inNamesView(r.presetIdent,`false`,e.when??`true`)}]}function insertTerm(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${EDIT_NS}${i}.insert.${t}`,s=`${EDIT_NS}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:ADDABLE_DOMAIN,anchor:n,relation:r};let c=menuMember(o),l=menuStateKey(s,o,void 0),u=menuPageKey(l),d=menuActionName(l,c);return a.variables[l]={...disclosureStateVar(l,DISCLOSURE_CLOSED),within:[EDIT_MODE_REF]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=disclosureCycleAction(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${disclosureTerm({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${TEXT_MIN_CONTRAST}`}) $m }}{{ end }}`}}function spliceContainer(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!isChromeExempt(e.name)&&e.insertedBy===void 0),i=e=>spliceContainer(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=mapOpens(o,i);if(isChromeExempt(o.name)){n.push(s);continue}let c={kind:`container`,direction:`horizontal`,children:o.insertedBy===void 0?editableUnit(o,s,a===r,t):insertedUnit(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:shownWhile(configureRefsIn(n),inNamesView(t.presetIdent,`true`,e.when))}}}function wrapWithPresetRows(e,t,n,r,i,a,o){let s=`${EDIT_NS}${t}.resetLayout`,c=`${EDIT_NS}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:CUSTOMIZED_BANNER_GATE},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},withTrailingCell(e,o)]}}function withTrailingCell(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),withTrailingCell(n,t)]}:{...e,children:[...e.children,t]}}function spliceEditChromeForPreset(e,t,n,r,i,a){let{node:o}=presetRoot(e,t),s={presetIdent:ident(t),rootKey:presetRootKey(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=spliceContainer(o,s);return n.variables[configuringVar(s.presetIdent)]=configuringDecl(s.configured),wrapWithPresetRows(c,s.presetIdent,s.rootKey,n,r,i,a)}function synthesizeEditChrome(e){let t={variables:{},actions:{},segments:{}},n=declareHelp(`${EDIT_NS}help`,EDIT_MODE_HELP,[EDIT_MODE_REF],t);t.variables[EDIT_LIVE_KEY]=disclosureStateVar(EDIT_LIVE_KEY,DISCLOSURE_CLOSED),t.actions[EDIT_LIVE_KEY]=disclosureCycleAction(EDIT_LIVE_KEY,EDIT_LIVE_REF.member),t.segments[EDIT_LIVE_KEY]={template:disclosureTrigger(EDIT_LIVE_KEY,...EDIT_LIVE_DISPLAY),when:EDIT_MODE_GATE};let r={kind:`segment`,name:EDIT_LIVE_KEY},i=n;t.variables[EDIT_CHANGES_VAR]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[EDIT_DONE_SEG]={do:[SAVE_SEG,EDIT_TOGGLE_ACTION]},t.segments[EDIT_DONE_SEG]={template:`{{ if ${TO_KEEP} }}{{ action "${EDIT_DONE_SEG}" "✓ save" }}{{ else }}{{ action "${EDIT_DONE_SEG}" "✓ done" }}{{ end }}`,when:EDIT_MODE_GATE},t.actions[EDIT_REWIND_ACTION]={rewind:!0},t.actions[EDIT_CANCEL_SEG]={do:[EDIT_REWIND_ACTION,EDIT_TOGGLE_ACTION]},t.segments[EDIT_CANCEL_SEG]={template:`{{ action "${EDIT_CANCEL_SEG}" "↩ cancel" }}`,when:`{{ and ${disclosureTerm(EDIT_MODE_REF)} ${CHANGED} }}`};let a=[{kind:`segment`,name:EDIT_DONE_SEG},{kind:`segment`,name:EDIT_CANCEL_SEG}],o={...e.presets};for(let n of presetNames(e.presets)){let s=spliceEditChromeForPreset(e,n,t,a,r,i);o[n]={...presetByName(e.presets,n),root:s}}return{...e,variables:{...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function encodeLayoutOp(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function decodeLayoutOp(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 mintPlacement(e,t,n){let r=freePlacementId(e,new Set(n.map(placementIds).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const INT_RE=/^-?\d+$/;function makeAllowListValidator(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 makeIntValidator(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!INT_RE.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 makeRangeValidator(e,t,n){return r=>r?INT_RE.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 mergeKeySpecs(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=>!INT_RE.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 wireForNoun(e){return e===`config`?`set-config`:`set-state`}function validatorForSpec(e,t,n){return t.kind===`int`?makeIntValidator(`menu page "${e}"`):t.kind===`range`?makeRangeValidator(t.min,t.max,`${n} stepper "${e}"`):makeAllowListValidator(t.allowed,`${n} "${e}"`,wireForNoun(n))}function mergeContributions(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:mergeKeySpecs(e,n,t)}))}function createGate(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 mergeContributions(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,validatorForSpec(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 createKeyspace(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};createGate(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=createGate(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}function makeConfigKeyspace(){return createKeyspace({},`config`,deriveConfigActionValidators)}function actionKeySpecs$1(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:resolveOptionDomain(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:[encodeLayoutOp({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[encodeLayoutOp({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:resolveOptionDomain(e.insertSegmentFrom,t).members.map(t=>encodeLayoutOp({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function clearableContributions(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?parsePersistTarget(n.persist):null;e?.scope===`preset-root`&&t.add(presetRootKey(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function actionContributions$1(e){let t=configOptionDomains(e);return[...clearableContributions(e),...Object.values(e.actions).flatMap(e=>actionKeySpecs$1(e,t))]}function deriveConfigActionValidators(e){return mergeContributions(actionContributions$1(e),`config`)}const RESOLVABLE_THEMES_LIST=listResolvablePaletteNames(),RESOLVABLE_THEMES=new Set(RESOLVABLE_THEMES_LIST),RESOLVABLE_ENDCAPS=new Set(ENDCAPS_SHAPES),validateTheme=e=>e?RESOLVABLE_THEMES.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${RESOLVABLE_THEMES_LIST.join(`, `)})`}:{ok:!1,reason:`theme name is required`},validateEndcaps=e=>e?RESOLVABLE_ENDCAPS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${ENDCAPS_SHAPES.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},BASELINE={endcaps:validateEndcaps,theme:validateTheme};function makeStateKeyspace(){return createKeyspace(BASELINE,`state`,deriveActionValidators)}function actionKeySpecs(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:resolveOptionDomain(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 dropBaselineAllowLists(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(BASELINE,e.key))}function actionContributions(e){let t=configOptionDomains(e);return dropBaselineAllowLists(Object.values(e.actions).flatMap(e=>actionKeySpecs(e,t)))}function deriveActionValidators(e){return mergeContributions(actionContributions(e))}function createGates(e){let t=makeStateKeyspace(),n=makeConfigKeyspace();for(let{key:n,allowed:r}of e.state)t.register(n,r);for(let{key:t,allowed:r}of e.config)n.register(t,r);return{state:t,config:n}}const UPDATE_DISMISSED_KEY=`update.dismissed`,UPDATE_NOTICE_FIELD=`updateNotice`,UPDATE_NOTICE_SESSION_KEY=SETTINGS.updateNotice.sessionKey;function daemonGates(){return createGates({config:[{key:UPDATE_NOTICE_FIELD,allowed:[`false`]}],state:[{key:UPDATE_NOTICE_SESSION_KEY,allowed:[`false`]},{key:UPDATE_DISMISSED_KEY,allowed:[]}]})}function updateIdentity(e){return e.kind===`source`?e.newer.digest:formatVersion(e.newer)}const describeStamp=e=>`${e.version} [${shortDigest(e.digest)}]`;function wordsOf(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:describeStamp(e.newer),running:describeStamp(e.running),act:`rebuild`,busy:`rebuilding…`};case`release`:return{headline:`Newer release`,newer:formatVersion(e.newer),running:formatVersion(e.running),act:`upgrade`,busy:`upgrading…`}}}const NO_NOTICE={offer:[],failure:[]};function updateNotice(e,t,n){if(e===null)return NO_NOTICE;let r=updateIdentity(e);if(!n.enabled||n.dismissed===r)return NO_NOTICE;let i=wordsOf(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[(e=>({about:`update-failed\0${r}`,text:e,copy:e}))(`${i.act} failed: ${t.reason}`)]:[],s=t.kind===`running`?diagnosticSpan(`[${i.busy}]`,null):diagnosticSpan(`[${i.act}]`,effectsUrl([{verb:VERB_APPLY_UPDATE,args:[n.sessionId]}])),c=[diagnosticSpan(a,null),s,diagnosticSpan(`[dismiss]`,effectsUrl([{verb:VERB_SET_STATE,args:[n.sessionId,UPDATE_DISMISSED_KEY,r]}])),diagnosticSpan(`[disable]`,effectsUrl([{verb:VERB_SET_CONFIG,args:[n.sessionId,UPDATE_NOTICE_FIELD,`false`]},{verb:VERB_SET_STATE,args:[n.sessionId,UPDATE_NOTICE_SESSION_KEY,`false`]}]))];return{offer:[{severity:UPDATE_SEVERITY,about:`update\0${r}`,message:a,copy:a,lines:[c]}],failure:o}}function commandOf(e){switch(e.kind){case`source`:return{bin:`pnpm`,args:[`build`],cwd:e.root};case`release`:return{bin:`pnpm`,args:[`dlx`,`${PACKAGE_NAME}@${formatVersion(e.newer)}`,`install`]}}}function updateReading(e,t){if(e.kind===`pending`)return e;let n=e.value;switch(n.kind){case`stale`:return ok$1({kind:`source`,root:n.root,newer:n.source,running:n.running});case`current`:return ABSENT$2;case`unchecked`:return failed$2(`build: unchecked: ${n.reason}`,`read`);case`not-source-checkout`:return releaseReading(t)}}function releaseReading(e){if(e.kind===`pending`)return e;let t=e.value;switch(t.kind){case`stale`:return ok$1({kind:`release`,newer:t.latest,running:t.installed});case`current`:case`ahead`:return ABSENT$2;case`unchecked`:return failed$2(`release: unchecked: ${t.reason}`,`read`)}}const ACT_TIMEOUT_MS=600*1e3,ACT_POLL_MS=2e3;function describeBuild(e){switch(e.kind){case`current`:return[`info`,`build: current ${describeStamp(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${describeStamp(e.source)}, running ${describeStamp(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function describeRelease(e){switch(e.kind){case`current`:return[`info`,`release: current ${formatVersion(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${formatVersion(e.latest)}, running ${formatVersion(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${formatVersion(e.installed)}, latest ${formatVersion(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function makeUpdateWatch(e){let{fact:t,clock:n,launcher:r,probe:i,entryUrl:a,digest:o,actsDir:s,intervalMs:c,releaseIntervalMs:l,registryUrl:u,fetchImpl:d,onApplied:f,log:p}=e,m=pendingOf(`unread`),h=pendingOf(`unread`),g=async e=>{let t=await i.startTime(e);if(E)throw new DaemonClosing(`apply-update`);return t},_=makeActReader(s,g,r,n),v=null,y=null,b=import_dist$1.observable.box({act:IDLE,actsError:null},{deep:!1,equals:import_dist$1.compareStructural}),x=()=>(0,import_dist$1.runInAction)(()=>b.set({act:v??IDLE,actsError:y})),S=changeLogger(p),C=changeLogger(p),w=new KeyedSerialQueue,T=e=>w.run(`acts`,e),E=!1,D=[],O=(e,t)=>{D.push(n.every(t,e,{unref:!0}))},k=()=>{let e=t.get();return e.kind===`ok`?e.value:null};function A(){let e=E?ABSENT$2:updateReading(m,h),r=restamp(t.get(),e,instantAt(n));(0,import_dist$1.runInAction)(()=>t.set(r))}function j(){let e=assessBuild(a,()=>bundleStamp(o));return m=ok$1(e),S(describeBuild(e)),A(),e}async function M(){let e=assessCurrency(PACKAGE_VERSION,await fetchLatestVersion(PACKAGE_NAME,d,u,n));h=ok$1(e),C(describeRelease(e)),A()}let N=changeLogger(p);async function F(e){try{let t=await e();return y=null,x(),{ok:!0,value:t}}catch(e){return e instanceof DaemonClosing?{ok:!1,error:e.message}:(y=`update act files (${s}): ${e.message}`,x(),N([`error`,y]),{ok:!1,error:y})}}function ee(e){if(!e?.alive||n.now()<=e.record.deadline)return;let{stands:t,signalled:i}=endOverdue(s,e,r),a=t?`timed out`:`outlived its verdict`,o=i?`ending it`:`its group took no signal`;p(`error`,`apply-update: act ${e.act} ${a}; ${o}`)}async function te(){let e=await F(async()=>{let e=await _.read();return E||ee(e),e});if(E||!e.ok)return;let t=judgeAct(e.value),n=v;v=t,n===null&&t.kind===`running`&&p(`info`,`apply-update: act ${t.act} is running; watching it`);let r=n?.kind===`running`&&t.kind!==`running`,i=r&&t.kind===`succeeded`;i&&p(`info`,`apply-update: act ${t.act} succeeded`),r&&t.kind===`failed`&&p(`error`,`apply-update: act ${t.act} failed: ${t.reason}`),(0,import_dist$1.runInAction)(()=>{i&&j(),x()}),i&&f()}let ne;async function I(){await T(te),!E&&(ne=n.after(ACT_POLL_MS,()=>void I(),{unref:!0}))}return{arm(){let e=j();O(j,c),D.push(()=>ne?.()),I(),e.kind===`not-source-checkout`&&(M(),O(()=>void M(),l))},close(){E=!0,A(),D.forEach(e=>e())},acts:()=>b.get(),running:()=>T(async()=>{let e=await F(()=>_.read());return e.ok&&judgeAct(e.value).kind===`running`}),act:()=>T(async()=>{if(E)throw new DaemonClosing(`apply-update`);let e=await F(()=>_.read());if(E)throw new DaemonClosing(`apply-update`);if(!e.ok)throw new BadVerbArgs(`apply-update: ${e.error}`);let t=k();if(t===null)throw new BadVerbArgs(`apply-update: nothing newer is known to apply`);let i=wordsOf(t),a=commandOf(t),o=e.value;if(judgeAct(o).kind===`running`)throw new BadVerbArgs(`apply-update: already ${i.busy}`);let c=await claimAct(r,s,o===null?null:o.act,updateIdentity(t),{...a,category:`update.apply`},ACT_TIMEOUT_MS,n.now(),g);if(!c.ok)throw new BadVerbArgs(`apply-update: ${c.reason}`);p(`info`,`apply-update: act ${c.act}: ${i.act} — ${a.bin} ${a.args?.join(` `)??``}`),v={kind:`running`,act:c.act},x()})}}function newUpdateFact(){return import_dist$1.observable.box(pendingOf(`unread`),{deep:!1})}function mtimeOf(e,t){try{return ok$1(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?ABSENT$2:failed$2(e.message,`read`)}}function sameStamp(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function makeBinaryWatch(e){let{targets:t,intervalMs:n,stat:r,held:i,exit:a,log:o,clock:s}=e,c=changeLogger(o),l=t.map(e=>({path:e,stamp:mtimeOf(e,r)})),u=l.filter(({stamp:e})=>e.kind!==`failed`),d=null,f=!1,p=()=>{f=!0,d?.()},m=async()=>{if(!f)for(let{path:e,stamp:t}of u){let n=mtimeOf(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!sameStamp(t,n)){let t=`binary ${n.kind===`absent`?`gone`:`changed`} (${e})`,r=await i();if(f)return;if(r){c([`info`,`${t}; the restart waits for the running update`]);return}o(`info`,`${t}; shutting down`),p(),a();return}}},h=()=>m().catch(e=>{o(`error`,`binary check failed: ${e.message}`)});return{arm(){for(let{path:e,stamp:t}of l)t.kind===`failed`&&o(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);d=s.every(n,()=>void h(),{unref:!0})},checkNow:h,close:p}}var TrailingEdge=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 GIT_PERIOD_MS=3e4,RESOLUTION_TTL_MS=3e4,DEFAULT_MAX_REPOS=64,PASS=`pass`,PR_PERIOD={okMs:5*6e4,failedMs:45e3},PR_BACKOFF_CEILING_MS=PR_PERIOD.okMs,DEFAULT_PR_LOOKUPS=2,PR_KEYS_KEPT=16;function prPeriodOf({failures:e}){return backedOffMs(PR_PERIOD,e,PR_BACKOFF_CEILING_MS)}function triggerOf(e){return e.includes(`first`)?`first`:e.length===0?`period`:`change`}function holdKey(e){return`git:${e}`}function watchSpec(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:path.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>boundOf$1(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${boundKey(i[t])}`).join(`|`)}`,targets:{dirs:r},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function branchOf(e){return e.kind===`ok`?e.value.branch:void 0}function owe(e){e.missed=!0,renew(e,`unread`)}function unkeyedPr(e,t){return e.missed&&e.reading.get().kind===`pending`&&settle$1(e,t.size>0?failed$2([...t].join(`; `),`read`):ABSENT$2),`unkeyed`}function composed({value:e,pr:t}){let n=currentOf(e);return n.kind===`ok`?ok$1({...n.value,pullRequest:currentOf(t)}):n}const CLOSED=failed$2(`git cache closed`,`read`);function threw(e){return t=>failed$2(`${e} threw: ${String(t)}`,`read`)}var GitDataProvider=class{repos=new Map;resolutions=new Map;closed=!1;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;forgeLookups;watchers;ownsWatchers;logger;clock;constructor(e){this.inner=e.inner,this.clock=e.clock,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??DEFAULT_MAX_REPOS,this.forgeLookups=new Limiter(e.maxPrLookups??DEFAULT_PR_LOOKUPS),this.logger=e.logger??quietLogger;let t=e.ledger??new RefreshLedger(this.logger);this.gitRefreshes=t.declare({name:`git`,scope:`repo`,refresh:[`first`,`period`,`change`],lines:[`first`,`period`,`change`]}),this.prRefreshes=t.declare({name:`pr`,scope:`repo`,refresh:[`first`,`period`],lines:[`first`,`period`]}),e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new WatcherRegistry({clock:this.clock,logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=this.clock.monotonic(),i=this.resolutions.get(n);if(i&&r-i.computedAt<RESOLUTION_TTL_MS)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=failed$2(`resolver threw: ${String(e)}`,`read`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n){let r=this.asked(e,t,n);if(r.kind===`settled`)return settledLane(r.outcome);let{state:i}=r;return i.value.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>composed(i)}}asked(e,t,n){if(this.closed)return{kind:`settled`,outcome:CLOSED};let r=this.resolution(t,n);return r.kind===`ok`?{kind:`asked`,state:this.ask(r.value,e)}:{kind:`settled`,outcome:r}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){t.value.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))}built(e){let t={period:new Period(()=>{this.readPr(n,t,`period`)},this.clock),seen:new Map,missed:!0,key:``,remote:ABSENT$2,reading:unread(),inFlight:null},n={root:e,refresh:new TrailingEdge,watch:this.followWatch(e,null).watch,period:new Period(()=>{n.refresh.share(PASS,()=>this.refreshPass(n))},this.clock),value:{reading:unread(),missed:!1},pr:t,holders:0,asked:new Set};return this.repos.set(e,n),n}followWatch(e,t){let n=this.inner.resolveGitDir(e),r=watchSpec(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(PASS,()=>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){return e.holders++,e.value.missed&&(owe(e.pr),e.asked.add(`resume`)),e.pr.missed&&e.pr.key!==``&&e.asked.add(`owed`),this.held(e),this.evict(),()=>{e.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(PASS,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr.period.hold(e.holders>0&&!e.pr.missed)}ask(e,t){let n=this.repos.get(e);n!==void 0&&this.touch(n);let r=n??this.built(e),i=r.asked.size;return n===void 0&&r.asked.add(`first`),t.take(holdKey(e),()=>this.hold(r)),this.queue(r,i),r}async pass(e){if(this.repos.get(e.root)!==e)return;let t=this.clock.monotonic(),n=[...e.asked];e.asked.clear();let r=this.followWatch(e.root,e.watch);e.watch=r.watch;let[i,a]=await Promise.all([this.inner.getGitInfo(e.root).catch(threw(`git fetch`)),this.remoteOf(e)]);if(this.repos.get(e.root)!==e)return;let o=new Set;if(e.value.missed=!1,settle$1(e.value,i),i.kind===`failed`&&o.add(i.reason),i.kind===`ok`)for(let e of gitInfoFailures(i.value))o.add(e);let s=branchOf(i),c=s===void 0?unkeyedPr(e.pr,o):this.movePr(e,s,a);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} pr=${c} watch=${r.move}`,triggerOf(n),o.size===0?ok$1(null):failed$2([...o].join(`; `),`read`),elapsedMs(this.clock,t))}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(threw(`git remote`))}movePr(e,t,n){let{pr:r}=e,i=`${t}|${n.kind===`ok`?n.value:n.kind}`;if(i===r.key&&!r.missed)return`kept`;r.key=i,r.remote=n;let a=r.seen.get(i);return a===void 0?e.holders===0?(owe(r),`owed`):(renew(r,`unread`),r.missed=!1,this.readPr(e,r,`first`),`looked-up`):(r.seen.delete(i),r.seen.set(i,a),r.missed=!1,settle$1(r,a.outcome),r.period.landed(prPeriodOf(a),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=this.clock.monotonic(),o=(i.kind===`ok`?this.forgeLookups.run(()=>(a=this.clock.monotonic(),this.inner.resolvePullRequest(e.root,i.value))).catch(threw(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:ABSENT$2)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${valueOf$1(r)}`,n,i,elapsedMs(this.clock,a));let o=this.clock.monotonic(),s={outcome:i,at:o,failures:i.kind===`failed`?(t.seen.get(r)?.failures??0)+1:0};t.seen.delete(r),t.seen.set(r,s);for(let e of t.seen.keys()){if(t.seen.size<=PR_KEYS_KEPT)break;t.seen.delete(e)}t.key!==r||t.missed||(settle$1(t,i),t.period.landed(prPeriodOf(s),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=failed$2(`git state dropped: ${e.root}`,`read`);answerPending(e.value,t),answerPending(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watch.handle.release(),e.period.dispose(),e.pr.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){this.closed=!0;for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},CacheManager=class{static usageDir(e){return path.join(e,`usage`)}static locksDir(e){return path.join(e,`locks`)}static isLocked(e,t){let n=path.join(this.locksDir(e),t);if(!fs.existsSync(n))return!1;try{let e=fs.readFileSync(n,`utf-8`),r=parseInt(e.trim(),10);if(isNaN(r))return debug(`Invalid PID in lock file ${t}, removing stale lock`),fs.unlinkSync(n),!1;try{return process.kill(r,0),!0}catch(e){return e.code===`ESRCH`?(debug(`Removing stale lock file ${t} for dead process ${r}`),fs.unlinkSync(n),!1):(debug(`Error checking process ${r} for lock ${t}:`,e),!0)}}catch(e){return debug(`Error reading lock file ${t}:`,e),!0}}static async acquireLock(e,t,n,r=5e3){let i=50,a=`wx`;await this.ensureCacheDirectories(e);let o=path.join(this.locksDir(e),n),s=t.monotonic(),c=String(process.pid);for(;t.monotonic()-s<r;)try{return await fs.promises.writeFile(o,c,{flag:`wx`}),debug(`Lock acquired for ${n}`),!0}catch(e){if(e.code===`EEXIST`)await sleep(t,50);else throw e}return debug(`Failed to acquire lock for ${n} within ${r}ms`),!1}static async releaseLock(e,t){let n=path.join(this.locksDir(e),t);try{await fs.promises.unlink(n),debug(`Lock released for ${t}`)}catch(e){e.code!==`ENOENT`&&debug(`Error releasing lock for ${t}:`,e)}}static async ensureCacheDirectories(e){try{await Promise.all([fs.promises.mkdir(e,{recursive:!0}),fs.promises.mkdir(this.usageDir(e),{recursive:!0}),fs.promises.mkdir(this.locksDir(e),{recursive:!0})])}catch(e){debug(`Failed to create cache directories:`,e)}}static createProjectHash(e){return createHash(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t,n,r){let i=3,a=75,o=`utf-8`;await this.ensureCacheDirectories(e);let s=path.join(this.usageDir(e),`${n}.json`),c=`${n}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(e,c)){debug(`Cache for ${n} is locked, waiting...`),await sleep(t,75);continue}try{let e=await fs.promises.readFile(s,`utf-8`),t=JSON.parse(e);return!r||t.timestamp>=r?(debug(`[CACHE-HIT] ${n} disk cache: found`),this.deserializeDates(t.data)):(debug(`${n} cache outdated: cache=${t.timestamp}, latest=${r}`),null)}catch(e){if(e.code===`ENOENT`)return debug(`No shared ${n} usage cache found`),null;debug(`Attempt ${i+1} failed to read ${n} cache: ${e.message}. Retrying...`),await sleep(t,75)}}return debug(`Failed to read ${n} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n,r,i){let a=`${n}.usage.lock`;if(!await this.acquireLock(e,t,a)){debug(`Could not acquire lock to set usage cache for ${n}`);return}try{await this.ensureCacheDirectories(e);let a=path.join(this.usageDir(e),`${n}.json`),o={data:r,timestamp:i||t.now()},s=JSON.stringify(o);await fs.promises.writeFile(a,s,`utf-8`),debug(`[CACHE-SET] ${n} disk cache stored`)}catch(e){debug(`Failed to save ${n} usage cache:`,e)}finally{await this.releaseLock(e,a)}}};const OFFLINE_PRICING_DATA={"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 PricingService=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(e,t){let n=t.now()-1440*60*1e3;return await CacheManager.getUsageCache(e,t,`pricing`,n)}static async saveDiskCache(e,t,n){await CacheManager.setUsageCache(e,t,`pricing`,n)}static async fetchPricingData(){return new Promise(e=>{let t=new URL$1(this.GITHUB_PRICING_URL),n=get({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){debug(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let r=``,i=0,a=1024*1024;t.setEncoding(`utf8`),t.on(`data`,t=>{if(i+=Buffer.byteLength(t),i>1048576){debug(`Response too large`),n.destroy(),e(null);return}r+=t}),t.on(`end`,()=>{try{let t=JSON.parse(r),n=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(debug(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),debug(`Pricing last updated: ${n?.updated||`unknown`}`),e(i)):(debug(`Invalid pricing data structure`),e(null))}catch(t){debug(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{debug(`Response error:`,t),e(null)})});n.on(`error`,t=>{debug(`Request error:`,t),e(null)}),n.on(`timeout`,()=>{debug(`Request timeout`),n.destroy(),e(null)}),n.end()})}static async getCurrentPricing(e,t){if(this.executionCache!==null)return debug(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let n=await this.loadDiskCache(e,t);if(n)return debug(`[CACHE-HIT] Pricing disk cache: ${Object.keys(n).length} models`),this.executionCache=n,debug(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(n).length} models`),n;let r=await this.fetchPricingData();return r?(await this.saveDiskCache(e,t,r),debug(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(r).length} models`),this.executionCache=r,debug(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(r).length} models`),r):(debug(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(OFFLINE_PRICING_DATA).length} models`),this.executionCache=OFFLINE_PRICING_DATA,debug(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(OFFLINE_PRICING_DATA).length} models`),OFFLINE_PRICING_DATA)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e,t,n){if(this.modelPricingCache.has(e))return debug(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let r=await this.getCurrentPricing(t,n),i;return i=r[e]?r[e]:this.fuzzyMatchModel(e,r),this.modelPricingCache.set(e,i),debug(`[CACHE-SET] Model pricing cache: ${e}`),i}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e,t,n){let r=e.message?.usage;if(!r)return 0;let i=this.extractModelId(e),a=await this.getModelPricing(i,t,n),o=r.input_tokens||0,s=r.output_tokens||0,c=r.cache_creation_input_tokens||0,l=r.cache_read_input_tokens||0,u=o/1e6*a.input,d=s/1e6*a.output,f=l/1e6*a.cache_read,p=c/1e6*a.cache_write_5m;return u+d+p+f}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const COMMAND_NAME=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function slashCommand(e){if(typeof e==`string`)return COMMAND_NAME.exec(e)?.[1]}function todoItems(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function turnText(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function entryActivity(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=todoItems(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?slashCommand(turnText(n)):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&o===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...o!==void 0&&{command:o}}}function getClaudePaths(e,t){return e===void 0?[join(t,`.config`,`claude`),join(t,`.claude`)].filter(e=>existsSync(e)):[e]}async function findProjectPaths(e){let t=[];for(let n of e){let e=join(n,`projects`),r=await unlessGone(readdir$1(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(join(e,n.name))}return t}async function unlessGone(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function findAgentTranscripts(e,t,n){let r=[],i=[],a=join(t,e,`subagents`);try{let t=(await readdir$1(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=join(a,o);if(n?.has(t)){r.push(t);continue}let s=await readAppended(t,void 0,void 0);if(s.kind!==`ok`){debug(`Failed to check agent file ${t}`);continue}i=longLinesWith(i,t,s.value);let c=jsonLine(decodeLines(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){debug(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function userEntryOf(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(firstBlockType(t)===`tool_result`)return`tool-result`;let n=typeof e.origin==`object`&&e.origin!==null?e.origin.kind:void 0;if(n!==void 0&&n!==`human`)return`turn`;let r=turnText(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||CLAUDE_CODE_TEXT.test(r)?`claude-code`:`prompt`}const TURN_GOES_ON=new Set([void 0,`tool_use`,`pause_turn`]);function turnOpenAfter(e,t){if(t.isSidechain)return e;switch(t.userEntry){case`prompt`:case`turn`:return!0;case`interrupt`:return!1;case`tool-result`:case`claude-code`:return e;case void 0:return t.type===`assistant`?TURN_GOES_ON.has(t.message?.stopReason):e}}const CLAUDE_CODE_TEXT=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function firstBlockType(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function makeEntry(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=userEntryOf(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0,stopReason:typeof t.stop_reason==`string`?t.stop_reason:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:entryActivity(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function jsonLine(e){let t=e.trim();if(!t)return{kind:`blank`};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{kind:`object`,value:e}:{kind:`unparsed`,reason:`not a JSON object`}}catch(e){return{kind:`unparsed`,reason:String(e)}}}function entryOf(e){let t=jsonLine(e);if(t.kind===`unparsed`)return debug(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return makeEntry(t.value)}catch(e){return debug(`Failed to project JSONL line: ${e}`),null}}function parseJsonlLines(e){let t=[];for(let n of e.split(`
|
|
185
|
+
`,QUIET_PCT=60,QUIET_MIN_CONTRAST=3,QUIET_TEXT=`readableOn (mix (color "foreground") (bgOf) ${QUIET_PCT}) (bgOf) 3`,DOCTOR_NS=`${SETTINGS_NS}doctor.`,VERDICT_OK=`ok`,VERDICT_FAILED=`failed`;function doctorReportKeys(e){let t=`${DOCTOR_NS}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function configFields({target:e}){return`configTarget=${e.source}`}function linkFields(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?sightingOf(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 terminalFeatureFields(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 installFields(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}=clientStanding(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const signedMb=e=>`${e>=0?`+`:``}${mb(e)}`;function daemonFields({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${otherDaemons(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`:`${unreadPostMortems(e.value,n).length}/${o.value.length}`,c=i.kind===`unmeasured`?`unmeasured`:`${measureOf(i.charge)}${i.charge.kind===`stand-in`?`(${signedMb(-i.charge.gap)})`:``}:${mb(i.charge.bytes)}`,l=i.kind===`unmeasured`?`-`:i.processes.map(e=>`${e.role}:${e.pid}:${e.sizes===null?`-`:mb(e.sizes.rss)}`).join(`,`);return`${r} memory=${c}/${mb(a)} processes=${l} postMortems=${s}`}function dataFields(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 frameFields(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>statusLineValue(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${valueOf$1(i)}`;let a=refreshedFrames(r.flatMap(e=>e.bars));return`frames=${FRAMES_SEEN.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${valueOf$1(i)}`}function statusLineValue(e){let t=statusLineOf(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 truecolorEnvFields(e){let t=envVarOf(e,TMUX_TRUECOLOR_VAR);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${valueOf$1(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function transcriptFields(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 nerdFontFields(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=glyphSighting(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 rowReason(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function doctorReportPairs(e){return e.flatMap(({check:e,verdict:t})=>{let n=doctorReportKeys(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:BOOLEAN_FALSE},{key:n.sighting,value:``}]:[{key:n.verdict,value:VERDICT_FAILED},{key:n.reason,value:rowReason(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?BOOLEAN_FALSE:BOOLEAN_TRUE},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const QUICK_ACTIONS={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function quickActions(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }} {{ action "${t(`copyResume`)}" "⎘ resume" }} {{ 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(QUICK_ACTIONS).map(([t,n])=>[`${e}${t}`,n]))}}const ARMED=`armed`,DISARMED=`disarmed`,CONFIRM_KEY_SUFFIX=`.armed`,isConfirmKey=e=>e.endsWith(CONFIRM_KEY_SUFFIX);function confirms(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 confirmStep(e,t,n){let r=`${e}${CONFIRM_KEY_SUFFIX}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${ARMED}")`,s=confirms(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:ARMED},[a]:{set:r,to:DISARMED},...s.actions},armed:o,variables:{[e]:{kind:`state`,key:r,default:DISARMED}},disarm:a}}const SLASH_LINE_PATTERN=`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`,SLASH_LINE=new RegExp(SLASH_LINE_PATTERN);function parseSlashLine(e){return typeof e==`string`&&SLASH_LINE.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 slashLine(e){let t=parseSlashLine(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const COMMANDS$1=[`/compact`,`/model`],CLEAR=`/clear`;function commandTray(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=confirmStep(`${e}clear`,{arm:CLEAR,confirm:`${CLEAR} ✓ confirm`},[{action:n,when:`true`}]);return{template:COMMANDS$1.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${IN_TMUX} }}`,actions:{...Object.fromEntries(COMMANDS$1.map(e=>[t(e),{slash:slashLine(e)}])),...r.actions,[n]:{slash:slashLine(CLEAR)}},variables:r.variables,disarm:r.disarm}}const AUTOCOMPACT_WINDOWS=Array.from({length:10},(e,t)=>(t+1)*1e5),LEAST=AUTOCOMPACT_WINDOWS[0],MOST=AUTOCOMPACT_WINDOWS[AUTOCOMPACT_WINDOWS.length-1];function autoCompactControls(e,t){let n=Math.min(t??MOST,MOST),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:AUTOCOMPACT_WINDOWS.filter(e=>e<r).at(-1)??0,higher:AUTOCOMPACT_WINDOWS.find(e=>e>r&&e<=n)??0}}function autocompactControl(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${IN_TMUX} }}{{ 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:slashLine(`/autocompact auto`)},...Object.fromEntries(AUTOCOMPACT_WINDOWS.map(t=>[`${e}${t}`,{slash:slashLine(`/autocompact ${t}`)}]))}}}const formatTokenCount=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 }}`,EDIT_SEG=`${SETTINGS_NS}edit`,TOOLBAR_SEG=`${SETTINGS_NS}toolbar`,TOOLBAR=quickActions(SETTINGS_NS),COMMANDS_SEG=`${SETTINGS_NS}commands`,COMMANDS=commandTray(`${COMMANDS_SEG}.`),AUTOCOMPACT_SEG=`${SETTINGS_NS}autocompact`,AUTOCOMPACT$1=autocompactControl(`${AUTOCOMPACT_SEG}.`,formatTokenCount),seg=e=>({kind:`segment`,name:e}),TAB_KEY=`${SETTINGS_NS}tab`,tabSeg=e=>`${TAB_KEY}.${e}`,tabToggle=e=>`${tabSeg(e)}.toggle`,tabRef=e=>({variable:TAB_KEY,key:TAB_KEY,member:e}),SAVE_SEG=`${SETTINGS_NS}save`,PRESET_SAVE=`${SETTINGS_NS}preset.save`,PRESET_DELETE=`${SETTINGS_NS}preset.delete`,PRESET_DELETE_GLYPH=`🚮`,controlSeg=e=>`${SETTINGS_NS}${e}`,controlApply=e=>`${SETTINGS_NS}apply.${e}`,controlReset=e=>`${SETTINGS_NS}reset.${e}`,THEME_DEFAULT_SEG=`${SETTINGS_NS}themeDefault.save`,THEME_DEFAULT_DIFFERS=`${SETTINGS_NS}themeDefault.differs`,THEME_DEFAULT_THEME=`${SETTINGS_NS}themeDefault.theme`,THEME_DEFAULT_CELL={when:`{{ .${THEME_DEFAULT_DIFFERS} }}`,template:`{{ action "${THEME_DEFAULT_SEG}" (printf "⤓ default for %s" .${THEME_DEFAULT_THEME}) }} {{ swatch "${controlApply(`theme`)}" .${THEME_DEFAULT_THEME} }}`},RESET_ALL_SEG=`${SETTINGS_NS}resetAll`,DOOR_TOGGLE=`${SETTINGS_ANCHOR}.toggle`,UNDO_ACTION=`${SETTINGS_NS}undo`,BACK_ACTION=`${SETTINGS_NS}back`,BACK_STEP=`${BACK_ACTION}.step`,BACK_COUNT=`${SETTINGS_NS}navigation.back`,BACK_SEG=BACK_ACTION,BACK_GLYPH=`◁`,BACK_CELL={template:`{{ if gt .${BACK_COUNT} 0 }}{{ action "${BACK_ACTION}" "${BACK_GLYPH}" }}{{ else }}{{ fg (${QUIET_TEXT}) "${BACK_GLYPH}" }}{{ end }}`},REDO_ACTION=`${SETTINGS_NS}redo`,DOCTOR_SEG=`${SETTINGS_NS}doctor`,DOCTOR_RUN_ACTION=`${DOCTOR_SEG}.run`,doctorFixAction=e=>`${DOCTOR_SEG}.fix.${e}`,doctorMarkAction=(e,t)=>`${DOCTOR_SEG}.mark.${e}.${t}`,doctorRowSeg=e=>`${DOCTOR_SEG}.${e}`,MARK_GLYPH={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},PICKER_KEY=sharedMenuStateKey(`${SETTINGS_NS}pickers`),submenuSeg=e=>`${SETTINGS_NS}${e}`,submenuToggle=e=>`${submenuSeg(e)}.toggle`,accordionOf=e=>isSubmenu(e)?sharedMenuStateKey(`${SETTINGS_NS}${e}Pickers`):PICKER_KEY,submenuRef=e=>{let t=accordionOf(PLACE[SUBMENUS[e].beside]);return{variable:t,key:t,member:e}},PREVIEWS={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${PRESET_DELETE}" (printf "${PRESET_DELETE_GLYPH} delete %s" .${SETTINGS.preset.effectiveVar}) }}`}},controlRow=(e,t)=>`${SETTINGS_NS}list.${e}.${t}`,controlResettable=e=>`${SETTINGS_NS}resettable.${e}`,DRIFT_MARK=` •`,anyResettable=e=>e.length===0?`false`:`(or ${e.map(e=>`(and (${e.shown}) .${controlResettable(e.name)})`).join(` `)})`,laneSettings=LANE_NAMES.map(e=>[LANES[e].switch.setting,e]),HELP_ARTIFACTS={variables:{},actions:{},segments:{}},HELP=Object.fromEntries(laneSettings.map(([e,t])=>[e,declareHelp(`${SETTINGS_NS}help.${e}`,LANE_HELP[t],[],HELP_ARTIFACTS)])),SPINNER=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],laneReadout=e=>{let t=t=>`.${laneFeedVar(e,t)}`,n=SPINNER.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if eq .${SETTINGS[LANES[e].switch.setting].effectiveVar} ${JSON.stringify(LANES[e].switch.on)} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},DIAGNOSTICS_INDICATOR=`{{ if .diagnostics.label }} {{ bg .diagnostics.bg (fg .diagnostics.fg (action "${DIAGNOSTICS_VIEWING}" .diagnostics.label .diagnostics.open)) }}{{ end }}`,FPS_SEG=`${SETTINGS_NS}fps`,POLLED=`polled`,AT_MOST=`≤`,FPS_UNIT=` fps`,RATE_WIDTH=7,FRAME_RATE=`{{ if eq .${drawingVar(`by`)} "feed" }}{{ printf "%${RATE_WIDTH-4}s" (printf "${AT_MOST}%d" (int .${drawingVar(`fps`)})) }}${FPS_UNIT}{{ else }}${POLLED.padStart(RATE_WIDTH)}{{ end }}`,TRAIL=Object.fromEntries(laneSettings.map(([e,t])=>[e,laneReadout(t)])),submenusBeside=e=>SUBMENU_NAMES.filter(t=>SUBMENUS[t].beside===e),menuControl=e=>{let t=SETTINGS[e],n=PLACE[e];return{...t,name:e,place:n,control:settingControl({label:t.label,domain:settingControlDomain(t.configKey)},t.sessionKey,t.effectiveVar,controlApply(e),accordionOf(n)),beneath:t.previews.map(e=>PREVIEWS[e]),help:[HELP[e]].filter(e=>e!==void 0),submenus:submenusBeside(e)}},CONTROLS=Object.keys(SETTINGS).map(menuControl),controlsIn=e=>CONTROLS.filter(t=>t.place===e),controlsUnder=e=>CONTROLS.filter(t=>within$2(t.place,e)),markedDisplay=e=>t=>`(print ${templateLiteral(t)} (ternary ${templateLiteral(DRIFT_MARK)} "" ${anyResettable(controlsUnder(e))}))`,controlsAt=e=>controlsIn(e).flatMap(e=>[controlNode(e),...e.help,...e.submenus.map(e=>disclosureNode(submenuSeg(e),submenuRef(e),placeBody(e),`drop`))].map(t=>({...t,when:`{{ ${e.shown} }}`}))),SETTINGS_WRITTEN_KEYS=new Set(CONTROLS.flatMap(e=>[e.sessionKey,e.configKey])),RESET_ALL=confirmStep(RESET_ALL_SEG,{arm:`⟲`,confirm:`⟲ reset all?`},CONTROLS.map(e=>({action:controlReset(e.name),when:e.shown}))),SAVE_COUNTS=[`unsaved`,`history.undo`,`history.redo`],saveCountVar=e=>`${SETTINGS_NS}${e}`,UNSAVED_VAR=saveCountVar(`unsaved`),counted=(e,t)=>({body:t,shown:`(gt .${saveCountVar(e)} 0)`}),layerVar=e=>`${SETTINGS_NS}layers.${e}`,SAVE_LABEL=`(printf "💾 save %d" .${UNSAVED_VAR})`,SAVE_TO=LAYER_ROLES.map(e=>`{{ if .${layerVar(e)} }} {{ action "${SAVE_SEG}" "${e}" "${e}" }}{{ end }}`).join(``),SAVE_PARTS=[counted(`unsaved`,`{{ if or .${layerVar(`project`)} .${layerVar(`local`)} }}{{ ${SAVE_LABEL} }}:${SAVE_TO}{{ else }}{{ action "${SAVE_SEG}" ${SAVE_LABEL} "user" }}{{ end }}`),counted(`history.undo`,`{{ action "${UNDO_ACTION}" "↶" }}`),counted(`history.redo`,`{{ action "${REDO_ACTION}" "↷" }}`),{body:RESET_ALL.template,shown:`(or ${anyResettable(CONTROLS)} ${RESET_ALL.armed})`}],SAVE_CELL={when:`{{ or ${SAVE_PARTS.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+SAVE_PARTS.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},CONFIRMS=[{step:RESET_ALL,place:`door`},{step:COMMANDS,place:`session`}],disarms=e=>e.map(e=>e.step.disarm),DOOR_DISARMS=disarms(CONFIRMS),TAB_DISARMS=disarms(CONFIRMS.filter(e=>e.place!==`door`));function controlNode(e){let t=controlSeg(e.name);return e.control.kind===`inline`?seg(t):disclosureNode(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>seg(controlRow(e.name,n)))},`drop`)}function isSettingsAnchor(e){return e===SETTINGS_ANCHOR}function prependAnchor(e){let t=seg(SETTINGS_ANCHOR);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[prependAnchor(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 withAnchor(e){return countAnchors(e)>0?e:prependAnchor(e)}function countAnchors(e){let t=0;for(let n of walkNodes(e))n.kind===`segment`&&isSettingsAnchor(n.name)&&(t+=1);return t}function anchorUnderGate(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&isSettingsAnchor(e.name)||e.opens!==void 0&&anchorUnderGate(e.opens.body,!0):e.children.some(e=>anchorUnderGate(e,n))}const PLACE_BODY={door:{direction:`horizontal`,content:[seg(BACK_SEG)],after:[seg(EDIT_SEG),seg(SAVE_SEG)]},session:{direction:`vertical`,content:[seg(TOOLBAR_SEG),{kind:`container`,direction:`horizontal`,children:[seg(COMMANDS_SEG),seg(AUTOCOMPACT_SEG)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[seg(PRESET_SAVE)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[seg(DOCTOR_SEG),...CHECKS.map(e=>seg(doctorRowSeg(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[seg(THEME_DEFAULT_SEG)]},toggles:{direction:`horizontal`,content:[],after:[]}};function placeBody(e){let{direction:t,content:n,after:r}=PLACE_BODY[e];return{kind:`container`,direction:t,children:[...n,...controlsAt(e),...r]}}function expandAnchor(e){return e.kind===`segment`?isSettingsAnchor(e.name)?{kind:`container`,direction:`horizontal`,children:[disclosureNode(e.name,SETTINGS_REF,DOOR_BODY,`above`),seg(FPS_SEG)]}:e:expandContainer(e)}function doorBody(){return{kind:`container`,direction:`vertical`,children:[placeBody(`door`),{kind:`container`,direction:`horizontal`,children:TABS.map(({member:e})=>disclosureNode(tabSeg(e),tabRef(e),placeBody(e),`drop`))}]}}const DOOR_BODY=doorBody();function expandContainer(e){return{...e,children:e.children.map(e=>expandAnchor(e))}}function settingsArtifacts(e){let t={variables:{[SETTINGS_ANCHOR]:disclosureStateVar(SETTINGS_ANCHOR,DISCLOSURE_CLOSED),[DIAGNOSTICS_VIEWING]:{kind:`state`,key:DIAGNOSTICS_VIEWING,default:`0`}},actions:{[DOOR_TOGGLE]:disclosureCycleAction(SETTINGS_ANCHOR,SETTINGS_OPEN),[DIAGNOSTICS_VIEWING]:{set:DIAGNOSTICS_VIEWING,int:!0},[SETTINGS_ANCHOR]:{do:[DOOR_TOGGLE,...DOOR_DISARMS]},[DOCTOR_RUN_ACTION]:{doctor:`run`},...TOOLBAR.actions,...COMMANDS.actions,...AUTOCOMPACT$1.actions,[SAVE_SEG]:{save:!0,layer:`ask`},[UNDO_ACTION]:{undo:!0},[BACK_STEP]:{back:!0},[BACK_ACTION]:{do:[BACK_STEP,...DOOR_DISARMS]},[REDO_ACTION]:{redo:!0},[PRESET_SAVE]:{preset:`save`},[THEME_DEFAULT_SEG]:{themeDefault:`save`},[PRESET_DELETE]:{preset:`delete`,name:`{{ .${SETTINGS.preset.effectiveVar} }}`}},segments:{[SETTINGS_ANCHOR]:{template:`{{ $door := ${disclosureTriggerCall(SETTINGS_ANCHOR,templateLiteral(e),templateLiteral(`✖`))} }}{{ if ${disclosureTerm(SETTINGS_REF)} }}{{ fg (keptOn (roleTextOn "${DOOR_CLOSE_ROLE}" (bgOf)) (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+DIAGNOSTICS_INDICATOR},[FPS_SEG]:{template:FRAME_RATE},[TOOLBAR_SEG]:{template:TOOLBAR.template},[COMMANDS_SEG]:{template:COMMANDS.template,when:COMMANDS.when},[AUTOCOMPACT_SEG]:{template:AUTOCOMPACT$1.template,bg:AUTOCOMPACT$1.bg,when:AUTOCOMPACT$1.when},[BACK_SEG]:BACK_CELL,[SAVE_SEG]:SAVE_CELL,[THEME_DEFAULT_SEG]:THEME_DEFAULT_CELL,[PRESET_SAVE]:{template:`{{ action "${PRESET_SAVE}" "+ preset" }}`},[DOCTOR_SEG]:{template:`{{ action "${DOCTOR_RUN_ACTION}" "🩺 doctor" }}`},[EDIT_SEG]:{template:`{{ action "${EDIT_TOGGLE_ACTION}" "✎ arrange" "✎ done" }}`}}};t.variables[THEME_DEFAULT_DIFFERS]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[THEME_DEFAULT_THEME]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[BACK_COUNT]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of LAYER_ROLES)t.variables[layerVar(e)]={kind:`input`,path:`layers.${e}`,type:`boolean`,default:!1};for(let e of SAVE_COUNTS)t.variables[saveCountVar(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[TAB_KEY]=disclosureStateVar(TAB_KEY,DISCLOSURE_CLOSED);for(let{member:e,label:n}of TABS){t.actions[tabToggle(e)]=disclosureCycleAction(TAB_KEY,e),t.actions[tabSeg(e)]={do:[tabToggle(e),...TAB_DISARMS]};let r=markedDisplay(e);t.segments[tabSeg(e)]={template:`{{ ${disclosureTriggerCall(tabSeg(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,COMMANDS.variables,RESET_ALL.variables),declareSettingControls(t),declareDoctorRows(t),t}function declareDoctorRows(e){for(let t of CHECKS){let n=doctorReportKeys(t.name),r=doctorFixAction(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?GLYPH_MARKS:[];for(let n of i)e.actions[doctorMarkAction(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${doctorMarkAction(t.name,e)}" "${MARK_GLYPH[e]}" }}`).join(``);e.segments[doctorRowSeg(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} "${BOOLEAN_TRUE}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function declareSettingControls(e){for(let t of CONTROLS){Object.assign(e.actions,t.control.actions);let n=controlReset(t.name);e.actions[n]={reset:t.configKey},e.variables[controlResettable(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${controlResettable(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[controlSeg(t.name)]={template:`${t.control.template}${TRAIL[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[controlRow(t.name,r)]=n})}Object.assign(e.actions,RESET_ALL.actions),Object.assign(e.variables,HELP_ARTIFACTS.variables),Object.assign(e.actions,HELP_ARTIFACTS.actions),Object.assign(e.segments,HELP_ARTIFACTS.segments);for(let t of SUBMENU_NAMES){let n=submenuRef(t);e.actions[submenuToggle(t)]=disclosureCycleAction(n.key,n.member),e.segments[submenuSeg(t)]={template:`{{ action "${submenuToggle(t)}" ${markedDisplay(t)(SUBMENUS[t].trigger)} }}`}}}function ensureEditToggle(e){let{variables:t,actions:n}=editModeArtifacts();Object.assign(e.variables,t),Object.assign(e.actions,n)}function synthesizeSettingsMenu(e){let t=settingsArtifacts(e.globals.menuGlyph??`🍫`);ensureEditToggle(t);let n={...e.presets};for(let t of presetNames(e.presets)){let{node:r}=presetRoot(e,t),i=expandAnchor(withAnchor(r));n[t]={...presetByName(e.presets,t),root:i}}return{...e,variables:{...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const EDIT_LIVE_KEY=`${EDIT_NS}live`,EDIT_LIVE_DISPLAY=[`☐ live`,`☑ live`],EDIT_DONE_SEG=`${EDIT_NS}done`,EDIT_SAVE_ACTION=`${EDIT_NS}save`,EDIT_CANCEL_SEG=`${EDIT_NS}cancel`,EDIT_REWIND_ACTION=`${EDIT_NS}rewind`,EDIT_CHANGES_VAR=`${EDIT_NS}changes`,CHANGED=`(gt .${EDIT_CHANGES_VAR} 0)`,TO_KEEP=`(or ${CHANGED} (gt .${UNSAVED_VAR} 0))`,EDIT_LIVE_REF={variable:EDIT_LIVE_KEY,key:EDIT_LIVE_KEY,member:DISCLOSURE_OPEN};function configuringVar(e){return`${EDIT_NS}configuring.p${e}`}function namesView(e){return`and ${disclosureTerm(EDIT_MODE_REF)} (not ${disclosureTerm(EDIT_LIVE_REF)}) (ne .${configuringVar(e)} "true")`}function configuringDecl(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${EDIT_CONFIGURE_KEY} "${escapeTemplateLiteral(e)}")`).join(` `)} false }}`}}function inNamesView(e,t,n){return`{{ if ${namesView(e)} }}${t}{{ else }}${n}{{ end }}`}const PRESET_CUSTOMIZED_VAR=`preset.customized`,CUSTOMIZED_BANNER_GATE=`{{ and ${disclosureTerm(EDIT_MODE_REF)} .${PRESET_CUSTOMIZED_VAR} }}`,isChromeExempt=isReservedName;function configOptionDomains(e){return new Map([...perConfigDomainsFor(e),...addableSegmentDomains(e)])}const ADDABLE_DOMAIN=`${EDIT_NS}addable`;function addableSegmentDomains(e){return new Map([[ADDABLE_DOMAIN,{members:Object.keys(e.segments).filter(e=>!isChromeExempt(e)),library:{groups:LIBRARY_GROUPS.map(e=>({id:e,label:GROUP_LABELS[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function chromeCell(e,t,n){return n.segments[e]={template:t,when:EDIT_MODE_GATE,bg:NO_FILL},{kind:`segment`,name:e}}function removeTerm(e,t,n){let r=`${EDIT_NS}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${TEXT_MIN_CONTRAST}`}) (action "${r}" "✖") }}`}function inArrangeMode(e){return`{{ if ${disclosureTerm(EDIT_MODE_REF)} }}${e}{{ end }}`}function shownWhile(e,t){return e.reduce((e,t)=>`{{ if and ${disclosureTerm(EDIT_MODE_REF)} ${disclosureTerm(t)} }}true{{ else }}${e}{{ end }}`,t)}function configureRefsIn(e){return e.flatMap(e=>[...walkNodes(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function placementDraftKey(e,t,n){return`${PLACEMENT_DRAFT_NS}${e}.${t}.${n}`}function configureParts(e,t,n,r){let i=placementId(n),a=`${EDIT_NS}${e.presetIdent}`,o=configureMember(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=sharedMenuStateKey(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:DISCLOSURE_CLOSED},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:EDIT_CONFIGURE_KEY,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=placementDraftKey(e.presetIdent,i,r),l=`${PLACEMENT_DRAFT_NS}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:settingSpelling(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=settingControl(controlDeclOf(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 disclosureNode(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${CONFIGURE_GLYPH}" }}`,ref:{variable:EDIT_CONFIGURE_KEY,key:EDIT_CONFIGURE_KEY,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const LABEL_NS=`${EDIT_NS}label:`;function arrangedSegment(e){if(e.startsWith(LABEL_NS)){let t=e.slice(LABEL_NS.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function labelChrome(e,t,n,r){let i=placementId(e),a=labelSegment(n,i,e,t,i),o=Object.fromEntries(IMPLIED_SETTINGS.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...disclosureNode(a,r.ref,r.body,`drop`,shownWhile([r.ref],`{{ ${namesView(n.presetIdent)} }}`)),...Object.keys(o).length>0&&{settings:o},drafts:Object.fromEntries(IMPLIED_SETTINGS.map(e=>[e,r.drafts[e]]))}}function labelSegment(e,t,n,r,i){let a=`${LABEL_NS}${t}:${n.name}`;return e.artifacts.segments[a]={template:`{{ "${escapeTemplateLiteral(i)}" }}`,...r.palette!==void 0&&{palette:r.palette}},a}function editableUnit(e,t,n,r){let i=placementId(e),a=n?[insertTerm(r,String(r.posCounter.n++),i,`before`)]:[],o=String(r.posCounter.n++),s=insertTerm(r,o,i,`after`),c=removeTerm(r,o,i),l=r.segments[e.name],u=configureParts(r,o,e,settingsOf(l)),d=inArrangeMode(c),f=inArrangeMode(u.term);return[...a.map(e=>chromeCell(e.host,e.template,r.artifacts)),{...labelChrome(e,l,r,u),lead:d,trail:f},{...t,when:inNamesView(r.presetIdent,`false`,e.when??`true`),lead:d,trail:f,drafts:u.drafts},chromeCell(s.host,s.template,r.artifacts)]}function fileLabel(e){return path.join(path.basename(path.dirname(e)),path.basename(e))}function insertedUnit(e,t,n,r){let i=r.segments[e.name],a=placementId(e);return[{kind:`segment`,name:labelSegment(r,`${a}/${r.presetIdent}`,e,i,`${a} · ${fileLabel(t.file)} ${t.entry}`),when:`{{ ${namesView(r.presetIdent)} }}`},{...n,when:inNamesView(r.presetIdent,`false`,e.when??`true`)}]}function insertTerm(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${EDIT_NS}${i}.insert.${t}`,s=`${EDIT_NS}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:ADDABLE_DOMAIN,anchor:n,relation:r};let c=menuMember(o),l=menuStateKey(s,o,void 0),u=menuPageKey(l),d=menuActionName(l,c);return a.variables[l]={...disclosureStateVar(l,DISCLOSURE_CLOSED),within:[EDIT_MODE_REF]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=disclosureCycleAction(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${disclosureTerm({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${TEXT_MIN_CONTRAST}`}) $m }}{{ end }}`}}function spliceContainer(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!isChromeExempt(e.name)&&e.insertedBy===void 0),i=e=>spliceContainer(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=mapOpens(o,i);if(isChromeExempt(o.name)){n.push(s);continue}let c={kind:`container`,direction:`horizontal`,children:o.insertedBy===void 0?editableUnit(o,s,a===r,t):insertedUnit(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:shownWhile(configureRefsIn(n),inNamesView(t.presetIdent,`true`,e.when))}}}function wrapWithPresetRows(e,t,n,r,i,a,o){let s=`${EDIT_NS}${t}.resetLayout`,c=`${EDIT_NS}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:CUSTOMIZED_BANNER_GATE},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},withTrailingCell(e,o)]}}function withTrailingCell(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),withTrailingCell(n,t)]}:{...e,children:[...e.children,t]}}function spliceEditChromeForPreset(e,t,n,r,i,a){let{node:o}=presetRoot(e,t),s={presetIdent:ident(t),rootKey:presetRootKey(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=spliceContainer(o,s);return n.variables[configuringVar(s.presetIdent)]=configuringDecl(s.configured),wrapWithPresetRows(c,s.presetIdent,s.rootKey,n,r,i,a)}function synthesizeEditChrome(e){let t={variables:{},actions:{},segments:{}},n=declareHelp(`${EDIT_NS}help`,EDIT_MODE_HELP,[EDIT_MODE_REF],t);t.variables[EDIT_LIVE_KEY]=disclosureStateVar(EDIT_LIVE_KEY,DISCLOSURE_CLOSED),t.actions[EDIT_LIVE_KEY]=disclosureCycleAction(EDIT_LIVE_KEY,EDIT_LIVE_REF.member),t.segments[EDIT_LIVE_KEY]={template:disclosureTrigger(EDIT_LIVE_KEY,...EDIT_LIVE_DISPLAY),when:EDIT_MODE_GATE};let r={kind:`segment`,name:EDIT_LIVE_KEY},i=n;t.variables[EDIT_CHANGES_VAR]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[EDIT_SAVE_ACTION]={save:!0,layer:`user`},t.actions[EDIT_DONE_SEG]={do:[EDIT_SAVE_ACTION,EDIT_TOGGLE_ACTION]},t.segments[EDIT_DONE_SEG]={template:`{{ if ${TO_KEEP} }}{{ action "${EDIT_DONE_SEG}" "✓ save" }}{{ else }}{{ action "${EDIT_DONE_SEG}" "✓ done" }}{{ end }}`,when:EDIT_MODE_GATE},t.actions[EDIT_REWIND_ACTION]={rewind:!0},t.actions[EDIT_CANCEL_SEG]={do:[EDIT_REWIND_ACTION,EDIT_TOGGLE_ACTION]},t.segments[EDIT_CANCEL_SEG]={template:`{{ action "${EDIT_CANCEL_SEG}" "↩ cancel" }}`,when:`{{ and ${disclosureTerm(EDIT_MODE_REF)} ${CHANGED} }}`};let a=[{kind:`segment`,name:EDIT_DONE_SEG},{kind:`segment`,name:EDIT_CANCEL_SEG}],o={...e.presets};for(let n of presetNames(e.presets)){let s=spliceEditChromeForPreset(e,n,t,a,r,i);o[n]={...presetByName(e.presets,n),root:s}}return{...e,variables:{...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function encodeLayoutOp(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function decodeLayoutOp(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 mintPlacement(e,t,n){let r=freePlacementId(e,new Set(n.map(placementIds).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const INT_RE=/^-?\d+$/;function makeAllowListValidator(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 makeIntValidator(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!INT_RE.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 makeRangeValidator(e,t,n){return r=>r?INT_RE.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 mergeKeySpecs(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=>!INT_RE.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 wireForNoun(e){return e===`config`?`set-config`:`set-state`}function validatorForSpec(e,t,n){return t.kind===`int`?makeIntValidator(`menu page "${e}"`):t.kind===`range`?makeRangeValidator(t.min,t.max,`${n} stepper "${e}"`):makeAllowListValidator(t.allowed,`${n} "${e}"`,wireForNoun(n))}function mergeContributions(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:mergeKeySpecs(e,n,t)}))}function createGate(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 mergeContributions(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,validatorForSpec(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 createKeyspace(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};createGate(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=createGate(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}function makeConfigKeyspace(){return createKeyspace({},`config`,deriveConfigActionValidators)}function actionKeySpecs$1(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:resolveOptionDomain(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:[encodeLayoutOp({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[encodeLayoutOp({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:resolveOptionDomain(e.insertSegmentFrom,t).members.map(t=>encodeLayoutOp({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function clearableContributions(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?parsePersistTarget(n.persist):null;e?.scope===`preset-root`&&t.add(presetRootKey(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function actionContributions$1(e){let t=configOptionDomains(e);return[...clearableContributions(e),...Object.values(e.actions).flatMap(e=>actionKeySpecs$1(e,t))]}function deriveConfigActionValidators(e){return mergeContributions(actionContributions$1(e),`config`)}const RESOLVABLE_THEMES_LIST=listResolvablePaletteNames(),RESOLVABLE_THEMES=new Set(RESOLVABLE_THEMES_LIST),RESOLVABLE_ENDCAPS=new Set(ENDCAPS_SHAPES),validateTheme=e=>e?RESOLVABLE_THEMES.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${RESOLVABLE_THEMES_LIST.join(`, `)})`}:{ok:!1,reason:`theme name is required`},validateEndcaps=e=>e?RESOLVABLE_ENDCAPS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${ENDCAPS_SHAPES.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},BASELINE={endcaps:validateEndcaps,theme:validateTheme};function makeStateKeyspace(){return createKeyspace(BASELINE,`state`,deriveActionValidators)}function actionKeySpecs(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:resolveOptionDomain(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 dropBaselineAllowLists(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(BASELINE,e.key))}function actionContributions(e){let t=configOptionDomains(e);return dropBaselineAllowLists(Object.values(e.actions).flatMap(e=>actionKeySpecs(e,t)))}function deriveActionValidators(e){return mergeContributions(actionContributions(e))}function createGates(e){let t=makeStateKeyspace(),n=makeConfigKeyspace();for(let{key:n,allowed:r}of e.state)t.register(n,r);for(let{key:t,allowed:r}of e.config)n.register(t,r);return{state:t,config:n}}const UPDATE_DISMISSED_KEY=`update.dismissed`,UPDATE_NOTICE_FIELD=`updateNotice`,UPDATE_NOTICE_SESSION_KEY=SETTINGS.updateNotice.sessionKey;function daemonGates(){return createGates({config:[{key:UPDATE_NOTICE_FIELD,allowed:[`false`]}],state:[{key:UPDATE_NOTICE_SESSION_KEY,allowed:[`false`]},{key:UPDATE_DISMISSED_KEY,allowed:[]}]})}function updateIdentity(e){return e.kind===`source`?e.newer.digest:formatVersion(e.newer)}const describeStamp=e=>`${e.version} [${shortDigest(e.digest)}]`;function wordsOf(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:describeStamp(e.newer),running:describeStamp(e.running),act:`rebuild`,busy:`rebuilding…`};case`release`:return{headline:`Newer release`,newer:formatVersion(e.newer),running:formatVersion(e.running),act:`upgrade`,busy:`upgrading…`}}}const NO_NOTICE={offer:[],failure:[]};function updateNotice(e,t,n){if(e===null)return NO_NOTICE;let r=updateIdentity(e);if(!n.enabled||n.dismissed===r)return NO_NOTICE;let i=wordsOf(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[(e=>({about:`update-failed\0${r}`,text:e,copy:e}))(`${i.act} failed: ${t.reason}`)]:[],s=t.kind===`running`?diagnosticSpan(`[${i.busy}]`,null):diagnosticSpan(`[${i.act}]`,effectsUrl([{verb:VERB_APPLY_UPDATE,args:[n.sessionId]}])),c=[diagnosticSpan(a,null),s,diagnosticSpan(`[dismiss]`,effectsUrl([{verb:VERB_SET_STATE,args:[n.sessionId,UPDATE_DISMISSED_KEY,r]}])),diagnosticSpan(`[disable]`,effectsUrl([{verb:VERB_SET_CONFIG,args:[n.sessionId,`user`,UPDATE_NOTICE_FIELD,`false`]},{verb:VERB_SET_STATE,args:[n.sessionId,UPDATE_NOTICE_SESSION_KEY,`false`]}]))];return{offer:[{severity:UPDATE_SEVERITY,about:`update\0${r}`,message:a,copy:a,lines:[c]}],failure:o}}function commandOf(e){switch(e.kind){case`source`:return{bin:`pnpm`,args:[`build`],cwd:e.root};case`release`:return{bin:`pnpm`,args:[`dlx`,`${PACKAGE_NAME}@${formatVersion(e.newer)}`,`install`]}}}function updateReading(e,t){if(e.kind===`pending`)return e;let n=e.value;switch(n.kind){case`stale`:return ok$1({kind:`source`,root:n.root,newer:n.source,running:n.running});case`current`:return ABSENT$2;case`unchecked`:return failed$2(`build: unchecked: ${n.reason}`,`read`);case`not-source-checkout`:return releaseReading(t)}}function releaseReading(e){if(e.kind===`pending`)return e;let t=e.value;switch(t.kind){case`stale`:return ok$1({kind:`release`,newer:t.latest,running:t.installed});case`current`:case`ahead`:return ABSENT$2;case`unchecked`:return failed$2(`release: unchecked: ${t.reason}`,`read`)}}const ACT_TIMEOUT_MS=600*1e3,ACT_POLL_MS=2e3;function describeBuild(e){switch(e.kind){case`current`:return[`info`,`build: current ${describeStamp(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${describeStamp(e.source)}, running ${describeStamp(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function describeRelease(e){switch(e.kind){case`current`:return[`info`,`release: current ${formatVersion(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${formatVersion(e.latest)}, running ${formatVersion(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${formatVersion(e.installed)}, latest ${formatVersion(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function makeUpdateWatch(e){let{fact:t,clock:n,launcher:r,probe:i,entryUrl:a,digest:o,actsDir:s,intervalMs:c,releaseIntervalMs:l,registryUrl:u,fetchImpl:d,onApplied:f,log:p}=e,m=pendingOf(`unread`),h=pendingOf(`unread`),g=async e=>{let t=await i.startTime(e);if(E)throw new DaemonClosing(`apply-update`);return t},_=makeActReader(s,g,r,n),v=null,y=null,b=import_dist$1.observable.box({act:IDLE,actsError:null},{deep:!1,equals:import_dist$1.compareStructural}),x=()=>(0,import_dist$1.runInAction)(()=>b.set({act:v??IDLE,actsError:y})),S=changeLogger(p),C=changeLogger(p),w=new KeyedSerialQueue,T=e=>w.run(`acts`,e),E=!1,D=[],O=(e,t)=>{D.push(n.every(t,e,{unref:!0}))},k=()=>{let e=t.get();return e.kind===`ok`?e.value:null};function A(){let e=E?ABSENT$2:updateReading(m,h),r=restamp(t.get(),e,instantAt(n));(0,import_dist$1.runInAction)(()=>t.set(r))}function j(){let e=assessBuild(a,()=>bundleStamp(o));return m=ok$1(e),S(describeBuild(e)),A(),e}async function M(){let e=assessCurrency(PACKAGE_VERSION,await fetchLatestVersion(PACKAGE_NAME,d,u,n));h=ok$1(e),C(describeRelease(e)),A()}let N=changeLogger(p);async function F(e){try{let t=await e();return y=null,x(),{ok:!0,value:t}}catch(e){return e instanceof DaemonClosing?{ok:!1,error:e.message}:(y=`update act files (${s}): ${e.message}`,x(),N([`error`,y]),{ok:!1,error:y})}}function ee(e){if(!e?.alive||n.now()<=e.record.deadline)return;let{stands:t,signalled:i}=endOverdue(s,e,r),a=t?`timed out`:`outlived its verdict`,o=i?`ending it`:`its group took no signal`;p(`error`,`apply-update: act ${e.act} ${a}; ${o}`)}async function te(){let e=await F(async()=>{let e=await _.read();return E||ee(e),e});if(E||!e.ok)return;let t=judgeAct(e.value),n=v;v=t,n===null&&t.kind===`running`&&p(`info`,`apply-update: act ${t.act} is running; watching it`);let r=n?.kind===`running`&&t.kind!==`running`,i=r&&t.kind===`succeeded`;i&&p(`info`,`apply-update: act ${t.act} succeeded`),r&&t.kind===`failed`&&p(`error`,`apply-update: act ${t.act} failed: ${t.reason}`),(0,import_dist$1.runInAction)(()=>{i&&j(),x()}),i&&f()}let ne;async function I(){await T(te),!E&&(ne=n.after(ACT_POLL_MS,()=>void I(),{unref:!0}))}return{arm(){let e=j();O(j,c),D.push(()=>ne?.()),I(),e.kind===`not-source-checkout`&&(M(),O(()=>void M(),l))},close(){E=!0,A(),D.forEach(e=>e())},acts:()=>b.get(),running:()=>T(async()=>{let e=await F(()=>_.read());return e.ok&&judgeAct(e.value).kind===`running`}),act:()=>T(async()=>{if(E)throw new DaemonClosing(`apply-update`);let e=await F(()=>_.read());if(E)throw new DaemonClosing(`apply-update`);if(!e.ok)throw new BadVerbArgs(`apply-update: ${e.error}`);let t=k();if(t===null)throw new BadVerbArgs(`apply-update: nothing newer is known to apply`);let i=wordsOf(t),a=commandOf(t),o=e.value;if(judgeAct(o).kind===`running`)throw new BadVerbArgs(`apply-update: already ${i.busy}`);let c=await claimAct(r,s,o===null?null:o.act,updateIdentity(t),{...a,category:`update.apply`},ACT_TIMEOUT_MS,n.now(),g);if(!c.ok)throw new BadVerbArgs(`apply-update: ${c.reason}`);p(`info`,`apply-update: act ${c.act}: ${i.act} — ${a.bin} ${a.args?.join(` `)??``}`),v={kind:`running`,act:c.act},x()})}}function newUpdateFact(){return import_dist$1.observable.box(pendingOf(`unread`),{deep:!1})}function mtimeOf(e,t){try{return ok$1(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?ABSENT$2:failed$2(e.message,`read`)}}function sameStamp(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function makeBinaryWatch(e){let{targets:t,intervalMs:n,stat:r,held:i,exit:a,log:o,clock:s}=e,c=changeLogger(o),l=t.map(e=>({path:e,stamp:mtimeOf(e,r)})),u=l.filter(({stamp:e})=>e.kind!==`failed`),d=null,f=!1,p=()=>{f=!0,d?.()},m=async()=>{if(!f)for(let{path:e,stamp:t}of u){let n=mtimeOf(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!sameStamp(t,n)){let t=`binary ${n.kind===`absent`?`gone`:`changed`} (${e})`,r=await i();if(f)return;if(r){c([`info`,`${t}; the restart waits for the running update`]);return}o(`info`,`${t}; shutting down`),p(),a();return}}},h=()=>m().catch(e=>{o(`error`,`binary check failed: ${e.message}`)});return{arm(){for(let{path:e,stamp:t}of l)t.kind===`failed`&&o(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);d=s.every(n,()=>void h(),{unref:!0})},checkNow:h,close:p}}var TrailingEdge=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 GIT_PERIOD_MS=3e4,RESOLUTION_TTL_MS=3e4,DEFAULT_MAX_REPOS=64,PASS=`pass`,PR_PERIOD={okMs:5*6e4,failedMs:45e3},PR_BACKOFF_CEILING_MS=PR_PERIOD.okMs,DEFAULT_PR_LOOKUPS=2,PR_KEYS_KEPT=16;function prPeriodOf({failures:e}){return backedOffMs(PR_PERIOD,e,PR_BACKOFF_CEILING_MS)}function triggerOf(e){return e.includes(`first`)?`first`:e.length===0?`period`:`change`}function holdKey(e){return`git:${e}`}function watchSpec(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:path.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>boundOf$1(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${boundKey(i[t])}`).join(`|`)}`,targets:{dirs:r},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function branchOf(e){return e.kind===`ok`?e.value.branch:void 0}function owe(e){e.missed=!0,renew(e,`unread`)}function unkeyedPr(e,t){return e.missed&&e.reading.get().kind===`pending`&&settle$1(e,t.size>0?failed$2([...t].join(`; `),`read`):ABSENT$2),`unkeyed`}function composed({value:e,pr:t}){let n=currentOf(e);return n.kind===`ok`?ok$1({...n.value,pullRequest:currentOf(t)}):n}const CLOSED=failed$2(`git cache closed`,`read`);function threw(e){return t=>failed$2(`${e} threw: ${String(t)}`,`read`)}var GitDataProvider=class{repos=new Map;resolutions=new Map;closed=!1;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;forgeLookups;watchers;ownsWatchers;logger;clock;constructor(e){this.inner=e.inner,this.clock=e.clock,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??DEFAULT_MAX_REPOS,this.forgeLookups=new Limiter(e.maxPrLookups??DEFAULT_PR_LOOKUPS),this.logger=e.logger??quietLogger;let t=e.ledger??new RefreshLedger(this.logger);this.gitRefreshes=t.declare({name:`git`,scope:`repo`,refresh:[`first`,`period`,`change`],lines:[`first`,`period`,`change`]}),this.prRefreshes=t.declare({name:`pr`,scope:`repo`,refresh:[`first`,`period`],lines:[`first`,`period`]}),e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new WatcherRegistry({clock:this.clock,logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=this.clock.monotonic(),i=this.resolutions.get(n);if(i&&r-i.computedAt<RESOLUTION_TTL_MS)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=failed$2(`resolver threw: ${String(e)}`,`read`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n){let r=this.asked(e,t,n);if(r.kind===`settled`)return settledLane(r.outcome);let{state:i}=r;return i.value.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>composed(i)}}asked(e,t,n){if(this.closed)return{kind:`settled`,outcome:CLOSED};let r=this.resolution(t,n);return r.kind===`ok`?{kind:`asked`,state:this.ask(r.value,e)}:{kind:`settled`,outcome:r}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){t.value.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))}built(e){let t={period:new Period(()=>{this.readPr(n,t,`period`)},this.clock),seen:new Map,missed:!0,key:``,remote:ABSENT$2,reading:unread(),inFlight:null},n={root:e,refresh:new TrailingEdge,watch:this.followWatch(e,null).watch,period:new Period(()=>{n.refresh.share(PASS,()=>this.refreshPass(n))},this.clock),value:{reading:unread(),missed:!1},pr:t,holders:0,asked:new Set};return this.repos.set(e,n),n}followWatch(e,t){let n=this.inner.resolveGitDir(e),r=watchSpec(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(PASS,()=>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){return e.holders++,e.value.missed&&(owe(e.pr),e.asked.add(`resume`)),e.pr.missed&&e.pr.key!==``&&e.asked.add(`owed`),this.held(e),this.evict(),()=>{e.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(PASS,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr.period.hold(e.holders>0&&!e.pr.missed)}ask(e,t){let n=this.repos.get(e);n!==void 0&&this.touch(n);let r=n??this.built(e),i=r.asked.size;return n===void 0&&r.asked.add(`first`),t.take(holdKey(e),()=>this.hold(r)),this.queue(r,i),r}async pass(e){if(this.repos.get(e.root)!==e)return;let t=this.clock.monotonic(),n=[...e.asked];e.asked.clear();let r=this.followWatch(e.root,e.watch);e.watch=r.watch;let[i,a]=await Promise.all([this.inner.getGitInfo(e.root).catch(threw(`git fetch`)),this.remoteOf(e)]);if(this.repos.get(e.root)!==e)return;let o=new Set;if(e.value.missed=!1,settle$1(e.value,i),i.kind===`failed`&&o.add(i.reason),i.kind===`ok`)for(let e of gitInfoFailures(i.value))o.add(e);let s=branchOf(i),c=s===void 0?unkeyedPr(e.pr,o):this.movePr(e,s,a);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} pr=${c} watch=${r.move}`,triggerOf(n),o.size===0?ok$1(null):failed$2([...o].join(`; `),`read`),elapsedMs(this.clock,t))}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(threw(`git remote`))}movePr(e,t,n){let{pr:r}=e,i=`${t}|${n.kind===`ok`?n.value:n.kind}`;if(i===r.key&&!r.missed)return`kept`;r.key=i,r.remote=n;let a=r.seen.get(i);return a===void 0?e.holders===0?(owe(r),`owed`):(renew(r,`unread`),r.missed=!1,this.readPr(e,r,`first`),`looked-up`):(r.seen.delete(i),r.seen.set(i,a),r.missed=!1,settle$1(r,a.outcome),r.period.landed(prPeriodOf(a),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=this.clock.monotonic(),o=(i.kind===`ok`?this.forgeLookups.run(()=>(a=this.clock.monotonic(),this.inner.resolvePullRequest(e.root,i.value))).catch(threw(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:ABSENT$2)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${valueOf$1(r)}`,n,i,elapsedMs(this.clock,a));let o=this.clock.monotonic(),s={outcome:i,at:o,failures:i.kind===`failed`?(t.seen.get(r)?.failures??0)+1:0};t.seen.delete(r),t.seen.set(r,s);for(let e of t.seen.keys()){if(t.seen.size<=PR_KEYS_KEPT)break;t.seen.delete(e)}t.key!==r||t.missed||(settle$1(t,i),t.period.landed(prPeriodOf(s),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=failed$2(`git state dropped: ${e.root}`,`read`);answerPending(e.value,t),answerPending(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watch.handle.release(),e.period.dispose(),e.pr.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){this.closed=!0;for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},CacheManager=class{static usageDir(e){return path.join(e,`usage`)}static locksDir(e){return path.join(e,`locks`)}static isLocked(e,t){let n=path.join(this.locksDir(e),t);if(!fs.existsSync(n))return!1;try{let e=fs.readFileSync(n,`utf-8`),r=parseInt(e.trim(),10);if(isNaN(r))return debug(`Invalid PID in lock file ${t}, removing stale lock`),fs.unlinkSync(n),!1;try{return process.kill(r,0),!0}catch(e){return e.code===`ESRCH`?(debug(`Removing stale lock file ${t} for dead process ${r}`),fs.unlinkSync(n),!1):(debug(`Error checking process ${r} for lock ${t}:`,e),!0)}}catch(e){return debug(`Error reading lock file ${t}:`,e),!0}}static async acquireLock(e,t,n,r=5e3){let i=50,a=`wx`;await this.ensureCacheDirectories(e);let o=path.join(this.locksDir(e),n),s=t.monotonic(),c=String(process.pid);for(;t.monotonic()-s<r;)try{return await fs.promises.writeFile(o,c,{flag:`wx`}),debug(`Lock acquired for ${n}`),!0}catch(e){if(e.code===`EEXIST`)await sleep(t,50);else throw e}return debug(`Failed to acquire lock for ${n} within ${r}ms`),!1}static async releaseLock(e,t){let n=path.join(this.locksDir(e),t);try{await fs.promises.unlink(n),debug(`Lock released for ${t}`)}catch(e){e.code!==`ENOENT`&&debug(`Error releasing lock for ${t}:`,e)}}static async ensureCacheDirectories(e){try{await Promise.all([fs.promises.mkdir(e,{recursive:!0}),fs.promises.mkdir(this.usageDir(e),{recursive:!0}),fs.promises.mkdir(this.locksDir(e),{recursive:!0})])}catch(e){debug(`Failed to create cache directories:`,e)}}static createProjectHash(e){return createHash(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t,n,r){let i=3,a=75,o=`utf-8`;await this.ensureCacheDirectories(e);let s=path.join(this.usageDir(e),`${n}.json`),c=`${n}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(e,c)){debug(`Cache for ${n} is locked, waiting...`),await sleep(t,75);continue}try{let e=await fs.promises.readFile(s,`utf-8`),t=JSON.parse(e);return!r||t.timestamp>=r?(debug(`[CACHE-HIT] ${n} disk cache: found`),this.deserializeDates(t.data)):(debug(`${n} cache outdated: cache=${t.timestamp}, latest=${r}`),null)}catch(e){if(e.code===`ENOENT`)return debug(`No shared ${n} usage cache found`),null;debug(`Attempt ${i+1} failed to read ${n} cache: ${e.message}. Retrying...`),await sleep(t,75)}}return debug(`Failed to read ${n} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n,r,i){let a=`${n}.usage.lock`;if(!await this.acquireLock(e,t,a)){debug(`Could not acquire lock to set usage cache for ${n}`);return}try{await this.ensureCacheDirectories(e);let a=path.join(this.usageDir(e),`${n}.json`),o={data:r,timestamp:i||t.now()},s=JSON.stringify(o);await fs.promises.writeFile(a,s,`utf-8`),debug(`[CACHE-SET] ${n} disk cache stored`)}catch(e){debug(`Failed to save ${n} usage cache:`,e)}finally{await this.releaseLock(e,a)}}};const OFFLINE_PRICING_DATA={"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 PricingService=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(e,t){let n=t.now()-1440*60*1e3;return await CacheManager.getUsageCache(e,t,`pricing`,n)}static async saveDiskCache(e,t,n){await CacheManager.setUsageCache(e,t,`pricing`,n)}static async fetchPricingData(){return new Promise(e=>{let t=new URL$1(this.GITHUB_PRICING_URL),n=get({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){debug(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let r=``,i=0,a=1024*1024;t.setEncoding(`utf8`),t.on(`data`,t=>{if(i+=Buffer.byteLength(t),i>1048576){debug(`Response too large`),n.destroy(),e(null);return}r+=t}),t.on(`end`,()=>{try{let t=JSON.parse(r),n=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(debug(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),debug(`Pricing last updated: ${n?.updated||`unknown`}`),e(i)):(debug(`Invalid pricing data structure`),e(null))}catch(t){debug(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{debug(`Response error:`,t),e(null)})});n.on(`error`,t=>{debug(`Request error:`,t),e(null)}),n.on(`timeout`,()=>{debug(`Request timeout`),n.destroy(),e(null)}),n.end()})}static async getCurrentPricing(e,t){if(this.executionCache!==null)return debug(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let n=await this.loadDiskCache(e,t);if(n)return debug(`[CACHE-HIT] Pricing disk cache: ${Object.keys(n).length} models`),this.executionCache=n,debug(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(n).length} models`),n;let r=await this.fetchPricingData();return r?(await this.saveDiskCache(e,t,r),debug(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(r).length} models`),this.executionCache=r,debug(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(r).length} models`),r):(debug(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(OFFLINE_PRICING_DATA).length} models`),this.executionCache=OFFLINE_PRICING_DATA,debug(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(OFFLINE_PRICING_DATA).length} models`),OFFLINE_PRICING_DATA)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e,t,n){if(this.modelPricingCache.has(e))return debug(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let r=await this.getCurrentPricing(t,n),i;return i=r[e]?r[e]:this.fuzzyMatchModel(e,r),this.modelPricingCache.set(e,i),debug(`[CACHE-SET] Model pricing cache: ${e}`),i}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e,t,n){let r=e.message?.usage;if(!r)return 0;let i=this.extractModelId(e),a=await this.getModelPricing(i,t,n),o=r.input_tokens||0,s=r.output_tokens||0,c=r.cache_creation_input_tokens||0,l=r.cache_read_input_tokens||0,u=o/1e6*a.input,d=s/1e6*a.output,f=l/1e6*a.cache_read,p=c/1e6*a.cache_write_5m;return u+d+p+f}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const COMMAND_NAME=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function slashCommand(e){if(typeof e==`string`)return COMMAND_NAME.exec(e)?.[1]}function todoItems(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function turnText(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function entryActivity(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=todoItems(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?slashCommand(turnText(n)):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&o===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...o!==void 0&&{command:o}}}function getClaudePaths(e,t){return e===void 0?[join(t,`.config`,`claude`),join(t,`.claude`)].filter(e=>existsSync(e)):[e]}async function findProjectPaths(e){let t=[];for(let n of e){let e=join(n,`projects`),r=await unlessGone(readdir$1(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(join(e,n.name))}return t}async function unlessGone(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function findAgentTranscripts(e,t,n){let r=[],i=[],a=join(t,e,`subagents`);try{let t=(await readdir$1(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=join(a,o);if(n?.has(t)){r.push(t);continue}let s=await readAppended(t,void 0,void 0);if(s.kind!==`ok`){debug(`Failed to check agent file ${t}`);continue}i=longLinesWith(i,t,s.value);let c=jsonLine(decodeLines(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){debug(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function userEntryOf(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(firstBlockType(t)===`tool_result`)return`tool-result`;let n=typeof e.origin==`object`&&e.origin!==null?e.origin.kind:void 0;if(n!==void 0&&n!==`human`)return`turn`;let r=turnText(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||CLAUDE_CODE_TEXT.test(r)?`claude-code`:`prompt`}const TURN_GOES_ON=new Set([void 0,`tool_use`,`pause_turn`]);function turnOpenAfter(e,t){if(t.isSidechain)return e;switch(t.userEntry){case`prompt`:case`turn`:return!0;case`interrupt`:return!1;case`tool-result`:case`claude-code`:return e;case void 0:return t.type===`assistant`?TURN_GOES_ON.has(t.message?.stopReason):e}}const CLAUDE_CODE_TEXT=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function firstBlockType(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function makeEntry(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=userEntryOf(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0,stopReason:typeof t.stop_reason==`string`?t.stop_reason:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:entryActivity(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function jsonLine(e){let t=e.trim();if(!t)return{kind:`blank`};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{kind:`object`,value:e}:{kind:`unparsed`,reason:`not a JSON object`}}catch(e){return{kind:`unparsed`,reason:String(e)}}}function entryOf(e){let t=jsonLine(e);if(t.kind===`unparsed`)return debug(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return makeEntry(t.value)}catch(e){return debug(`Failed to project JSONL line: ${e}`),null}}function parseJsonlLines(e){let t=[];for(let n of e.split(`
|
|
186
186
|
`)){let e=entryOf(n);e&&t.push(e)}return t}function longLinesWith(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function longLineLog(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function foldAppended(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await readAppended(e,a===void 0?void 0:{offset:a.offset,ino:a.ino},s?.size);if(t.kind!==`ok`)return t;let c=t.value;c.reset&&(o=n),i=longLinesWith(c.reset?[]:i,e,c),(s===void 0||c.reset)&&(s={size:c.size,stamp:c.stamp});let l=c.start+c.lines.length;if(o=await r(o,decodeLines(c,e=>parseJsonlLines(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return ok$1({folded:{cursor:a,value:o},longLines:i})}}var SingleFlight=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}};const unwritten=e=>isPending(e);var BoxNode=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n,r){this.name=e,this.type=t,this.clock=r,unwritten(n)||assertType(e,t,n,`initial value`),this.cell=import_dist$1.observable.box(n,{deep:!1}),this.lastChangedAt=unwritten(n)?null:r.now()}read(){let e=this.cell.get();if(unwritten(e))throw new PendingValueError(this.name,`variable "${this.name}" has no value yet: nothing has written it`);return e}set(e){unwritten(e)||assertType(this.name,this.type,e,`set value`),!(0,import_dist$1.compareStructural)(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}stored(){return this.cell.get()}},Kept=class{cell;constructor(e,t,n){if(this.cell=(0,import_dist$1.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_()}},Projected=class{constructor(e){this.deriver=e}read(){return this.deriver()}},ComputedNode=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new Kept(`Variable "${e}"`,()=>{let e=n();return assertType(this.name,this.type,e,`computed result`),e})}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}},ProjectionNode=class{kind=`projection`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new Projected(()=>{let e=n();return assertType(this.name,this.type,e,`projection result`),e})}read(){return this.cell.read()}lastUpdatedMs(){return null}},DocumentCell=class{kind=`document`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.clock=n,this.cell=import_dist$1.observable.box(shaped(t),{deep:!1}),this.lastChangedAt=t.kind===`pending`?null:n.now()}read(){return this.cell.get()}set(e){let t=shaped(e);sameDocument(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=this.clock.now())}lastUpdatedMs(){return this.lastChangedAt}},DerivedDocument=class{kind=`document`;cell;constructor(e,t){this.name=e,this.cell=new Kept(`Variable "${e}"`,()=>shaped(t()),sameDocument)}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}};function documentKey(e){return JSON.stringify(e)}function sameDocument(e,t){return documentKey(e)===documentKey(t)}function shaped(e){return e.kind===`ok`?{kind:`ok`,value:toDocument(e.value)}:e}function assertType(e,t,n,r){let i=typeOf(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var VariableStore=class{constructor(e,t=null){this.clock=e,this.parent=t}nodes=import_dist$1.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new BoxNode(e,t,n,this.clock))}defineDocument(e,t){this.declare(e,new DocumentCell(e,t,this.clock))}defineDerivedDocument(e,t){this.declare(e,new DerivedDocument(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`?ComputedNode:ProjectionNode;this.declare(e,new a(e,t,()=>r(i)))}derive(e,t,n){if(this.refuseDisposed(`Derived value "${e}"`),t===`projection`)return new Projected(n);let r=new Kept(`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 DocumentCell))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,import_dist$1.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,import_dist$1.runInAction)(()=>n.set(t))}runInAction(e){(0,import_dist$1.runInAction)(e)}has(e){return this.nodes.has(e)||(this.parent?.has(e)??!1)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`){let e=t.read();return e.kind===`pending`?e:ok$1(documentKey(e))}try{return ok$1(String(t.read()))}catch(e){return readPending(e)===void 0?ok$1(` failed:${e instanceof Error?e.message:String(e)}`):pendingOf(`unread`)}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.parent?.names()??[],...this.nodes.keys()]}dispose(){if(this.disposed)return 0;this.disposed=!0;let e=0;return(0,import_dist$1.runInAction)(()=>{for(let t of this.nodes.values())(t instanceof ComputedNode||t instanceof DerivedDocument)&&(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,import_dist$1.runInAction)(()=>this.nodes.set(e,t))}};const EMPTY_DAY={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0};function addDay(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function dayKey(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function oneDay(e,t,n){return{[dayKey(dateOf(e))]:{...EMPTY_DAY,cost:t,input:n}}}function projectToday(e,t){let n=dayKey(dateOf(t)),r=e.sums[n],i=e.own[n];if(r===void 0&&i===void 0)return ABSENT$2;let a={...EMPTY_DAY};return r!==void 0&&addDay(a,r),i!==void 0&&addDay(a,i),ok$1({cost:a.cost,tokens:a.input+a.output+a.cacheCreation+a.cacheRead,tokenBreakdown:{input:a.input,output:a.output,cacheCreation:a.cacheCreation,cacheRead:a.cacheRead},date:n})}const SPEED_RING_CAPACITY=64;function speedSampleOf(e,t,n){let r=e?e.input+e.cacheCreation+e.cacheRead:0,i=e?e.output:0;return{input:r,output:i,total:r+i,atMs:n,turnOpen:t}}const DEFAULT_STALE_AGE_MS=1440*60*1e3,DEFAULT_SWEEP_INTERVAL_MS=300*1e3,DEFAULT_RESCAN={okMs:60*1e3,failedMs:10*1e3},MAX_UNHELD_SCANS=8,SEED_CONCURRENCY=8,EMPTY_USAGE={calculatedCost:null,tokens:null,tokenBreakdown:null};function seedCutoffMs(e){let t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()-1),t.getTime()}function emptyBreakdown(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const EMPTY_FILE_FOLD={entries:0,cost:0,breakdown:emptyBreakdown(),days:new Map,turnOpen:!1,response:void 0};function responseOf(e){let t=e.message?.id;return t===void 0?void 0:`${t}:${e.raw.requestId??``}`}async function foldFile(e,t,n,r){let i=dayKey(new Date(seedCutoffMs(r.now()))),a=e.entries,o=e.cost,s=e.turnOpen,c=e.response,l={...e.breakdown},u=new Map;for(let[t,n]of e.days)t>=i&&u.set(t,{...n});for(let e of t){s=turnOpenAfter(s,e);let t=e.message?.usage;if(!t)continue;let d=responseOf(e);if(d!==void 0&&d===c)continue;c=d,a++;let f=e.costUSD??await PricingService.calculateCostForEntry(e.raw,n,r);o+=f,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;let p=dayKey(new Date(e.timestamp));if(p<i)continue;let m=u.get(p)??{...EMPTY_DAY};m.cost+=f,m.input+=t.input_tokens||0,m.output+=t.output_tokens||0,m.cacheCreation+=t.cache_creation_input_tokens||0,m.cacheRead+=t.cache_read_input_tokens||0,u.set(p,m)}return{entries:a,cost:o,breakdown:l,days:u,turnOpen:s,response:c}}function mergeFolds(e){let t=0,n=0,r=emptyBreakdown(),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)??{...EMPTY_DAY};addDay(n,t),i.set(e,n)}}if(t===0)return{usage:EMPTY_USAGE,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{usage:{calculatedCost:n,tokens:a,tokenBreakdown:r},days:i}}function under(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function daySumsOver(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!under(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...EMPTY_DAY};addDay(r,t),n.set(e,r)}return Object.fromEntries(n)}async function mapPool(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 answer(e,t){(0,import_dist$1.runInAction)(()=>e.set(t))}var SessionUsageStore=class{sessions=import_dist$1.observable.map(void 0,{deep:!1});flight=new SingleFlight;scans;daySets=new Map;speedFlight=new SingleFlight;refreshFlight=new SingleFlight;staleAgeMs;host;log;refreshTally={hits:0,misses:0};ledger;usage;sweeps=0;stopSweep=null;closed=!1;clock;constructor(e){this.host=e.host,this.clock=e.clock,this.log=e.logger??quietLogger,this.ledger=e.ledger??new RefreshLedger(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`first`,`period`,`change`],lines:[]}),this.staleAgeMs=e.staleAgeMs??DEFAULT_STALE_AGE_MS,this.scans=new KeyedSource({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${valueOf$1(e.join(`,`))}`,read:e=>this.scan(e),every:()=>e.rescan??DEFAULT_RESCAN,watch:NO_WATCH,maxEntries:MAX_UNHELD_SCANS,lines:REFRESH_TRIGGERS,logger:this.log,ledger:this.ledger,clock:this.clock});let t=e.sweepIntervalMs??DEFAULT_SWEEP_INTERVAL_MS;t>0&&(this.stopSweep=this.clock.every(t,()=>this.sweepStale(),{unref:!0}))}getStats(){return{size:this.sessions.size,hits:this.refreshTally.hits,misses:this.refreshTally.misses,sweeps:this.sweeps}}scanStats(){return this.scans.stats()}refresh(e,t,n){let r=null,i=()=>{if(r!==null)return r;let i=statStamp(t);return r={stamp:i,record:this.refreshed(e,t,i,n)},r};return{usage:async()=>{let e=await i().record;return e.kind===`failed`?e:ok$1(e.kind===`ok`?e.value.usage:EMPTY_USAGE)},speed:t=>this.observed(e,i,t)}}usageOf(e){let t=this.sessions.get(e);if(t===void 0)return pendingOf(`unread`);let n=t.failure.get();return n===null?ok$1(t.record?.usage??EMPTY_USAGE):failed$2(n,`read`)}refreshed(e,t,n,r){return this.refreshFlight.run(`${e}:${n}`,async()=>{let i={hits:0,misses:0},a=this.clock.monotonic(),o=await this.ingest(e,t,i,n);return this.refreshTally.hits+=i.hits,this.refreshTally.misses+=i.misses,i.misses>0&&this.usage.recorded(`sid=${valueOf$1(e)}`,r,o,elapsedMs(this.clock,a)),answer(this.hold(e).failure,o.kind===`failed`?o.reason:null),o})}declareToday(e,t){if(this.closed)return settledLane(failed$2(`usage store closed`,`read`));let n=getClaudePaths(t,this.host.home),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?ok$1({roots:i.roots,sums:i.sums.read()}):e}}}daysOutside(e,t){let n=this.sessions.get(e);if(n===void 0)return ABSENT$2;let r=n.failure.get();if(r!==null)return failed$2(r,`read`);let i=n.record;return i===void 0||under(i.transcriptPath,t)?ABSENT$2:ok$1(Object.fromEntries(i.days))}async observed(e,t,n){let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return answer(this.hold(e).speed,t),t;let a=this.hold(e),o=a.speed.get();if(a.sampledAt===r&&o?.kind===`ok`)return o;let s=t.kind===`ok`?speedSampleOf(t.value.usage.tokenBreakdown,t.value.turnOpen,n):speedSampleOf(null,!1,n),{ring:c}=a;c.push(s),c.sort((e,t)=>e.atMs-t.atMs),c.length>SPEED_RING_CAPACITY&&c.shift(),c.at(-1)===s&&(a.sampledAt=r);let l=ok$1({samples:[...c]});return answer(a.speed,l),l})}speedOf(e){return this.sessions.get(e)?.speed.get()??pendingOf(`unread`)}async ingest(e,t,n,r){let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,ok$1(i);if(!t)return i?ok$1(i):ABSENT$2;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 failed$2(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`,`read`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let{mainStamp:c,...l}=s.value,u={...l,transcriptStamp:c,transcriptPath:t},d=this.sessions.get(e)?.record;return d===o?(this.stored(e,u),ok$1(u)):d===void 0?ok$1(u):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,import_dist$1.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=this.clock.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:this.clock.now(),record:void 0,ring:[],sampledAt:null,failure:import_dist$1.observable.box(null),speed:import_dist$1.observable.box(void 0,{deep:!1})};return(0,import_dist$1.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=>join(e,`projects`)+sep),i={roots:r,sums:new Kept(`today over ${e.join(`,`)}`,()=>daySumsOver(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await findAgentTranscripts(e,dirname(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of longLineLog(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 foldAppended(e,r,EMPTY_FILE_FOLD,(e,t)=>foldFile(e,t,cacheDir(this.host),this.clock));if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{folded:s,longLines:c}=o.value;for(let e of longLineLog(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return ok$1({files:i,...mergeFolds(i),mainStamp:a,turnOpen:i.get(t)?.value.turnOpen??!1})}async scan(e){try{let t=seedCutoffMs(this.clock.now()),n=await findProjectPaths(e),r=[];for(let e of n){let n=await unlessGone(readdir$1(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=join(e,i),a=await unlessGone(stat$1(n));if(a===void 0||a.mtimeMs<t)continue;let o=parseSessionId(i.slice(0,-6));if(!o.ok){this.log(`warn`,`usageStore scan: transcript ${JSON.stringify(i)} names no session: session id ${o.problem}`);continue}r.push({sessionId:o.id,path:n,stamp:stampOf(a)})}}let i=[],a={hits:0,misses:0};return await mapPool(r,SEED_CONCURRENCY,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=${valueOf$1(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?failed$2(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`,`read`):ok$1({sessions:r.length,read:a.misses})}catch(e){return failed$2(`usage scan: ${e instanceof Error?e.message:String(e)}`,`read`)}}sweepStale(){let e=this.clock.now(),t=dayKey(new Date(e)),n=0,r=0,i=0;return(0,import_dist$1.runInAction)(()=>{for(let[a,{lastSeenAt:o,record:s}]of[...this.sessions])if(!(e-o<=this.staleAgeMs)){if(s?.days.has(t)){r++;continue}this.sessions.delete(a),n++,s===void 0&&i++}}),n>0&&this.sweeps++,(n>0||r>0)&&this.log(`info`,`usageStore sweep dropped=${n} noRecord=${i} held=${r}`),n}close(){this.closed=!0,this.stopSweep?.(),this.stopSweep=null,this.scans.close(),(0,import_dist$1.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}};function derived(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?ABSENT$2:ok$1(n)}function nonEmpty(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?ok$1(t):ABSENT$2}const COMMIT_TIME_CACHE_MAX=256,REMOTES_CACHE_MAX=256;function configIdentity(e){try{let t=fs.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var GitService=class{constructor(e){this.launcher=e}isGitRepo(e){return holdsGit(e)}async execGitAsync(e,t){return this.launcher.launch({bin:`git`,args:[...e],cwd:t.cwd,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}resolveEffectiveGitDir(e,t){return this.isWorktree(e)?ok$1(e):t&&this.isGitRepo(t)?ok$1(t):this.isGitRepo(e)?ok$1(e):this.findGitRoot(e)}findGitRoot(e){let t=gitRootOf(e);return t===void 0?ABSENT$2:ok$1(t)}async getGitInfo(e,t){try{return await this.computeGitInfo(e,t)}catch(e){return failed$2(`git: ${e instanceof Error?e.message:String(e)}`,`read`)}}async computeGitInfo(e,t){let n;if(this.isWorktree(e))n=e;else if(t&&this.isGitRepo(t))n=t;else if(this.isGitRepo(e))n=e;else{let t=this.findGitRoot(e);if(t.kind!==`ok`)return t;n=t.value}let r=await this.getCoreAsync(n);if(r.kind!==`ok`)return r;let i=await this.committedAt(n,r.value.oid),a=await this.getRemotesAsync(n);return ok$1({branch:r.value.branch,status:r.value.status,aheadBehind:r.value.aheadBehind,head:r.value.oid,workingTree:r.value.workingTree,sha:derived(r.value.oid,e=>e.slice(0,7)),upstream:r.value.upstream,committedAt:i,stashCount:this.getStashCount(n),repoName:derived(a,e=>this.repoNameFrom(e,n)),repoUrl:derived(a,repoWebUrl),operation:this.getOngoingOperation(n)})}resolveGitDir(e){return orElse(gitDirNamed(e),path.join(e,`.git`))}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return fs.existsSync(path.join(t,`MERGE_HEAD`))?ok$1(`MERGE`):fs.existsSync(path.join(t,`CHERRY_PICK_HEAD`))?ok$1(`CHERRY-PICK`):fs.existsSync(path.join(t,`REVERT_HEAD`))?ok$1(`REVERT`):fs.existsSync(path.join(t,`BISECT_LOG`))?ok$1(`BISECT`):fs.existsSync(path.join(t,`rebase-merge`))||fs.existsSync(path.join(t,`rebase-apply`))?ok$1(`REBASE`):ABSENT$2}catch(e){return failed$2(`git operation probe: ${e instanceof Error?e.message:String(e)}`,`read`)}}async committedAt(e,t){return t.kind===`ok`?this.commitTimestamp(e,t.value):t}commitTimes=new Map;async commitTimestamp(e,t){let n=this.commitTimes.get(t);if(n!==void 0)return this.commitTimes.delete(t),this.commitTimes.set(t,n),n;let r=this.readCommitTimestamp(e,t);for(this.commitTimes.set(t,r),r.then(e=>{e.kind!==`ok`&&this.commitTimes.get(t)===r&&this.commitTimes.delete(t)},()=>{this.commitTimes.get(t)===r&&this.commitTimes.delete(t)});this.commitTimes.size>COMMIT_TIME_CACHE_MAX;){let e=this.commitTimes.keys().next().value;if(e===void 0)break;this.commitTimes.delete(e)}return r}async readCommitTimestamp(e,t){let n=nonEmpty(classify(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10);return Number.isNaN(r)?failed$2(`git log -1: unparseable timestamp "${n.value}"`,`parse`):ok$1(r)}resolveCommonGitDir(e){return orElse(commonDirOf(e),e)}getStashCount(e){let t=path.join(this.resolveCommonGitDir(this.resolveGitDir(e)),`logs`,`refs`,`stash`),n;try{n=fs.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?ok$1(0):failed$2(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`,`read`)}let r=n.trim();return ok$1(r?r.split(`
|
|
187
187
|
`).length:0)}async getRemotesAsync(e){let t=configIdentity(path.join(this.resolveCommonGitDir(this.resolveGitDir(e)),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>REMOTES_CACHE_MAX;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){return remotesOf(await this.execGitAsync(REMOTES_ARGS,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=repoRemoteUrl(e);return(n===null?null:repoNameFromUrl(n))??path.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=forgeRemoteUrl(t.value);return n===null?ABSENT$2:ok$1(n)}async execForgeAsync(e,t,n){return this.launcher.launch({bin:e,args:[...t],cwd:n.cwd,timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=detectForge(t);return n===`github`?classifyForgePr(`gh pr view`,await this.execForgeAsync(FORGE_CLI.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,parseGithubPr):n===`gitlab`?classifyForgePr(`glab mr view`,await this.execForgeAsync(FORGE_CLI.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,parseGitlabMr):ABSENT$2}isWorktree(e){try{let t=path.join(e,`.git`);return!!(fs.existsSync(t)&&fs.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){debug(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=classify(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?ok$1(parseStatusV2(t.value)):t}},ObservableLru=class{values=import_dist$1.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,import_dist$1.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)}})}};const MAX_SESSIONS$4=256;var TranscriptFold=class{sessions;constructor(e,t,n,r,i=quietLogger,a=MAX_SESSIONS$4){this.empty=e,this.step=t,this.refreshes=n,this.clock=r,this.log=i,this.sessions=new ObservableLru(a)}async read(e,t,n){let r=this.sessions.get(e),i=r?.folded,a=statStamp(t);if(r?.folded&&a!==``&&r.folded.cursor.stamp===a){let{folded:t,answer:n}=r;return n.kind===`ok`&&n.value===t.value?(this.sessions.touch(e),n):this.store(e,t,{kind:`ok`,value:t.value})}let o=this.clock.monotonic(),s=await foldAppended(t,i,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${valueOf$1(e)}`,n,s,elapsedMs(this.clock,o)),s.kind===`failed`)return this.store(e,i,s);if(s.kind===`absent`)return this.store(e,i,{kind:`ok`,value:i?.value??this.empty});let{folded:c,longLines:l}=s.value;for(let e of longLineLog(l))this.log(`info`,e);return this.store(e,c,{kind:`ok`,value:c.value})}answer(e){return this.sessions.get(e)?.answer??pendingOf(`unread`)}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};const DEFAULT_CONTEXT_WINDOW=2e5;function step$2(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 ContextProvider=class{fold;constructor(e){let t=e.logger??quietLogger;this.fold=new TranscriptFold(void 0,step$2,(e.ledger??new RefreshLedger(t)).declare({name:`context`,scope:`session`,refresh:[`first`,`period`,`change`],lines:[]}),e.clock,t)}async refresh(e,t,n){return tokensFrom(await this.fold.read(e,t,n))}tokensOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:tokensFrom(t)}};function tokensFrom(e){return e.kind===`failed`?failed$2(`context transcript: ${e.reason}`,e.failedAt):e.value===void 0?(debug(`No main chain entries with usage data found`),ABSENT$2):ok$1(e.value)}function 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)}}function contextFromHook(e){let t=e.context_window;if(!t?.current_usage)return 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),a=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)}}function contextOver(e,t){let n=contextFromHook(t);if(n!==null)return ok$1(n);if(e.kind!==`ok`)return e;let r=contextLimitOf(t);return ok$1({totalTokens:e.value,maxTokens:r,...ratioPercentages(e.value,r)})}function contextLimitOf(e){return e.context_window?.context_window_size??DEFAULT_CONTEXT_WINDOW}const RECENT_WINDOW=20,EMPTY$2={messageCount:0,nonPrompts:0,recent:[]},NON_PROMPTS=new Set([`turn`,`interrupt`,`claude-code`]);function step$1(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!NON_PROMPTS.has(t.userEntry),recent:n.length>RECENT_WINDOW?n.slice(-RECENT_WINDOW):n}}function lastResponseTime(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 MetricsProvider=class{fold;constructor(e){let t=e.logger??quietLogger;this.fold=new TranscriptFold(EMPTY$2,step$1,(e.ledger??new RefreshLedger(t)).declare({name:`metrics`,scope:`session`,refresh:[`first`,`period`,`change`],lines:[]}),e.clock,t)}async refresh(e,t,n){return debug(`Getting metrics from the transcript for session: ${e}`),foldFrom(e,await this.fold.read(e,t,n))}foldOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:foldFrom(e,t)}};function foldFrom(e,t){return t.kind===`failed`?failed$2(`metrics (${e}): ${t.reason}`,t.failedAt):ok$1({lastResponseTime:lastResponseTime(t.value.recent),messageCount:t.value.messageCount,nonPrompts:t.value.nonPrompts})}function metricsOver(e,t){let n=t.cost;return n?e.kind===`ok`?ok$1({...e.value,responseTime:n.total_api_duration_ms/1e3,sessionDuration:n.total_duration_ms/1e3,linesAdded:n.total_lines_added,linesRemoved:n.total_lines_removed}):e:ABSENT$2}const EMPTY$1={command:null,todos:[],pending:[],done:[]};function bump(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 atBoundary(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 step(e,t){if(t.isSidechain)return e;let n=atBoundary(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=bump(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 report(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>bump(e,t.name),[]),done:e.done}}var ActivityProvider=class{fold;constructor(e){let t=e.logger??quietLogger;this.fold=new TranscriptFold(EMPTY$1,step,(e.ledger??new RefreshLedger(t)).declare({name:`activity`,scope:`session`,refresh:[`first`,`period`,`change`],lines:[]}),e.clock,t)}async refresh(e,t,n){return activityFrom(e,await this.fold.read(e,t,n))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:activityFrom(e,t)}};function activityFrom(e,t){return t.kind===`failed`?failed$2(`activity (${e}): ${t.reason}`,t.failedAt):ok$1(report(t.value))}function invocation(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function tmuxRun(e,t){return e.ok?{kind:`ok`,stdout:e.stdout}:e.reason===`rate-limited`?{kind:`rate-limited`,reason:failureText(e)}:{kind:`failed`,reason:`tmux ${t[0]} failed (${failureText(e)})`}}async function runTmuxAsync(e,t,n,r,i){return tmuxRun(await e.launch(invocation(t,n,r,i)),r)}const NAME_PERIOD_MS=3e4,MAX_ENTRIES$2=64;var TmuxService=class{names;constructor(e){let t=e.logger??quietLogger;this.names=new KeyedSource({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${valueOf$1(e.pane)} socket=${valueOf$1(e.socket)}`,read:t=>askSessionName(e.launcher,t),every:()=>({okMs:NAME_PERIOD_MS,failedMs:NAME_PERIOD_MS}),watch:NO_WATCH,maxEntries:MAX_ENTRIES$2,lines:REFRESH_TRIGGERS,logger:t,ledger:e.ledger??new RefreshLedger(t),clock:e.clock})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function askSessionName(e,t){let n=await runTmuxAsync(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return failed$2(n.reason,`read`);let r=n.stdout.trim();return r?ok$1(r):ABSENT$2}const HOST_PERIOD_MS=6e4,HOST_EVERY={okMs:HOST_PERIOD_MS,failedMs:HOST_PERIOD_MS};function shortHostname(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function syscall(e,t){try{let e=t();return Promise.resolve(e===``?ABSENT$2:ok$1(e))}catch(t){return Promise.resolve(failed$2(`host.${e}: ${String(t)}`,`read`))}}var HostService=class{name;user;constructor(e){let t=e.logger??quietLogger,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:()=>HOST_EVERY,watch:NO_WATCH,maxEntries:1,lines:REFRESH_TRIGGERS,logger:t,ledger:e.ledger??new RefreshLedger(t),clock:e.clock};this.name=new KeyedSource({...n,name:`host.name`,read:()=>syscall(`name`,()=>shortHostname(os.hostname()))}),this.user=new KeyedSource({...n,name:`host.user`,read:()=>syscall(`user`,()=>os.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()}};const MAX_FILES=64;var AutoCompactProvider=class{known=new ObservableLru(MAX_FILES);refreshes;constructor(e,t=quietLogger,n=new RefreshLedger(t)){this.clock=e,this.refreshes=n.declare({name:`autocompact`,scope:`configDir`,refresh:[`first`,`period`,`change`],lines:[]})}window(e,t){let n=stampAt(e),r=this.known.get(e);if(r!==void 0&&r.stamp===n)return this.known.touch(e),r.outcome;let i=this.clock.monotonic(),a=readAutoCompactWindow(e);return this.refreshes.recorded(`path=${valueOf$1(e)} stamp=${valueOf$1(n)}`,t,a,elapsedMs(this.clock,i)),this.known.set(e,{stamp:n,outcome:a}),a}stored(e){return this.known.get(e)?.outcome??pendingOf(`unread`)}getStats(){let{refreshes:e,failures:t,abandoned:n,lastMs:r}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,abandoned:n,lastMs:r}}};function stampAt(e){try{let t=fs.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:stampOf(t)}catch(e){return`unread:${e.code??`error`}`}}function readAutoCompactWindow(e){let t=readClaudeSettingsOutcome(e);if(t.kind!==`ok`)return t;let n=t.value.autoCompactWindow;return n===void 0?ok$1(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=LEAST&&n<=MOST?ok$1(n):failed$2(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${LEAST}–${MOST} tokens)`,`parse`)}const CACHE_TTL_MS=3600*1e3,TAIL_CHUNK=64*1024,TAIL_MAX=1*1024*1024,CACHE_HIT_RE=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function cacheActivityTs(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}const MAX_SESSIONS$3=256;var CacheExpiryProvider=class{known=new ObservableLru(MAX_SESSIONS$3);refreshes;constructor(e,t=quietLogger,n=new RefreshLedger(t)){this.clock=e,this.refreshes=n.declare({name:`cache`,scope:`session`,refresh:[`first`,`period`,`change`],lines:[]})}async refresh(e,t,n){let r=statStamp(t),i=this.known.get(e);if(i!==void 0&&r!==``&&i.stamp===r&&i.outcome.kind!==`failed`)return this.known.touch(e),i.outcome;let a=await this.read(e,t,r,n);return this.known.set(e,{stamp:r,outcome:a}),a}expiryOf(e){return this.known.get(e)?.outcome??pendingOf(`unread`)}getStats(){let{refreshes:e,failures:t,abandoned:n,lastMs:r}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,abandoned:n,lastMs:r}}async read(e,t,n,r){let i=this.clock.monotonic(),a=await cacheExpiresAt(t);return this.refreshes.recorded(`sid=${valueOf$1(e)} stamp=${valueOf$1(n)}`,r,a,elapsedMs(this.clock,i)),a}};async function cacheExpiresAt(e){let t=await findLastCacheActivityTs(e);return t.kind===`ok`?ok$1(Math.floor((t.value+CACHE_TTL_MS)/1e3)):t}async function findLastCacheActivityTs(e){for(let t of[TAIL_CHUNK,TAIL_MAX]){let n=await readTail(e,t);if(n.kind!==`ok`)return n;let r=scanBufferForLastCacheTs(n.value.buf,n.value.fromStart);if(r!=null)return ok$1(r);if(n.value.fromStart)return ABSENT$2}return ABSENT$2}function scanBufferForLastCacheTs(e,t){let n=e.toString(`utf8`).split(`
|
|
188
|
-
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!CACHE_HIT_RE.test(t))continue;let r=cacheActivityTs(t);if(r!=null)return r}return null}var RefreshFaults=class{bySession=import_dist$1.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:failed$2(n,`read`)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,import_dist$1.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const LINE_BREAK=/\r\n|\r|\n/g,textParser=e=>ok$1(e.replace(LINE_BREAK,` `).trim());function regexParser(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?failed$2(`regex no-match`,`parse`):ok$1(n.replace(LINE_BREAK,` `))}}const jsonParser=e=>{try{return ok$1(JSON.parse(e))}catch(e){return failed$2(`JSON parse failed: ${e.message}`,`parse`)}};function mergeWithDefault(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{},...PAYLOAD_INPUTS},segments:overlayByName(t.segments,segmentDeltas(t.segments,e.segments??{})),root:mergeRoot(e.root??EMPTY_ROWS,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:overlayByName(t.presets,presetDeltas(t.presets,e.presets??{})),themeDefaults:overlayByName(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function segmentDeltas(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 presetDeltas(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 overlayByName(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const RENAMED_SEGMENTS=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 renamedHint(e){let t=RENAMED_SEGMENTS.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`;case`removed`:return` (the built-in segment "${e}" was removed: ${t.why})`}}function requireCache(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: ${CACHE_KEYS.join(`, `)})`,line:findKeyLine(e.source,t.split(`.`))}),null):validateCache(e,`${t}.cache`,n.cache)}function requireCacheSpec(e){return{required:!0,json:cacheJson(),parse:(t,n,r,i)=>requireCache(t,n,i,e)??void 0}}const CACHE_SCHEMA={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&isValidDuration(n)?{ttl:n}:reject(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${describeValue(n)}`)},watch_file:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?{watch_file:n}:reject(e,t,`cache.watch_file must be a path string, got ${describeValue(n)}`)},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:reject(e,t,`cache.depends_on must be an array of variable-name strings, got ${describeValue(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:reject(e,t,`cache.key must be a non-empty template string, got ${describeValue(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:reject(e,t,`cache.never must be the literal boolean true, got ${describeValue(n)}`)}}};function validateCache(e,t,n){return oneOfPresent(e,CACHE_SCHEMA,t,n)}function cacheJson(){return oneOfPresentJson(CACHE_SCHEMA)}const DURATION_RE=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function isValidDuration(e){return DURATION_RE.test(e)}const RETIRED_VARIABLES=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 replacement(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 retiredVariableMessage(e){let t=RETIRED_VARIABLES.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${replacement(t)}`}function retiredReadHint(e){let t=RETIRED_VARIABLES.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${replacement(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const RETIRED_INPUT_PATHS=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`]]),RETIRED_GIT_FIELDS=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 json5Of(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 retiredGitKindMessage(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`?RETIRED_GIT_FIELDS.get(e.field):void 0;if(n===void 0){let e=[...RETIRED_GIT_FIELDS.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 ${json5Of(n.declare)} under a name of your own`}function validateVariables(e,t,n){if(n===void 0)return{};if(!isPlainObject$2(n))return e.issues.push({path:t,message:`${t} must be an object, got ${describeType(n)}`,line:findKeyLine(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=taggedUnion(e,VARIABLE_SCHEMA,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function literalValueSpec(){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 ${describeType(i)}`,line:findKeyLine(e.source,t.split(`.`))});return}return i}}}function typedDefaultSpec(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return optionalTypedDefault(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const PARSE_SCHEMA={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:reject(e,t,`parse.text must be the literal boolean true, got ${describeValue(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?{regex:n}:reject(e,t,`parse.regex must be a pattern string, got ${describeValue(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:reject(e,t,`parse.json must be the literal boolean true, got ${describeValue(n)}`)}}};function parseSpec(){return{required:!1,json:oneOfPresentJson(PARSE_SCHEMA),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:findKeyLine(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:oneOfPresent(e,PARSE_SCHEMA,`${t}.parse`,r.parse)??void 0)}}function sourceDefaultSpec(){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)=>isPlainObject$2(r.parse)&&`json`in r.parse?jsonDefault(e,t,r.default):optionalStringField(e,t,r,`default`)}}function jsonDefault(e,t,n){if(n!==void 0)return isSourceDefault(n)?n:reject(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${describeValue(n)}`)??void 0}function isSourceDefault(e){return e!==null&&isJsonValue(e)}const LITERAL_FIELDS={value:literalValueSpec(),default:optionalStringSpec()};function inputPathSpec(){let e=requireStringSpec();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:RETIRED_INPUT_PATHS.get(a);return o===void 0?a:reject(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const INPUT_FIELDS={path:inputPathSpec(),type:optionalEnumSpec([`string`,`number`,`boolean`]),default:typedDefaultSpec()},ENV_FIELDS={name:requireStringSpec(),default:optionalStringSpec()},FILE_FIELDS={path:requireStringSpec(),readMode:optionalEnumSpec([`whole`,`first-line`]),parse:parseSpec(),cache:requireCacheSpec(`file`),default:sourceDefaultSpec()},SHELL_FIELDS={command:requireStringSpec(),parse:parseSpec(),cache:requireCacheSpec(`shell`),default:sourceDefaultSpec()};function noCachePolicy(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const TEMPLATE_FIELDS={template:requireStringSpec(),type:optionalEnumSpec([`string`,`number`,`boolean`]),default:typedDefaultSpec()},TEMPLATE_VAR_REMOVED=noCachePolicy(`a template variable recomputes whenever a variable it reads changes`),TIME_FIELDS={layout:requireStringSpec(),default:optionalStringSpec()},TIME_VAR_REMOVED=noCachePolicy(`a time variable reads the instant its render is drawn at`),STATE_FIELDS={key:requireStringSpec(),default:optionalStringSpec()},VARIABLE_TAG=`kind`;function arm(e,t,n={}){return{...armFacets(VARIABLE_TAG,e,t),parse:(r,i,a)=>{refuseRemoved(r,n,i,a);let o=fields(r,t,i,a);return o===null?null:{kind:e,...o}}}}const VARIABLE_SCHEMA={tag:VARIABLE_TAG,noun:`source kind`,memberNoun:`variable`,arms:{literal:arm(`literal`,LITERAL_FIELDS),input:arm(`input`,INPUT_FIELDS),env:arm(`env`,ENV_FIELDS),file:arm(`file`,FILE_FIELDS),shell:arm(`shell`,SHELL_FIELDS),template:arm(`template`,TEMPLATE_FIELDS,TEMPLATE_VAR_REMOVED),time:arm(`time`,TIME_FIELDS,TIME_VAR_REMOVED),state:arm(`state`,STATE_FIELDS)},retired:{git:retiredGitKindMessage}};function variableDeclJson(){return taggedUnionJson(VARIABLE_SCHEMA)}function variablesMapJson(){return{type:`object`,additionalProperties:variableDeclJson()}}const SETTING_NAME=/^[A-Za-z_][A-Za-z0-9_]*$/,SETTING_NAME_JSON={pattern:SETTING_NAME.source},SETTING_VALUE_JSON={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},SETTING_DECL_JSON={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`,...SETTING_NAME_JSON}}}]},default:SETTING_VALUE_JSON}},DECL_KEYS=[`label`,`domain`,`default`],RANGE_KEYS=[`min`,`max`,`step`,`atLeast`];function issue$1(e,t,n){e.issues.push({path:t,message:n,line:findKeyLine(e.source,t.split(`.`))})}function parseDomain(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 issue$1(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 issue$1(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?issue$1(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(isPlainObject$2(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!RANGE_KEYS.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}}:issue$1(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 issue$1(e,t,`domain must be "bool", a list of words, or { min, max }, got ${describeValue(n)}`)}function parseSettingDecl(e,t,n){if(!isPlainObject$2(n))return issue$1(e,t,`${t} must be { label, domain, default }, got ${describeType(n)}`);for(let r of Object.keys(n))DECL_KEYS.includes(r)||issue$1(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${DECL_KEYS.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||issue$1(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${describeValue(r)}`);let a=parseDomain(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!isSettingValue(n.default)||!inSettingDomain(o,n.default)?issue$1(e,`${t}.default`,`default must be ${describeSettingDomain(o)}, got ${describeValue(n.default)}`):o}function isSettingValue(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const IMPLIED_HINTS={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${THEME_SETTING}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function isImplied(e){return IMPLIED_SETTINGS.includes(e)}function settingsDeclSpec(){return{required:!1,json:{type:`object`,propertyNames:{...SETTING_NAME_JSON,not:{enum:[...IMPLIED_SETTINGS]}},additionalProperties:SETTING_DECL_JSON},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!isPlainObject$2(i))return issue$1(e,a,`${a} must be an object of name → { label, domain, default }, got ${describeType(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!SETTING_NAME.test(t)){issue$1(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(isImplied(t)){issue$1(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${IMPLIED_HINTS[t]}`);continue}let r=parseSettingDecl(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const RESERVED_ID_JSON=RESERVED_NAMESPACES.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function placementIdSpec(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${RESERVED_ID_JSON})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!isReservedName(i)?i:issue$1(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${RESERVED_NAMESPACES.map(e=>`"${e}"`).join(`, `)} namespaces, got ${describeValue(i)}`)}}}function placementSettingsSpec(){return{required:!1,json:{type:`object`,propertyNames:SETTING_NAME_JSON,additionalProperties:SETTING_VALUE_JSON},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!isPlainObject$2(i))return issue$1(e,a,`a placement's "settings" must be an object of setting name → value, got ${describeType(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))isSettingValue(n)?o[t]=n:issue$1(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${describeType(n)}`);return o}}}function inheritableSegmentNames(e){return new Set(Object.keys(e.segments).filter(e=>!isReservedName(e)))}function validateSegments(e,t,n){if(t===void 0)return{};if(!isPlainObject$2(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${describeType(t)}`,line:findKeyLine(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=record(e,n.has(i)?SEGMENT_DELTA_SCHEMA:SEGMENT_SCHEMA,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function joinTemplateBody(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 ${describeType(s)}`,line:findKeyLine(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 ${describeType(i)}`,line:findKeyLine(e.source,[...t.split(`.`),n])})}const TEMPLATE_BODY_JSON={anyOf:[{type:`string`},{type:`array`,items:{type:`string`}}]};function ownTemplateSpec(){return{required:!0,json:TEMPLATE_BODY_JSON,parse:(e,t,n,r)=>r[n]===void 0?reject(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${renamedHint(t.slice(9))}`)??void 0:joinTemplateBody(e,t,n,r)}}function optionalTemplateBodySpec(){return{required:!1,json:TEMPLATE_BODY_JSON,parse:(e,t,n,r)=>r[n]===void 0?void 0:joinTemplateBody(e,t,n,r)}}function partialsSpec(){return{required:!1,json:{type:`object`,additionalProperties:TEMPLATE_BODY_JSON},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;if(!isPlainObject$2(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be an object, got ${describeType(i)}`,line:findKeyLine(e.source,[...t.split(`.`),n])});return}let a=Object.create(null);for(let r of Object.keys(i)){let o=joinTemplateBody(e,`${t}.${n}`,r,i);o!==void 0&&(a[r]=o)}return a}}}function widthSpec(){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 ${describeValue(i)}`,line:findKeyLine(e.source,[...t.split(`.`),n])})}}}}function varsSpec(){return{required:!1,json:variablesMapJson(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return validateVariables(e,`${t}.${n}`,i)}}}const SEGMENT_FIELDS={template:ownTemplateSpec(),description:optionalStringSpec(),group:optionalEnumSpec(SEGMENT_GROUPS),width:widthSpec(),justify:optionalEnumSpec(JUSTIFY_MODES),truncate:optionalEnumSpec(TRUNCATE_MODES),bg:optionalStringSpec(),fg:optionalStringSpec(),when:optionalStringSpec(),palette:paletteSpec(),vars:varsSpec(),settings:settingsDeclSpec(),missingData:optionalEnumSpec(MISSING_DATA),partials:partialsSpec()},SEGMENT_SCHEMA={noun:`segment key`,fields:SEGMENT_FIELDS},SEGMENT_DELTA_SCHEMA={noun:`segment key`,fields:{...SEGMENT_FIELDS,template:optionalTemplateBodySpec()}},SEGMENT_DEF_NAME=`Segment`,SEGMENT_DELTA_DEF_NAME=`SegmentDelta`,SEGMENT_REF=`#/definitions/${SEGMENT_DEF_NAME}`,SEGMENT_DELTA_REF=`#/definitions/${SEGMENT_DELTA_DEF_NAME}`;function validateHelpers(e,t){if(t===void 0)return{};if(!isPlainObject$2(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${describeType(t)}`,line:findKeyLine(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 ${describeValue(i)}`,line:findKeyLine(e.source,[`helpers`,r])});continue}n[r]=i}return n}function validateActions(e,t,n){if(t===void 0)return{};if(!isPlainObject$2(t))return issue(e,`actions`,`actions must be an object, got ${describeType(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=validateActionDecl(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function issue(e,t,n){e.issues.push({path:t,message:n,line:findKeyLine(e.source,t.split(`.`))})}function validateActionDecl(e,t,n,r){if(!isPlainObject$2(n))return issue(e,t,`${t} must be an action object, got ${describeType(n)}`),null;if(`persistWhen`in n)return issue(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=ACTION_KEYS.filter(e=>e in n);return i.length===1?actionArms(r)[i[0]](e,t,n):(issue(e,t,`action must declare exactly one of: ${ACTION_KEYS.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function actionHomeOf(e){return e===`<default>`?{dir:null}:path.isAbsolute(e)?{dir:path.dirname(e)}:{text:e}}const actionArms=e=>({set:(e,t,n)=>valueSourceAction(e,t,n,`set`,SET_ARMS),persist:(e,t,n)=>valueSourceAction(e,t,n,`persist`,PERSIST_ARMS),copy:templateArm(`copy`),open:templateArm(`open`),reset:resetArm,undo:markerArm(`undo`),redo:markerArm(`redo`),back:markerArm(`back`),rewind:markerArm(`rewind`),save:markerArm(`save`),preset:presetArm,themeDefault:themeDefaultArm,doctor:doctorArm,slash:slashArm,run:runArm(e),do:doArm});function templateArm(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&issue(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=requireString(t,n,r,e);return i===null?null:{[e]:i}}}function resetArm(e,t,n){for(let r of Object.keys(n))r!==`reset`&&issue(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=slashFreeString(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 MARKER_SUBJECT={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 markerArm(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&issue(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(issue(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${MARKER_SUBJECT[e]}), got ${describeValue(r[e])}`),null)}}function presetArm(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||issue(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return issue(e,`${t}.preset`,`preset must be "save" or "delete", got ${describeValue(r)}`),null;if(r===`save`)return{preset:`save`};let a=requireString(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function themeDefaultArm(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&issue(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(issue(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${describeValue(n.themeDefault)}`),null)}const DOCTOR_KEYS={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function doctorArm(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(DOCTOR_KEYS,r),a=i?DOCTOR_KEYS[r]:[...new Set(Object.values(DOCTOR_KEYS).flat())];for(let r of Object.keys(n))a.includes(r)||issue(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return issue(e,`${t}.doctor`,`doctor must be ${Object.keys(DOCTOR_KEYS).map(e=>`"${e}"`).join(`, `)}, got ${describeValue(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?MARKED_CHECKS:CHECKS;if(typeof o!=`string`||!s.some(e=>e.name===o))return issue(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${describeValue(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return GLYPH_MARKS.includes(c)?{doctor:`mark`,check:o,mark:c}:(issue(e,`${t}.mark`,`doctor mark must be ${GLYPH_MARKS.map(e=>`"${e}"`).join(` or `)}, got ${describeValue(c)}`),null)}function slashArm(e,t,n){for(let r of Object.keys(n))r!==`slash`&&issue(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=parseSlashLine(n.slash);return r.kind===`refused`?(issue(e,`${t}.slash`,r.reason),null):{slash:r.line}}const RUN_KEYS=[`run`,`env`,`refreshes`],ENV_NAME=/^[A-Za-z_][A-Za-z0-9_]*$/;function runArm(e){return(t,n,r)=>{for(let e of Object.keys(r))RUN_KEYS.includes(e)||issue(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${RUN_KEYS.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&issue(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${describeValue(a)}`);let o=r.env??{};(!isPlainObject$2(o)||Object.entries(o).some(([e,t])=>!ENV_NAME.test(e)||typeof t!=`string`))&&issue(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${describeValue(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&issue(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${describeValue(s)}`),`dir`in e||issue(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}}}const RUN_ARM_JSON={type:`object`,properties:{run:{type:`array`,items:{type:`string`},minItems:1},env:{type:`object`,propertyNames:{pattern:ENV_NAME.source},additionalProperties:{type:`string`}},refreshes:{type:`array`,items:{type:`string`,minLength:1}}},required:[`run`],additionalProperties:!1};function doArm(e,t,n){for(let r of Object.keys(n))r!==`do`&&issue(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===``)?(issue(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 ${describeValue(r)}`),null):{do:r}}function slashFreeString(e,t,n,r,i,a){let o=requireString(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(issue(e,s,i),null):o.includes(`/`)?(issue(e,s,a(o)),null):o}const DISCRIMINATOR_NOUN={set:`the SessionState key to write`,persist:`the config globals field to write`};function validateDiscriminatorKey(e,t,n,r){let i=DISCRIMINATOR_NOUN[r],a=slashFreeString(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 wireName(e){return e===`set`?`set-state`:`set-config`}const TO_FIELDS_SET={to:setLiteralSpec(`set`)},TO_FIELDS_PERSIST={to:setLiteralSpec(`persist`)},FROM_FIELDS_SET={from:fromSpec(`set`)},FROM_FIELDS_PERSIST={from:fromSpec(`persist`)},BOUNDED_FIELDS={min:requireIntSpec(),max:requireIntSpec(),by:requireIntSpec()},INT_FIELDS={int:intMarkerSpec()},CYCLE_FIELDS_SET={cycle:cycleSpec(`set`)},CYCLE_FIELDS_PERSIST={cycle:cycleSpec(`persist`)},REMOVE_SEGMENT_FIELDS={removeSegment:layoutNameSpec(`removeSegment`)},INSERT_SEGMENT_FIELDS={insertSegment:layoutNameSpec(`insertSegment`),anchor:layoutNameSpec(`anchor`),relation:relationSpec()},INSERT_SEGMENT_FROM_FIELDS={insertSegmentFrom:fromSpec(`persist`),anchor:layoutNameSpec(`anchor`),relation:relationSpec()},minLessThanMax={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},byNonZero={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function valueSourceArm(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>fields(e,t,n,r),c=objectJson(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?refine(s,...n):s}}const SET_ARMS=[valueSourceArm(`set`,TO_FIELDS_SET),valueSourceArm(`set`,FROM_FIELDS_SET),valueSourceArm(`set`,BOUNDED_FIELDS,[minLessThanMax,byNonZero]),valueSourceArm(`set`,INT_FIELDS),valueSourceArm(`set`,CYCLE_FIELDS_SET)],PERSIST_ARMS=[valueSourceArm(`persist`,TO_FIELDS_PERSIST),valueSourceArm(`persist`,FROM_FIELDS_PERSIST),valueSourceArm(`persist`,BOUNDED_FIELDS,[minLessThanMax,byNonZero]),valueSourceArm(`persist`,CYCLE_FIELDS_PERSIST),valueSourceArm(`persist`,REMOVE_SEGMENT_FIELDS),valueSourceArm(`persist`,INSERT_SEGMENT_FIELDS,[],[`insertSegment`]),valueSourceArm(`persist`,INSERT_SEGMENT_FROM_FIELDS,[],[`insertSegmentFrom`])];function valueSourceClauses(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 VALUE_SOURCE_MESSAGE(e){let t=valueSourceClauses(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 valueSourceAction(e,t,n,r,i){let a=validateDiscriminatorKey(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return issue(e,t,`${VALUE_SOURCE_MESSAGE(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)||issue(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 setLiteralSpec(e){let t=wireName(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>slashFreeString(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 fromSpec(e){let t=wireName(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===``){issue(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){issue(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===``)){issue(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){issue(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){issue(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}issue(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${describeValue(o)}`)}}}function cycleSpec(e){let t=wireName(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`)){issue(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${describeType(o)}`);return}let c=o;if(c.length<2){issue(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){issue(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){issue(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){issue(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function intMarkerSpec(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){issue(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${describeValue(r[n])}`);return}return!0}}}function layoutNameSpec(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=requireString(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){issue(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){issue(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 relationSpec(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){issue(e,`${t}.${n}`,`relation must be "before" or "after", got ${describeValue(i)}`);return}return i}}}function requireIntSpec(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){issue(e,`${t}.${n}`,`${n} must be an integer, got ${describeValue(i)}`);return}return i}}}function droppedPluginNotice(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const DEFINITION_KEYS=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),DEFINITION_FILE=`plugin.json5`,PLUGIN_NAME=/^[a-z][a-z0-9_]*$/;function pluginDefinition(e,t){let n=path.basename(path.dirname(e));return PLUGIN_NAME.test(n)?{path:e,scope:t,name:n}:{path:e,scope:t,name:void 0}}function pluginDataVar(e){return`${e}.data`}const STORAGE_FOLDER=`session`;function sessionFileName(e){return`${e}.json`}function attempt(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:reasonOf(e)}}}function reasonOf(e){return e instanceof ConfigError?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 listedPlugins(e,t,n,r){return e.map(e=>pluginDefinition(resolveUserPath(path.dirname(t),e,r),n))}function applyPlugins(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=n.path,o=n.name===void 0?void 0:pluginNs(n),s=(t,r)=>{let i=new Map(e.rendering);return o!==void 0&&r!==e.config&&i.delete(o),{...e,config:r,rendering:i,dropped:[...e.dropped,{...n,reason:t}]}};if(path.basename(a)!==`plugin.json5`){let t=`a plugin is a folder holding its ${DEFINITION_FILE}, and the folder's name is the plugin's: move this file to <dir>/<name>/${DEFINITION_FILE} and list that`;return s(t,o===void 0?e.config:tombstone(withoutPlugin(e.config,o),o,{...n,reason:t}))}if(n.name===void 0||o===void 0)return s(`its folder "${path.basename(path.dirname(a))}" is not a plugin name (one matching ${PLUGIN_NAME}: it prefixes every name the plugin declares)`,e.config);let c=i.get(o);if(c!==void 0)return s(`plugin "${n.name}" is already listed, from ${c}`,e.config);i.set(o,a);let l=withoutPlugin(e.config,o),u=attempt(()=>{let i=fs.readFileSync(a,`utf-8`),s=mergeWithDefault(fragmentOf(a,n,{source:i,json:import_lib.default.parse(i)},t),l);return requireOneSourcePerFile(a,o,s),r(s,o,l!==e.config),s});if(u.ok)return{...e,config:u.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[o,n]])};let d={...n,reason:u.reason};return s(u.reason,tombstone(l,o,d))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function withoutPlugin(e,t){let n=ownedBy(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 tombstone(e,t,n){return{...e,variables:{...e.variables,[t]:{kind:`dropped`,reason:droppedPluginNotice(n),definition:n.path}}}}function tombstonesOf(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})=>ownedBy(t)(e))}function dropsOwning(e,t){let n=tombstonesOf(e.config),r=[...e.rendering.keys()].map(ownedBy),i=[...t,...e.dropped].filter(e=>e.name===void 0);return e=>{let t=scopeOf(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:droppedPluginNotice(e)})):[{definition:a.definition,notice:a.notice}]}}function withDroppedPlacements(e,t,n){let r=presetNames(e.presets).flatMap(t=>[...walkNodes(presetRoot(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,standIn(e,t.map(e=>e.notice),r.filter(t=>t.name===e))])),o=tombstonesOf(e),s=Object.values(e.variables).some(e=>e.kind===`dropped`),c=s?Object.values(e.segments).flatMap(e=>[...SEGMENT_TEMPLATE_FIELDS.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=>templateActionRefs(t,e.helpers).map(e=>e.name)),...l],e.actions),f=u(c.flatMap(t=>[...templateHelperCalls(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 standIn(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,settingFor(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function settingFor(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 fragmentOf(e,t,{source:n,json:r},{checkout:i,home:a}){let o=pluginNs(t),s=[],c=()=>{throw new ConfigError(e,s)};if(!isPlainObject$2(r))return s.push({path:``,message:`a plugin definition must be an object, got ${describeType(r)}`}),c();for(let t of Object.keys(r))DEFINITION_KEYS.has(t)||s.push({path:t,message:t===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${path.basename(path.dirname(e))}") — remove "plugin"`:`a plugin definition may not declare "${t}". Expected only: ${[...DEFINITION_KEYS].join(`, `)}`});let l=r.data===void 0?void 0:dataPathOf(r.data,e,i,a,s),u=r.sources===void 0?{}:sourcesOf$1(r.sources,e,s);if(s.length>0)return c();let d={source:n,issues:s,allowedPalettes:new Set(listResolvablePaletteNames()),groups:[],unplaced:[],inherited:[]},f=l===void 0?{}:validateVariables(d,`data`,{[pluginDataVar(o)]:{kind:`file`,path:l,parse:{json:!0},cache:{watch_file:l},default:{}}}),p=validateVariables(d,`variables`,r.variables);for(let[e,t]of[[`variables`,Object.keys(p)],[`sources`,Object.keys(u)]])t.includes(`data`)&&s.push({path:`${e}.data`,message:`"data" names the plugin's data file (.${pluginDataVar(o)}), 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(p,e)&&s.push({path:`sources.${e}`,message:`source "${e}" and variable "${e}" are one name (.${o}.${e}): give one of them another name`});let m={variables:{...f,...prefixed(o,u),...prefixed(o,Object.fromEntries(Object.entries(p).map(([e,t])=>[e,stateKeyUnder(o,t)])))},segments:prefixed(o,stateKeysUnder(o,validateSegments(d,r.segments,new Set))),helpers:prefixed(o,validateHelpers(d,r.helpers)),actions:prefixed(o,setKeysUnder(o,validateActions(d,r.actions,{dir:fs.realpathSync(path.dirname(e))})))};s.push(...wrongScopeRefs(m,t));let h=boundToSelf(o,m);for(let[e,t]of fragmentTemplates(h))try{SYNTAX_ENGINE.parse(t)}catch(t){s.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return s.length>0&&c(),h}function boundToSelf(e,t){let n=t=>bindSelf(t,SELF,e),r=t=>ownedBy(`self`)(t)?`${e}${t.slice(SELF.length)}`:t,i=(e,t)=>Object.fromEntries(Object.entries(e??{}).map(([e,n])=>[e,t(n)]));return{...t,variables:i(t.variables,e=>selfDepends(mapVariableTemplates(e,n),r)),segments:i(t.segments,e=>({...e,...Object.fromEntries(SEGMENT_TEMPLATE_FIELDS.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=>selfDepends(mapVariableTemplates(e,n),r))}})),helpers:i(t.helpers,n),actions:i(t.actions,e=>mapActionNames(mapActionTemplates(e,n),r))}}function selfDepends(e,t){return hasCacheField(e)&&`depends_on`in e.cache?{...e,cache:{depends_on:e.cache.depends_on.map(t)}}:e}function mapActionNames(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 SEGMENT_TEMPLATE_FIELDS=[`template`,`bg`,`fg`,`when`];function wrongScopeRefs(e,t){let n=e.helpers??{},r=PLUGIN_SCOPES.filter(e=>e!==t.scope).map(e=>({scope:e,ns:pluginNs({scope:e,name:t.name})})),i=new Map,a=(e,n,a)=>{let o=r.find(({ns:e})=>ownedBy(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 ${pluginNs(t)}: a plugin names itself without its scope — write ${s}${SELF}${n.slice(o.ns.length)}`})},o=[...[...fragmentTemplates(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 templateReads(t,n))i===null&&a(e,r,!0);for(let{name:r,via:i}of templateActionRefs(t,n))i===null&&a(e,r,!1);for(let n of templateHelperCalls(t,{}))a(e,n,!1)}for(let[t,n]of Object.entries(e.actions??{}))mapActionNames(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(hasCacheField(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*fragmentTemplates(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of variableTemplates(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of SEGMENT_TEMPLATE_FIELDS){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 variableTemplates(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 actionTemplates(n))yield[`actions.${t}.${e}`,r]}function prefixed(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,n]))}function keyUnder(e,t){return`${e}.${t}`}function stateKeyUnder(e,t){return t.kind===`state`?{...t,key:keyUnder(e,t.key)}:t}function stateKeysUnder(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,stateKeyUnder(e,n)]))}]))}function setKeysUnder(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:keyUnder(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>keyUnder(e,t))}:n]))}const SOURCE_NAME=PLUGIN_NAME,BUILT_SOURCE={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function sourcesOf$1(e,t,n){if(!isPlainObject$2(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${describeType(e)}`}),{};let r=path.join(fs.realpathSync(path.dirname(t)),STORAGE_FOLDER),i=JSON.stringify(BUILT_SOURCE),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!SOURCE_NAME.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${SOURCE_NAME}: it is the last segment of .<scope>.<plugin>.${t})`});continue}let s=unbuilt(o,BUILT_SOURCE,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 requireOneSourcePerFile(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=sourceFileOf(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=ownedBy(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 ConfigError(e,a)}function sourceFileOf(e){return path.join(e.storage,sessionFileName(`<session id>`))}function unbuilt(e,t,n){return!isPlainObject$2(t)||!isPlainObject$2(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)?unbuilt(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function dataPathOf(e,t,n,r,i){if(typeof e==`string`&&e!==``)return resolveUserPath(path.dirname(t),e,r);if(isPlainObject$2(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(path.isAbsolute(t)||t.startsWith(`~`)||path.normalize(t).split(path.sep)[0]===`..`){i.push({path:`data.checkout`,message:`data.checkout "${t}" must be a path inside the checkout, relative to its root (like ".lit/statusline.json"): no absolute path, "~" or ".."`});return}if(n===null){i.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return path.resolve(n.root,t)}if(isPlainObject$2(e)&&`project`in e){i.push({path:`data.project`,message:`data: { project } is now data: { checkout }: the same path, relative to the root of the git checkout the session works in (a linked worktree is its own checkout)`});return}i.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { checkout: "<path>" } relative to the root of the session's checkout`})}const DAY_MS=1440*60*1e3,STORAGE_FILE_MAX_AGE_MS=30*DAY_MS,STORAGE_SWEEP_EVERY_MS=DAY_MS,MAX_ENTRIES$1=256,fileName=e=>sessionFileName(e),fileOf=e=>path.join(e.folder,fileName(e.sessionId)),keyString=e=>JSON.stringify([e.folder,e.generation]);function madeOnce(e){try{fs.mkdirSync(e)}catch(t){let n;try{n=fs.statSync(e)}catch{throw t}if(!n.isDirectory())throw Error(`${e} is not a folder`)}}const current=(e,t)=>e.health.kind===`watching`&&t.kind===`found`&&t.identity!==`gone`&&e.identity!==`gone`&&sameIdentity(t.identity,e.identity);var ManagedStorage=class{sessions;watched=new Map;holds=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;generations=0;watchers;logger;identityOf;fileEvents;clock;unsubscribe;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??statIdentity,this.fileEvents=e.fileEvents,this.clock=e.clock,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new KeyedSource({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.folder,e.sessionId]),fields:e=>`file=${valueOf$1(fileOf(e))}`,read:e=>this.read(e),every:()=>null,watch:NO_WATCH,maxEntries:MAX_ENTRIES$1,lines:REFRESH_TRIGGERS,logger:e.logger,ledger:e.ledger??new RefreshLedger(e.logger),clock:e.clock})}hold(e,t){this.holds.set(e,t);for(let e of new Set(t)){let t=this.watched.get(e),n=this.found(e);if(t!==void 0&¤t(t,n))continue;let r=this.generations++;t!==void 0&&this.logger(`info`,`plugin storage generation folder=${valueOf$1(e)} generation=${r}`),this.opened({folder:e,generation:r},n),t!==void 0&&this.closed(t),this.sessions.changed(t=>t.folder===e)}this.closeUnheld()}release(e){this.holds.delete(e),this.closeUnheld()}declare(e,t,n){return this.sessions.declare(e,{folder:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({folder:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost}}close(){this.unsubscribe(),this.sessions.close(),this.holds.clear(),this.closeUnheld()}found(e){try{return madeOnce(e),{kind:`found`,identity:this.identityOf(e)}}catch(e){return{kind:`unusable`,reason:`could not be created or read: ${e.message}`}}}closeUnheld(){let e=new Set([...this.holds.values()].flat());for(let[t,n]of[...this.watched])e.has(t)||this.closed(n)}opened(e,t){let n={key:e,identity:t.kind===`found`?t.identity:`gone`,handle:this.watchers.acquire(`plugin-storage:${keyString(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(n,e)),stopSweep:this.clock.every(STORAGE_SWEEP_EVERY_MS,()=>void this.sweep(e),{unref:!0}),health:{kind:`watching`}};this.watched.set(e.folder,n),t.kind===`unusable`&&this.faulted(n,`unusable`,t.reason);for(let e of n.handle.deaf)this.faulted(n,`refused`,e.reason);return this.sweep(e),n}closed(e){this.watched.get(e.key.folder)===e&&this.watched.delete(e.key.folder),e.health={kind:`closed`},e.stopSweep(),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>e.folder===n.folder;switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.includes(path.join(n.folder,path.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.includes(fileOf(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}=e,i;try{i=this.identityOf(r.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let a=e.identity;if(i!==`gone`&&a!==`gone`&&sameIdentity(i,a)){t();return}e.health={kind:`lost`},this.lost++,this.logger(`info`,`plugin storage lost folder=${valueOf$1(r.folder)} generation=${r.generation} now=${i===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>e.folder===r.folder)}faulted(e,t,n){let{key:r}=e;e.health.kind===`watching`&&(e.health={kind:`faulted`,reason:n},this.faultCounts[t]++,this.logger(`warn`,`plugin storage fault folder=${valueOf$1(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>e.folder===r.folder))}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(e);if(t===void 0)return null;let{health:n}=t;switch(n.kind){case`faulted`:return`cannot refresh: ${e} ${n.reason}; reload the config or restart the daemon`;case`watching`:case`lost`:{let t=stallReason(this.fileEvents.delivery());return t===null?null:`cannot refresh: ${e}: ${t}`}case`closed`:return null}}async read(e){let t=this.standing(e.folder);if(t!==null)return failed$2(t,`read`);let n=fileOf(e),r;try{r=await fs.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?ABSENT$2:failed$2(`${n}: ${t.message}`,`read`)}if(r.trim()===``)return ABSENT$2;let i=jsonParser(r);return i.kind===`failed`?failed$2(`${n}: ${i.reason}`,i.failedAt):i}async sweep(e){let t=this.clock.monotonic(),n=this.clock.now()-STORAGE_FILE_MAX_AGE_MS,r=0,i=0,a=()=>`plugin storage sweep folder=${valueOf$1(e.folder)} scanned=${r} removed=${i} took=${elapsedMs(this.clock,t)}ms`;try{let t=await fs.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=path.join(e.folder,a.name);try{let{mtimeMs:r}=await fs.promises.stat(t),o=this.sessions.isHeld(t=>t.folder===e.folder&&fileName(t.sessionId)===a.name);if(r>=n||o)continue;await fs.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)}`)}}};const TRANSCRIPT_PERIOD={okMs:1e4,failedMs:1e4},MAX_UNHELD=16,keyOfFollowed=({session:e,transcript:t,settings:n})=>[e,t,n].join(`\0`);var TranscriptLanes=class{source;constructor(e){this.deps=e,this.source=new KeyedSource({name:`transcript`,scope:`session`,keyOf:keyOfFollowed,fields:({session:e})=>`sid=${valueOf$1(e)}`,read:(e,t,n)=>this.read(e,n),every:()=>e.every??TRANSCRIPT_PERIOD,watch:(e,t)=>this.watch(e,t),maxEntries:MAX_UNHELD,lines:[`first`,`change`,`supersede`],logger:e.logger,ledger:e.ledger,clock:e.clock})}declare(e,t){return this.source.declare(e,t)}stats(){return this.source.stats()}close(){this.source.close()}watch(e,t){let{transcript:n,settings:r}=e,i=this.deps.watchers.acquire(`transcript-lanes:${keyOfFollowed(e)}`,{dirs:[{path:dirname(n),filenames:[basename(n)]},{path:dirname(r),filenames:[basename(r)]}]},t);return()=>i.release()}async read({session:e,transcript:t,settings:n},r){let{owners:i,clock:a,logger:o}=this.deps,s=i.usageStore.refresh(e,t,r),c={session:()=>s.usage(),context:()=>i.contextProvider.refresh(e,t,r),metrics:()=>i.metricsProvider.refresh(e,t,r),activity:()=>i.activityProvider.refresh(e,t,r),cache:()=>i.cacheExpiry.refresh(e,t,r),speed:()=>s.speed(a.now()),autocompact:async()=>i.autoCompact.window(n,r)};return await Promise.all(REFRESH_LANES.map(async t=>{let n=null;try{await c[t]()}catch(e){o(`error`,`${t} lane threw: ${inspect(e)}`),n=`${t}: ${String(e)}`}i.faults.refreshed(e,t,n)})),ok$1(null)}};function createPayloadProviders(e){let{launcher:t,clock:n,logger:r,ledger:i}=e,a={usageStore:new SessionUsageStore({host:e.host,clock:n,logger:r,ledger:i}),contextProvider:new ContextProvider({clock:n,logger:r,ledger:i}),metricsProvider:new MetricsProvider({clock:n,logger:r,ledger:i}),activityProvider:new ActivityProvider({clock:n,logger:r,ledger:i}),autoCompact:new AutoCompactProvider(n,r,i),cacheExpiry:new CacheExpiryProvider(n,r,i),faults:new RefreshFaults},o={hostService:new HostService({clock:n,logger:r,ledger:i}),gitProvider:new GitDataProvider({inner:new GitService(t),watchers:e.watchers,clock:n,logger:r,ledger:i}),tmuxService:new TmuxService({launcher:t,clock:n,logger:r,ledger:i}),transcriptLanes:new TranscriptLanes({owners:a,watchers:e.watchers,clock:n,logger:r,ledger:i}),managedStorage:new ManagedStorage({watchers:e.watchers,fileEvents:e.fileEvents,clock:n,logger:r,ledger:i})};return{...a,...o,home:e.host.home,sourceRuns:e.sourceRuns,log:e.logger,closes:[[`gitProvider close`,()=>o.gitProvider.close()],[`transcriptLanes close`,()=>o.transcriptLanes.close()],[`usageStore close`,()=>a.usageStore.close()],[`tmuxService close`,()=>o.tmuxService.close()],[`hostService close`,()=>o.hostService.close()],[`managedStorage close`,()=>o.managedStorage.close()]]}}async function runTeardown(e,t){let n=[];for(let[r,i]of e)try{await i()}catch(e){t(`warn`,`${r} failed: ${inspect(e)}`),n.push(r)}return n}var require_ByteBuffer=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let{pow:t,floor:n}=Math,r=t(2,32);e.default=class e{static allocate(t=16){return new e(new Uint8Array(t))}constructor(e){this.position=0,this.data=e,this.int32ArrayForConvert=new Uint32Array(1),this.int8ArrayForConvert=new Uint8Array(this.int32ArrayForConvert.buffer)}put(e){if(this.position===this.data.length){let e=this.data;this.data=new Uint8Array(this.data.length*2),this.data.set(e)}this.data[this.position]=e,this.position++}putInt32(e){if(this.data.length-this.position<4){let e=this.data;this.data=new Uint8Array(this.data.length*2+4),this.data.set(e)}this.int32ArrayForConvert[0]=e,this.data.set(this.int8ArrayForConvert.reverse(),this.position),this.position+=4}putInt64(e){this.putInt32(n(e/r)),this.putInt32(e)}putArray(e){if(this.data.length-this.position<e.byteLength){let t=this.data;this.data=new Uint8Array(this.position+e.byteLength),this.data.set(t)}this.data.set(e,this.position),this.position+=e.byteLength}get(){let e=this.data[this.position];return this.position++,e}getInt32(){this.int8ArrayForConvert.set(this.data.slice(this.position,this.position+4).reverse());let e=this.int32ArrayForConvert[0];return this.position+=4,e}getInt64(){let e=this.getInt32(),t=this.getInt32();return e*r+t}resetPosition(){this.position=0}}})),require_HistogramIterationValue=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=class{constructor(){this.reset()}reset(){this.valueIteratedTo=0,this.valueIteratedFrom=0,this.countAtValueIteratedTo=0,this.countAddedInThisIterationStep=0,this.totalCountToThisValue=0,this.totalValueToThisValue=0,this.percentile=0,this.percentileLevelIteratedTo=0}}})),require_JsHistogramIterator=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_HistogramIterationValue();e.default=class{constructor(){this.currentIterationValue=new t.default}resetIterator(e){this.histogram=e,this.savedHistogramTotalRawCount=e.totalCount,this.arrayTotalCount=e.totalCount,this.currentIndex=0,this.currentValueAtIndex=0,this.nextValueAtIndex=2**e.unitMagnitude,this.prevValueIteratedTo=0,this.totalCountToPrevIndex=0,this.totalCountToCurrentIndex=0,this.totalValueToCurrentIndex=0,this.countAtThisValue=0,this.freshSubBucket=!0,this.currentIterationValue.reset()}hasNext(){if(this.histogram.totalCount!==this.savedHistogramTotalRawCount)throw`Concurrent Modification Exception`;return this.totalCountToCurrentIndex<this.arrayTotalCount}next(){for(;!this.exhaustedSubBuckets();){if(this.countAtThisValue=this.histogram.getCountAtIndex(this.currentIndex),this.freshSubBucket&&=(this.totalCountToCurrentIndex+=this.countAtThisValue,this.totalValueToCurrentIndex+=this.countAtThisValue*this.histogram.highestEquivalentValue(this.currentValueAtIndex),!1),this.reachedIterationLevel()){let e=this.getValueIteratedTo();if(Object.assign(this.currentIterationValue,{valueIteratedTo:e,valueIteratedFrom:this.prevValueIteratedTo,countAtValueIteratedTo:this.countAtThisValue,countAddedInThisIterationStep:this.totalCountToCurrentIndex-this.totalCountToPrevIndex,totalCountToThisValue:this.totalCountToCurrentIndex,totalValueToThisValue:this.totalValueToCurrentIndex,percentile:100*this.totalCountToCurrentIndex/this.arrayTotalCount,percentileLevelIteratedTo:this.getPercentileIteratedTo()}),this.prevValueIteratedTo=e,this.totalCountToPrevIndex=this.totalCountToCurrentIndex,this.incrementIterationLevel(),this.histogram.totalCount!==this.savedHistogramTotalRawCount)throw Error(`Concurrent Modification Exception`);return this.currentIterationValue}this.incrementSubBucket()}throw Error(`Index Out Of Bounds Exception`)}getPercentileIteratedTo(){return 100*this.totalCountToCurrentIndex/this.arrayTotalCount}getPercentileIteratedFrom(){return 100*this.totalCountToPrevIndex/this.arrayTotalCount}getValueIteratedTo(){return this.histogram.highestEquivalentValue(this.currentValueAtIndex)}exhaustedSubBuckets(){return this.currentIndex>=this.histogram.countsArrayLength}incrementSubBucket(){this.freshSubBucket=!0,this.currentIndex++,this.currentValueAtIndex=this.histogram.valueFromIndex(this.currentIndex),this.nextValueAtIndex=this.histogram.valueFromIndex(this.currentIndex+1)}}})),require_RecordedValuesIterator=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_JsHistogramIterator();e.default=class extends t.default{constructor(e){super(),this.doReset(e)}reset(){this.doReset(this.histogram)}doReset(e){super.resetIterator(e),this.visitedIndex=-1}incrementIterationLevel(){this.visitedIndex=this.currentIndex}reachedIterationLevel(){return this.histogram.getCountAtIndex(this.currentIndex)!=0&&this.visitedIndex!==this.currentIndex}}})),require_PercentileIterator=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_JsHistogramIterator(),{pow:n,floor:r,log2:i}=Math;e.default=class extends t.default{constructor(e,t){super(),this.percentileTicksPerHalfDistance=0,this.percentileLevelToIterateTo=0,this.percentileLevelToIterateFrom=0,this.reachedLastRecordedValue=!1,this.doReset(e,t)}reset(e){this.doReset(this.histogram,e)}doReset(e,t){super.resetIterator(e),this.percentileTicksPerHalfDistance=t,this.percentileLevelToIterateTo=0,this.percentileLevelToIterateFrom=0,this.reachedLastRecordedValue=!1}hasNext(){return super.hasNext()?!0:!this.reachedLastRecordedValue&&this.arrayTotalCount>0?(this.percentileLevelToIterateTo=100,this.reachedLastRecordedValue=!0,!0):!1}incrementIterationLevel(){this.percentileLevelToIterateFrom=this.percentileLevelToIterateTo;let e=this.percentileTicksPerHalfDistance*n(2,r(i(100/(100-this.percentileLevelToIterateTo)))+1);this.percentileLevelToIterateTo+=100/e}reachedIterationLevel(){return this.countAtThisValue===0?!1:100*this.totalCountToCurrentIndex/this.arrayTotalCount>=this.percentileLevelToIterateTo}getPercentileIteratedTo(){return this.percentileLevelToIterateTo}getPercentileIteratedFrom(){return this.percentileLevelToIterateFrom}}})),require_formatters=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.floatFormatter=e.keepSignificantDigits=e.integerFormatter=void 0;let t=e=>t=>t.length<e?` `.repeat(e-t.length)+t:t;e.integerFormatter=e=>{let n=t(e);return e=>n(``+e)};let{floor:n,log10:r,pow:i}=Math,a=e=>n(r(e)+1);e.keepSignificantDigits=e=>t=>{let n=a(t);return n>e?t-t%i(10,n-e):t},e.floatFormatter=(e,n)=>{let r=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:n,minimumFractionDigits:n,useGrouping:!1}),i=t(e);return e=>i(r.format(e))}})),require_ulp=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=e=>2**(Math.floor(Math.log2(e))-52)})),require_Histogram=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.toSummary=e.NO_TAG=void 0;let t=require_formatters();e.NO_TAG=`NO TAG`,e.toSummary=e=>{let{totalCount:n,maxValue:r,numberOfSignificantValueDigits:i}=e,a=(0,t.keepSignificantDigits)(i);return{p50:a(e.getValueAtPercentile(50)),p75:a(e.getValueAtPercentile(75)),p90:a(e.getValueAtPercentile(90)),p97_5:a(e.getValueAtPercentile(97.5)),p99:a(e.getValueAtPercentile(99)),p99_9:a(e.getValueAtPercentile(99.9)),p99_99:a(e.getValueAtPercentile(99.99)),p99_999:a(e.getValueAtPercentile(99.999)),max:r,totalCount:n}}})),require_JsHistogram=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=e.JsHistogram=void 0;let t=require_RecordedValuesIterator(),n=require_PercentileIterator(),r=require_formatters(),i=require_ulp(),a=require_Histogram(),{pow:o,floor:s,ceil:c,log2:l,max:u,min:d}=Math;var f=class e{incrementTotalCount(){this._totalCount++}addToTotalCount(e){this._totalCount+=e}setTotalCount(e){this._totalCount=e}get totalCount(){return this._totalCount}updatedMaxValue(e){let t=e+this.unitMagnitudeMask;this.maxValue=t}updateMinNonZeroValue(e){if(e<=this.unitMagnitudeMask)return;let t=s(e/this.lowestDiscernibleValueRounded)*this.lowestDiscernibleValueRounded;this.minNonZeroValue=t}constructor(t,n,r){if(this.autoResize=!1,this.startTimeStampMsec=2**53-1,this.endTimeStampMsec=0,this.tag=a.NO_TAG,this.maxValue=0,this.minNonZeroValue=2**53-1,this.identity=0,this.highestTrackableValue=0,this.lowestDiscernibleValue=0,this.numberOfSignificantValueDigits=0,this.bucketCount=0,this.subBucketCount=0,this.countsArrayLength=0,this.wordSizeInBytes=0,t<1)throw Error(`lowestDiscernibleValue must be >= 1`);if(n<2*t)throw Error(`highestTrackableValue must be >= 2 * lowestDiscernibleValue ( 2 * ${t} )`);if(r<0||r>5)throw Error(`numberOfSignificantValueDigits must be between 0 and 5`);this.identity=e.identityBuilder++,this.init(t,n,r)}init(e,r,i){this.lowestDiscernibleValue=e,this.highestTrackableValue=r,this.numberOfSignificantValueDigits=i;let a=2*s(o(10,i));this.unitMagnitude=s(l(e)),this.lowestDiscernibleValueRounded=o(2,this.unitMagnitude),this.unitMagnitudeMask=this.lowestDiscernibleValueRounded-1;let u=c(l(a));this.subBucketHalfCountMagnitude=(u>1?u:1)-1,this.subBucketCount=o(2,this.subBucketHalfCountMagnitude+1),this.subBucketHalfCount=this.subBucketCount/2,this.subBucketMask=(s(this.subBucketCount)-1)*o(2,this.unitMagnitude),this.establishSize(r),this.leadingZeroCountBase=53-this.unitMagnitude-this.subBucketHalfCountMagnitude-1,this.percentileIterator=new n.default(this,1),this.recordedValuesIterator=new t.default(this)}establishSize(e){this.countsArrayLength=this.determineArrayLengthNeeded(e),this.bucketCount=this.getBucketsNeededToCoverValue(e),this.highestTrackableValue=e}determineArrayLengthNeeded(e){if(e<2*this.lowestDiscernibleValue)throw Error(`highestTrackableValue (`+e+`) cannot be < (2 * lowestDiscernibleValue)`);return this.getLengthForNumberOfBuckets(this.getBucketsNeededToCoverValue(e))}getLengthForNumberOfBuckets(e){return(e+1)*(this.subBucketCount/2)}getBucketsNeededToCoverValue(e){let t=this.subBucketCount*o(2,this.unitMagnitude),n=1;for(;t<=e;){if(t>(2**53-1)/2)return n+1;t*=2,n++}return n}recordValue(e){this.recordSingleValue(e)}recordSingleValue(e){let t=this.countsArrayIndex(e);t>=this.countsArrayLength?this.handleRecordException(1,e):this.incrementCountAtIndex(t),this.updateMinAndMax(e),this.incrementTotalCount()}handleRecordException(e,t){if(!this.autoResize)throw Error(`Value `+t+` is outside of histogram covered range`);this.resize(t);var n=this.countsArrayIndex(t);this.addToCountAtIndex(n,e),this.highestTrackableValue=this.highestEquivalentValue(this.valueFromIndex(this.countsArrayLength-1))}countsArrayIndex(e){if(e<0)throw Error(`Histogram recorded value cannot be negative.`);let t=this.getBucketIndex(e),n=this.getSubBucketIndex(e,t);return this.computeCountsArrayIndex(t,n)}computeCountsArrayIndex(e,t){return(e+1)*o(2,this.subBucketHalfCountMagnitude)+(t-this.subBucketHalfCount)}getBucketIndex(e){return u(s(l(e))-this.subBucketHalfCountMagnitude-this.unitMagnitude,0)}getSubBucketIndex(e,t){return s(e/o(2,t+this.unitMagnitude))}updateMinAndMax(e){e>this.maxValue&&this.updatedMaxValue(e),e<this.minNonZeroValue&&e!==0&&this.updateMinNonZeroValue(e)}getValueAtPercentile(e){let t=d(e,100)/100*this.totalCount,n=u(c(t-(0,i.default)(t)),1),r=0;for(let t=0;t<this.countsArrayLength;t++)if(r+=this.getCountAtIndex(t),r>=n){var a=this.valueFromIndex(t);return e===0?this.lowestEquivalentValue(a):this.highestEquivalentValue(a)}return 0}valueFromIndexes(e,t){return t*o(2,e+this.unitMagnitude)}valueFromIndex(e){let t=s(e/this.subBucketHalfCount)-1,n=e%this.subBucketHalfCount+this.subBucketHalfCount;return t<0&&(n-=this.subBucketHalfCount,t=0),this.valueFromIndexes(t,n)}lowestEquivalentValue(e){let t=this.getBucketIndex(e),n=this.getSubBucketIndex(e,t);return this.valueFromIndexes(t,n)}highestEquivalentValue(e){return this.nextNonEquivalentValue(e)-1}nextNonEquivalentValue(e){return this.lowestEquivalentValue(e)+this.sizeOfEquivalentValueRange(e)}sizeOfEquivalentValueRange(e){let t=this.getBucketIndex(e),n=this.getSubBucketIndex(e,t);return o(2,this.unitMagnitude+(n>=this.subBucketCount?t+1:t))}medianEquivalentValue(e){return this.lowestEquivalentValue(e)+s(this.sizeOfEquivalentValueRange(e)/2)}get mean(){if(this.totalCount===0)return 0;this.recordedValuesIterator.reset();let e=0;for(;this.recordedValuesIterator.hasNext();){let t=this.recordedValuesIterator.next();e+=this.medianEquivalentValue(t.valueIteratedTo)*t.countAtValueIteratedTo}return e/this.totalCount}getStdDeviation(e=this.mean){if(this.totalCount===0)return 0;let t=0;for(this.recordedValuesIterator.reset();this.recordedValuesIterator.hasNext();){let n=this.recordedValuesIterator.next(),r=this.medianEquivalentValue(n.valueIteratedTo)-e;t+=r*r*n.countAddedInThisIterationStep}return Math.sqrt(t/this.totalCount)}get stdDeviation(){if(this.totalCount===0)return 0;let e=this.mean,t=0;for(this.recordedValuesIterator.reset();this.recordedValuesIterator.hasNext();){let n=this.recordedValuesIterator.next(),r=this.medianEquivalentValue(n.valueIteratedTo)-e;t+=r*r*n.countAddedInThisIterationStep}return Math.sqrt(t/this.totalCount)}outputPercentileDistribution(e=5,t=1,n=!1){let i=``;n?i+=`"Value","Percentile","TotalCount","1/(1-Percentile)"
|
|
188
|
+
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!CACHE_HIT_RE.test(t))continue;let r=cacheActivityTs(t);if(r!=null)return r}return null}var RefreshFaults=class{bySession=import_dist$1.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:failed$2(n,`read`)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,import_dist$1.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const LINE_BREAK=/\r\n|\r|\n/g,textParser=e=>ok$1(e.replace(LINE_BREAK,` `).trim());function regexParser(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?failed$2(`regex no-match`,`parse`):ok$1(n.replace(LINE_BREAK,` `))}}const jsonParser=e=>{try{return ok$1(JSON.parse(e))}catch(e){return failed$2(`JSON parse failed: ${e.message}`,`parse`)}};function mergeWithDefault(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{},...PAYLOAD_INPUTS},segments:overlayByName(t.segments,segmentDeltas(t.segments,e.segments??{})),root:mergeRoot(e.root??EMPTY_ROWS,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:overlayByName(t.presets,presetDeltas(t.presets,e.presets??{})),themeDefaults:overlayByName(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function segmentDeltas(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 presetDeltas(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 overlayByName(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const RENAMED_SEGMENTS=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 renamedHint(e){let t=RENAMED_SEGMENTS.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`;case`removed`:return` (the built-in segment "${e}" was removed: ${t.why})`}}function requireCache(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: ${CACHE_KEYS.join(`, `)})`,line:findKeyLine(e.source,t.split(`.`))}),null):validateCache(e,`${t}.cache`,n.cache)}function requireCacheSpec(e){return{required:!0,json:cacheJson(),parse:(t,n,r,i)=>requireCache(t,n,i,e)??void 0}}const CACHE_SCHEMA={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&isValidDuration(n)?{ttl:n}:reject(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${describeValue(n)}`)},watch_file:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?{watch_file:n}:reject(e,t,`cache.watch_file must be a path string, got ${describeValue(n)}`)},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:reject(e,t,`cache.depends_on must be an array of variable-name strings, got ${describeValue(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:reject(e,t,`cache.key must be a non-empty template string, got ${describeValue(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:reject(e,t,`cache.never must be the literal boolean true, got ${describeValue(n)}`)}}};function validateCache(e,t,n){return oneOfPresent(e,CACHE_SCHEMA,t,n)}function cacheJson(){return oneOfPresentJson(CACHE_SCHEMA)}const DURATION_RE=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function isValidDuration(e){return DURATION_RE.test(e)}const RETIRED_VARIABLES=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 replacement(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 retiredVariableMessage(e){let t=RETIRED_VARIABLES.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${replacement(t)}`}function retiredReadHint(e){let t=RETIRED_VARIABLES.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${replacement(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const RETIRED_INPUT_PATHS=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`]]),RETIRED_GIT_FIELDS=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 json5Of(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 retiredGitKindMessage(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`?RETIRED_GIT_FIELDS.get(e.field):void 0;if(n===void 0){let e=[...RETIRED_GIT_FIELDS.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 ${json5Of(n.declare)} under a name of your own`}function validateVariables(e,t,n){if(n===void 0)return{};if(!isPlainObject$2(n))return e.issues.push({path:t,message:`${t} must be an object, got ${describeType(n)}`,line:findKeyLine(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=taggedUnion(e,VARIABLE_SCHEMA,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function literalValueSpec(){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 ${describeType(i)}`,line:findKeyLine(e.source,t.split(`.`))});return}return i}}}function typedDefaultSpec(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return optionalTypedDefault(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const PARSE_SCHEMA={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:reject(e,t,`parse.text must be the literal boolean true, got ${describeValue(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?{regex:n}:reject(e,t,`parse.regex must be a pattern string, got ${describeValue(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:reject(e,t,`parse.json must be the literal boolean true, got ${describeValue(n)}`)}}};function parseSpec(){return{required:!1,json:oneOfPresentJson(PARSE_SCHEMA),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:findKeyLine(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:oneOfPresent(e,PARSE_SCHEMA,`${t}.parse`,r.parse)??void 0)}}function sourceDefaultSpec(){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)=>isPlainObject$2(r.parse)&&`json`in r.parse?jsonDefault(e,t,r.default):optionalStringField(e,t,r,`default`)}}function jsonDefault(e,t,n){if(n!==void 0)return isSourceDefault(n)?n:reject(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${describeValue(n)}`)??void 0}function isSourceDefault(e){return e!==null&&isJsonValue(e)}const LITERAL_FIELDS={value:literalValueSpec(),default:optionalStringSpec()};function inputPathSpec(){let e=requireStringSpec();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:RETIRED_INPUT_PATHS.get(a);return o===void 0?a:reject(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const INPUT_FIELDS={path:inputPathSpec(),type:optionalEnumSpec([`string`,`number`,`boolean`]),default:typedDefaultSpec()},ENV_FIELDS={name:requireStringSpec(),default:optionalStringSpec()},FILE_FIELDS={path:requireStringSpec(),readMode:optionalEnumSpec([`whole`,`first-line`]),parse:parseSpec(),cache:requireCacheSpec(`file`),default:sourceDefaultSpec()},SHELL_FIELDS={command:requireStringSpec(),parse:parseSpec(),cache:requireCacheSpec(`shell`),default:sourceDefaultSpec()};function noCachePolicy(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const TEMPLATE_FIELDS={template:requireStringSpec(),type:optionalEnumSpec([`string`,`number`,`boolean`]),default:typedDefaultSpec()},TEMPLATE_VAR_REMOVED=noCachePolicy(`a template variable recomputes whenever a variable it reads changes`),TIME_FIELDS={layout:requireStringSpec(),default:optionalStringSpec()},TIME_VAR_REMOVED=noCachePolicy(`a time variable reads the instant its render is drawn at`),STATE_FIELDS={key:requireStringSpec(),default:optionalStringSpec()},VARIABLE_TAG=`kind`;function arm(e,t,n={}){return{...armFacets(VARIABLE_TAG,e,t),parse:(r,i,a)=>{refuseRemoved(r,n,i,a);let o=fields(r,t,i,a);return o===null?null:{kind:e,...o}}}}const VARIABLE_SCHEMA={tag:VARIABLE_TAG,noun:`source kind`,memberNoun:`variable`,arms:{literal:arm(`literal`,LITERAL_FIELDS),input:arm(`input`,INPUT_FIELDS),env:arm(`env`,ENV_FIELDS),file:arm(`file`,FILE_FIELDS),shell:arm(`shell`,SHELL_FIELDS),template:arm(`template`,TEMPLATE_FIELDS,TEMPLATE_VAR_REMOVED),time:arm(`time`,TIME_FIELDS,TIME_VAR_REMOVED),state:arm(`state`,STATE_FIELDS)},retired:{git:retiredGitKindMessage}};function variableDeclJson(){return taggedUnionJson(VARIABLE_SCHEMA)}function variablesMapJson(){return{type:`object`,additionalProperties:variableDeclJson()}}const SETTING_NAME=/^[A-Za-z_][A-Za-z0-9_]*$/,SETTING_NAME_JSON={pattern:SETTING_NAME.source},SETTING_VALUE_JSON={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},SETTING_DECL_JSON={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`,...SETTING_NAME_JSON}}}]},default:SETTING_VALUE_JSON}},DECL_KEYS=[`label`,`domain`,`default`],RANGE_KEYS=[`min`,`max`,`step`,`atLeast`];function issue$1(e,t,n){e.issues.push({path:t,message:n,line:findKeyLine(e.source,t.split(`.`))})}function parseDomain(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 issue$1(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 issue$1(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?issue$1(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(isPlainObject$2(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!RANGE_KEYS.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}}:issue$1(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 issue$1(e,t,`domain must be "bool", a list of words, or { min, max }, got ${describeValue(n)}`)}function parseSettingDecl(e,t,n){if(!isPlainObject$2(n))return issue$1(e,t,`${t} must be { label, domain, default }, got ${describeType(n)}`);for(let r of Object.keys(n))DECL_KEYS.includes(r)||issue$1(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${DECL_KEYS.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||issue$1(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${describeValue(r)}`);let a=parseDomain(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!isSettingValue(n.default)||!inSettingDomain(o,n.default)?issue$1(e,`${t}.default`,`default must be ${describeSettingDomain(o)}, got ${describeValue(n.default)}`):o}function isSettingValue(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const IMPLIED_HINTS={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${THEME_SETTING}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function isImplied(e){return IMPLIED_SETTINGS.includes(e)}function settingsDeclSpec(){return{required:!1,json:{type:`object`,propertyNames:{...SETTING_NAME_JSON,not:{enum:[...IMPLIED_SETTINGS]}},additionalProperties:SETTING_DECL_JSON},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!isPlainObject$2(i))return issue$1(e,a,`${a} must be an object of name → { label, domain, default }, got ${describeType(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!SETTING_NAME.test(t)){issue$1(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(isImplied(t)){issue$1(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${IMPLIED_HINTS[t]}`);continue}let r=parseSettingDecl(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const RESERVED_ID_JSON=RESERVED_NAMESPACES.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function placementIdSpec(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${RESERVED_ID_JSON})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!isReservedName(i)?i:issue$1(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${RESERVED_NAMESPACES.map(e=>`"${e}"`).join(`, `)} namespaces, got ${describeValue(i)}`)}}}function placementSettingsSpec(){return{required:!1,json:{type:`object`,propertyNames:SETTING_NAME_JSON,additionalProperties:SETTING_VALUE_JSON},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!isPlainObject$2(i))return issue$1(e,a,`a placement's "settings" must be an object of setting name → value, got ${describeType(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))isSettingValue(n)?o[t]=n:issue$1(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${describeType(n)}`);return o}}}function inheritableSegmentNames(e){return new Set(Object.keys(e.segments).filter(e=>!isReservedName(e)))}function validateSegments(e,t,n){if(t===void 0)return{};if(!isPlainObject$2(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${describeType(t)}`,line:findKeyLine(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=record(e,n.has(i)?SEGMENT_DELTA_SCHEMA:SEGMENT_SCHEMA,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function joinTemplateBody(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 ${describeType(s)}`,line:findKeyLine(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 ${describeType(i)}`,line:findKeyLine(e.source,[...t.split(`.`),n])})}const TEMPLATE_BODY_JSON={anyOf:[{type:`string`},{type:`array`,items:{type:`string`}}]};function ownTemplateSpec(){return{required:!0,json:TEMPLATE_BODY_JSON,parse:(e,t,n,r)=>r[n]===void 0?reject(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${renamedHint(t.slice(9))}`)??void 0:joinTemplateBody(e,t,n,r)}}function optionalTemplateBodySpec(){return{required:!1,json:TEMPLATE_BODY_JSON,parse:(e,t,n,r)=>r[n]===void 0?void 0:joinTemplateBody(e,t,n,r)}}function partialsSpec(){return{required:!1,json:{type:`object`,additionalProperties:TEMPLATE_BODY_JSON},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;if(!isPlainObject$2(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n} must be an object, got ${describeType(i)}`,line:findKeyLine(e.source,[...t.split(`.`),n])});return}let a=Object.create(null);for(let r of Object.keys(i)){let o=joinTemplateBody(e,`${t}.${n}`,r,i);o!==void 0&&(a[r]=o)}return a}}}function widthSpec(){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 ${describeValue(i)}`,line:findKeyLine(e.source,[...t.split(`.`),n])})}}}}function varsSpec(){return{required:!1,json:variablesMapJson(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return validateVariables(e,`${t}.${n}`,i)}}}const SEGMENT_FIELDS={template:ownTemplateSpec(),description:optionalStringSpec(),group:optionalEnumSpec(SEGMENT_GROUPS),width:widthSpec(),justify:optionalEnumSpec(JUSTIFY_MODES),truncate:optionalEnumSpec(TRUNCATE_MODES),bg:optionalStringSpec(),fg:optionalStringSpec(),when:optionalStringSpec(),palette:paletteSpec(),vars:varsSpec(),settings:settingsDeclSpec(),missingData:optionalEnumSpec(MISSING_DATA),partials:partialsSpec()},SEGMENT_SCHEMA={noun:`segment key`,fields:SEGMENT_FIELDS},SEGMENT_DELTA_SCHEMA={noun:`segment key`,fields:{...SEGMENT_FIELDS,template:optionalTemplateBodySpec()}},SEGMENT_DEF_NAME=`Segment`,SEGMENT_DELTA_DEF_NAME=`SegmentDelta`,SEGMENT_REF=`#/definitions/${SEGMENT_DEF_NAME}`,SEGMENT_DELTA_REF=`#/definitions/${SEGMENT_DELTA_DEF_NAME}`;function validateHelpers(e,t){if(t===void 0)return{};if(!isPlainObject$2(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${describeType(t)}`,line:findKeyLine(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 ${describeValue(i)}`,line:findKeyLine(e.source,[`helpers`,r])});continue}n[r]=i}return n}function validateActions(e,t,n){if(t===void 0)return{};if(!isPlainObject$2(t))return issue(e,`actions`,`actions must be an object, got ${describeType(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=validateActionDecl(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function issue(e,t,n){e.issues.push({path:t,message:n,line:findKeyLine(e.source,t.split(`.`))})}function validateActionDecl(e,t,n,r){if(!isPlainObject$2(n))return issue(e,t,`${t} must be an action object, got ${describeType(n)}`),null;if(`persistWhen`in n)return issue(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=ACTION_KEYS.filter(e=>e in n);if(i.length!==1)return issue(e,t,`action must declare exactly one of: ${ACTION_KEYS.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null;let a=i[0],{layer:o,...s}=n,c=LAYER_CHOICES[a];if(o===void 0)return actionArms(r)[a](e,t,s);if(c===void 0)return issue(e,`${t}.layer`,`a ${a} action writes no config, so it names no layer`),null;if(!c.includes(o))return issue(e,`${t}.layer`,`layer must be one of ${c.join(`, `)}, got ${describeValue(o)}`),null;let l=actionArms(r)[a](e,t,s);return l===null?null:{...l,layer:o}}function actionHomeOf(e){return e===`<default>`?{dir:null}:path.isAbsolute(e)?{dir:path.dirname(e)}:{text:e}}const actionArms=e=>({set:(e,t,n)=>valueSourceAction(e,t,n,`set`,SET_ARMS),persist:(e,t,n)=>valueSourceAction(e,t,n,`persist`,PERSIST_ARMS),copy:templateArm(`copy`),open:templateArm(`open`),reset:resetArm,undo:markerArm(`undo`),redo:markerArm(`redo`),back:markerArm(`back`),rewind:markerArm(`rewind`),save:markerArm(`save`),preset:presetArm,themeDefault:themeDefaultArm,doctor:doctorArm,slash:slashArm,run:runArm(e),do:doArm});function templateArm(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&issue(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=requireString(t,n,r,e);return i===null?null:{[e]:i}}}function resetArm(e,t,n){for(let r of Object.keys(n))r!==`reset`&&issue(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=slashFreeString(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 MARKER_SUBJECT={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 markerArm(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&issue(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(issue(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${MARKER_SUBJECT[e]}), got ${describeValue(r[e])}`),null)}}function presetArm(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||issue(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return issue(e,`${t}.preset`,`preset must be "save" or "delete", got ${describeValue(r)}`),null;if(r===`save`)return{preset:`save`};let a=requireString(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function themeDefaultArm(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&issue(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(issue(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${describeValue(n.themeDefault)}`),null)}const DOCTOR_KEYS={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function doctorArm(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(DOCTOR_KEYS,r),a=i?DOCTOR_KEYS[r]:[...new Set(Object.values(DOCTOR_KEYS).flat())];for(let r of Object.keys(n))a.includes(r)||issue(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return issue(e,`${t}.doctor`,`doctor must be ${Object.keys(DOCTOR_KEYS).map(e=>`"${e}"`).join(`, `)}, got ${describeValue(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?MARKED_CHECKS:CHECKS;if(typeof o!=`string`||!s.some(e=>e.name===o))return issue(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${describeValue(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return GLYPH_MARKS.includes(c)?{doctor:`mark`,check:o,mark:c}:(issue(e,`${t}.mark`,`doctor mark must be ${GLYPH_MARKS.map(e=>`"${e}"`).join(` or `)}, got ${describeValue(c)}`),null)}function slashArm(e,t,n){for(let r of Object.keys(n))r!==`slash`&&issue(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=parseSlashLine(n.slash);return r.kind===`refused`?(issue(e,`${t}.slash`,r.reason),null):{slash:r.line}}const RUN_KEYS=[`run`,`env`,`refreshes`],ENV_NAME=/^[A-Za-z_][A-Za-z0-9_]*$/;function runArm(e){return(t,n,r)=>{for(let e of Object.keys(r))RUN_KEYS.includes(e)||issue(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${RUN_KEYS.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&issue(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${describeValue(a)}`);let o=r.env??{};(!isPlainObject$2(o)||Object.entries(o).some(([e,t])=>!ENV_NAME.test(e)||typeof t!=`string`))&&issue(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${describeValue(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&issue(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${describeValue(s)}`),`dir`in e||issue(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}}}const RUN_ARM_JSON={type:`object`,properties:{run:{type:`array`,items:{type:`string`},minItems:1},env:{type:`object`,propertyNames:{pattern:ENV_NAME.source},additionalProperties:{type:`string`}},refreshes:{type:`array`,items:{type:`string`,minLength:1}}},required:[`run`],additionalProperties:!1};function doArm(e,t,n){for(let r of Object.keys(n))r!==`do`&&issue(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===``)?(issue(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 ${describeValue(r)}`),null):{do:r}}function slashFreeString(e,t,n,r,i,a){let o=requireString(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(issue(e,s,i),null):o.includes(`/`)?(issue(e,s,a(o)),null):o}const DISCRIMINATOR_NOUN={set:`the SessionState key to write`,persist:`the config globals field to write`};function validateDiscriminatorKey(e,t,n,r){let i=DISCRIMINATOR_NOUN[r],a=slashFreeString(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 wireName(e){return e===`set`?`set-state`:`set-config`}const TO_FIELDS_SET={to:setLiteralSpec(`set`)},TO_FIELDS_PERSIST={to:setLiteralSpec(`persist`)},FROM_FIELDS_SET={from:fromSpec(`set`)},FROM_FIELDS_PERSIST={from:fromSpec(`persist`)},BOUNDED_FIELDS={min:requireIntSpec(),max:requireIntSpec(),by:requireIntSpec()},INT_FIELDS={int:intMarkerSpec()},CYCLE_FIELDS_SET={cycle:cycleSpec(`set`)},CYCLE_FIELDS_PERSIST={cycle:cycleSpec(`persist`)},REMOVE_SEGMENT_FIELDS={removeSegment:layoutNameSpec(`removeSegment`)},INSERT_SEGMENT_FIELDS={insertSegment:layoutNameSpec(`insertSegment`),anchor:layoutNameSpec(`anchor`),relation:relationSpec()},INSERT_SEGMENT_FROM_FIELDS={insertSegmentFrom:fromSpec(`persist`),anchor:layoutNameSpec(`anchor`),relation:relationSpec()},minLessThanMax={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},byNonZero={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function valueSourceArm(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>fields(e,t,n,r),c=objectJson(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?refine(s,...n):s}}const SET_ARMS=[valueSourceArm(`set`,TO_FIELDS_SET),valueSourceArm(`set`,FROM_FIELDS_SET),valueSourceArm(`set`,BOUNDED_FIELDS,[minLessThanMax,byNonZero]),valueSourceArm(`set`,INT_FIELDS),valueSourceArm(`set`,CYCLE_FIELDS_SET)],PERSIST_ARMS=[valueSourceArm(`persist`,TO_FIELDS_PERSIST),valueSourceArm(`persist`,FROM_FIELDS_PERSIST),valueSourceArm(`persist`,BOUNDED_FIELDS,[minLessThanMax,byNonZero]),valueSourceArm(`persist`,CYCLE_FIELDS_PERSIST),valueSourceArm(`persist`,REMOVE_SEGMENT_FIELDS),valueSourceArm(`persist`,INSERT_SEGMENT_FIELDS,[],[`insertSegment`]),valueSourceArm(`persist`,INSERT_SEGMENT_FROM_FIELDS,[],[`insertSegmentFrom`])];function valueSourceClauses(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 VALUE_SOURCE_MESSAGE(e){let t=valueSourceClauses(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 valueSourceAction(e,t,n,r,i){let a=validateDiscriminatorKey(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return issue(e,t,`${VALUE_SOURCE_MESSAGE(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)||issue(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 setLiteralSpec(e){let t=wireName(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>slashFreeString(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 fromSpec(e){let t=wireName(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===``){issue(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){issue(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===``)){issue(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){issue(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){issue(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}issue(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${describeValue(o)}`)}}}function cycleSpec(e){let t=wireName(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`)){issue(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${describeType(o)}`);return}let c=o;if(c.length<2){issue(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){issue(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){issue(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){issue(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function intMarkerSpec(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){issue(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${describeValue(r[n])}`);return}return!0}}}function layoutNameSpec(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=requireString(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){issue(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){issue(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 relationSpec(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){issue(e,`${t}.${n}`,`relation must be "before" or "after", got ${describeValue(i)}`);return}return i}}}function requireIntSpec(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){issue(e,`${t}.${n}`,`${n} must be an integer, got ${describeValue(i)}`);return}return i}}}function droppedPluginNotice(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const DEFINITION_KEYS=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),DEFINITION_FILE=`plugin.json5`,PLUGIN_NAME=/^[a-z][a-z0-9_]*$/;function pluginDefinition(e,t){let n=path.basename(path.dirname(e));return PLUGIN_NAME.test(n)?{path:e,scope:t,name:n}:{path:e,scope:t,name:void 0}}function pluginDataVar(e){return`${e}.data`}const STORAGE_FOLDER=`session`;function sessionFileName(e){return`${e}.json`}function attempt(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:reasonOf(e)}}}function reasonOf(e){return e instanceof ConfigError?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 listedPlugins(e,t,n,r){return e.map(e=>pluginDefinition(resolveUserPath(path.dirname(t),e,r),n))}function applyPlugins(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=n.path,o=n.name===void 0?void 0:pluginNs(n),s=(t,r)=>{let i=new Map(e.rendering);return o!==void 0&&r!==e.config&&i.delete(o),{...e,config:r,rendering:i,dropped:[...e.dropped,{...n,reason:t}]}};if(path.basename(a)!==`plugin.json5`){let t=`a plugin is a folder holding its ${DEFINITION_FILE}, and the folder's name is the plugin's: move this file to <dir>/<name>/${DEFINITION_FILE} and list that`;return s(t,o===void 0?e.config:tombstone(withoutPlugin(e.config,o),o,{...n,reason:t}))}if(n.name===void 0||o===void 0)return s(`its folder "${path.basename(path.dirname(a))}" is not a plugin name (one matching ${PLUGIN_NAME}: it prefixes every name the plugin declares)`,e.config);let c=i.get(o);if(c!==void 0)return s(`plugin "${n.name}" is already listed, from ${c}`,e.config);i.set(o,a);let l=withoutPlugin(e.config,o),u=attempt(()=>{let i=fs.readFileSync(a,`utf-8`),s=mergeWithDefault(fragmentOf(a,n,{source:i,json:import_lib.default.parse(i)},t),l);return requireOneSourcePerFile(a,o,s),r(s,o,l!==e.config),s});if(u.ok)return{...e,config:u.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[o,n]])};let d={...n,reason:u.reason};return s(u.reason,tombstone(l,o,d))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function withoutPlugin(e,t){let n=ownedBy(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 tombstone(e,t,n){return{...e,variables:{...e.variables,[t]:{kind:`dropped`,reason:droppedPluginNotice(n),definition:n.path}}}}function tombstonesOf(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})=>ownedBy(t)(e))}function dropsOwning(e,t){let n=tombstonesOf(e.config),r=[...e.rendering.keys()].map(ownedBy),i=[...t,...e.dropped].filter(e=>e.name===void 0);return e=>{let t=scopeOf$1(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:droppedPluginNotice(e)})):[{definition:a.definition,notice:a.notice}]}}function withDroppedPlacements(e,t,n){let r=presetNames(e.presets).flatMap(t=>[...walkNodes(presetRoot(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,standIn(e,t.map(e=>e.notice),r.filter(t=>t.name===e))])),o=tombstonesOf(e),s=Object.values(e.variables).some(e=>e.kind===`dropped`),c=s?Object.values(e.segments).flatMap(e=>[...SEGMENT_TEMPLATE_FIELDS.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=>templateActionRefs(t,e.helpers).map(e=>e.name)),...l],e.actions),f=u(c.flatMap(t=>[...templateHelperCalls(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 standIn(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,settingFor(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function settingFor(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 fragmentOf(e,t,{source:n,json:r},{checkout:i,home:a}){let o=pluginNs(t),s=[],c=()=>{throw new ConfigError(e,s)};if(!isPlainObject$2(r))return s.push({path:``,message:`a plugin definition must be an object, got ${describeType(r)}`}),c();for(let t of Object.keys(r))DEFINITION_KEYS.has(t)||s.push({path:t,message:t===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${path.basename(path.dirname(e))}") — remove "plugin"`:`a plugin definition may not declare "${t}". Expected only: ${[...DEFINITION_KEYS].join(`, `)}`});let l=r.data===void 0?void 0:dataPathOf(r.data,e,i,a,s),u=r.sources===void 0?{}:sourcesOf$1(r.sources,e,s);if(s.length>0)return c();let d={source:n,issues:s,allowedPalettes:new Set(listResolvablePaletteNames()),groups:[],unplaced:[],inherited:[]},f=l===void 0?{}:validateVariables(d,`data`,{[pluginDataVar(o)]:{kind:`file`,path:l,parse:{json:!0},cache:{watch_file:l},default:{}}}),p=validateVariables(d,`variables`,r.variables);for(let[e,t]of[[`variables`,Object.keys(p)],[`sources`,Object.keys(u)]])t.includes(`data`)&&s.push({path:`${e}.data`,message:`"data" names the plugin's data file (.${pluginDataVar(o)}), 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(p,e)&&s.push({path:`sources.${e}`,message:`source "${e}" and variable "${e}" are one name (.${o}.${e}): give one of them another name`});let m={variables:{...f,...prefixed(o,u),...prefixed(o,Object.fromEntries(Object.entries(p).map(([e,t])=>[e,stateKeyUnder(o,t)])))},segments:prefixed(o,stateKeysUnder(o,validateSegments(d,r.segments,new Set))),helpers:prefixed(o,validateHelpers(d,r.helpers)),actions:prefixed(o,setKeysUnder(o,validateActions(d,r.actions,{dir:fs.realpathSync(path.dirname(e))})))};s.push(...wrongScopeRefs(m,t));let h=boundToSelf(o,m);for(let[e,t]of fragmentTemplates(h))try{SYNTAX_ENGINE.parse(t)}catch(t){s.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return s.length>0&&c(),h}function boundToSelf(e,t){let n=t=>bindSelf(t,SELF,e),r=t=>ownedBy(`self`)(t)?`${e}${t.slice(SELF.length)}`:t,i=(e,t)=>Object.fromEntries(Object.entries(e??{}).map(([e,n])=>[e,t(n)]));return{...t,variables:i(t.variables,e=>selfDepends(mapVariableTemplates(e,n),r)),segments:i(t.segments,e=>({...e,...Object.fromEntries(SEGMENT_TEMPLATE_FIELDS.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=>selfDepends(mapVariableTemplates(e,n),r))}})),helpers:i(t.helpers,n),actions:i(t.actions,e=>mapActionNames(mapActionTemplates(e,n),r))}}function selfDepends(e,t){return hasCacheField(e)&&`depends_on`in e.cache?{...e,cache:{depends_on:e.cache.depends_on.map(t)}}:e}function mapActionNames(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 SEGMENT_TEMPLATE_FIELDS=[`template`,`bg`,`fg`,`when`];function wrongScopeRefs(e,t){let n=e.helpers??{},r=PLUGIN_SCOPES.filter(e=>e!==t.scope).map(e=>({scope:e,ns:pluginNs({scope:e,name:t.name})})),i=new Map,a=(e,n,a)=>{let o=r.find(({ns:e})=>ownedBy(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 ${pluginNs(t)}: a plugin names itself without its scope — write ${s}${SELF}${n.slice(o.ns.length)}`})},o=[...[...fragmentTemplates(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 templateReads(t,n))i===null&&a(e,r,!0);for(let{name:r,via:i}of templateActionRefs(t,n))i===null&&a(e,r,!1);for(let n of templateHelperCalls(t,{}))a(e,n,!1)}for(let[t,n]of Object.entries(e.actions??{}))mapActionNames(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(hasCacheField(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*fragmentTemplates(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of variableTemplates(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of SEGMENT_TEMPLATE_FIELDS){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 variableTemplates(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 actionTemplates(n))yield[`actions.${t}.${e}`,r]}function prefixed(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,n]))}function keyUnder(e,t){return`${e}.${t}`}function stateKeyUnder(e,t){return t.kind===`state`?{...t,key:keyUnder(e,t.key)}:t}function stateKeysUnder(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,stateKeyUnder(e,n)]))}]))}function setKeysUnder(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:keyUnder(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>keyUnder(e,t))}:n]))}const SOURCE_NAME=PLUGIN_NAME,BUILT_SOURCE={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function sourcesOf$1(e,t,n){if(!isPlainObject$2(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${describeType(e)}`}),{};let r=path.join(fs.realpathSync(path.dirname(t)),STORAGE_FOLDER),i=JSON.stringify(BUILT_SOURCE),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!SOURCE_NAME.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${SOURCE_NAME}: it is the last segment of .<scope>.<plugin>.${t})`});continue}let s=unbuilt(o,BUILT_SOURCE,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 requireOneSourcePerFile(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=sourceFileOf(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=ownedBy(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 ConfigError(e,a)}function sourceFileOf(e){return path.join(e.storage,sessionFileName(`<session id>`))}function unbuilt(e,t,n){return!isPlainObject$2(t)||!isPlainObject$2(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)?unbuilt(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function dataPathOf(e,t,n,r,i){if(typeof e==`string`&&e!==``)return resolveUserPath(path.dirname(t),e,r);if(isPlainObject$2(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(path.isAbsolute(t)||t.startsWith(`~`)||path.normalize(t).split(path.sep)[0]===`..`){i.push({path:`data.checkout`,message:`data.checkout "${t}" must be a path inside the checkout, relative to its root (like ".lit/statusline.json"): no absolute path, "~" or ".."`});return}if(n===null){i.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return path.resolve(n.root,t)}if(isPlainObject$2(e)&&`project`in e){i.push({path:`data.project`,message:`data: { project } is now data: { checkout }: the same path, relative to the root of the git checkout the session works in (a linked worktree is its own checkout)`});return}i.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { checkout: "<path>" } relative to the root of the session's checkout`})}const DAY_MS=1440*60*1e3,STORAGE_FILE_MAX_AGE_MS=30*DAY_MS,STORAGE_SWEEP_EVERY_MS=DAY_MS,MAX_ENTRIES$1=256,fileName=e=>sessionFileName(e),fileOf=e=>path.join(e.folder,fileName(e.sessionId)),keyString=e=>JSON.stringify([e.folder,e.generation]);function madeOnce(e){try{fs.mkdirSync(e)}catch(t){let n;try{n=fs.statSync(e)}catch{throw t}if(!n.isDirectory())throw Error(`${e} is not a folder`)}}const current=(e,t)=>e.health.kind===`watching`&&t.kind===`found`&&t.identity!==`gone`&&e.identity!==`gone`&&sameIdentity(t.identity,e.identity);var ManagedStorage=class{sessions;watched=new Map;holds=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;generations=0;watchers;logger;identityOf;fileEvents;clock;unsubscribe;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??statIdentity,this.fileEvents=e.fileEvents,this.clock=e.clock,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new KeyedSource({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.folder,e.sessionId]),fields:e=>`file=${valueOf$1(fileOf(e))}`,read:e=>this.read(e),every:()=>null,watch:NO_WATCH,maxEntries:MAX_ENTRIES$1,lines:REFRESH_TRIGGERS,logger:e.logger,ledger:e.ledger??new RefreshLedger(e.logger),clock:e.clock})}hold(e,t){this.holds.set(e,t);for(let e of new Set(t)){let t=this.watched.get(e),n=this.found(e);if(t!==void 0&¤t(t,n))continue;let r=this.generations++;t!==void 0&&this.logger(`info`,`plugin storage generation folder=${valueOf$1(e)} generation=${r}`),this.opened({folder:e,generation:r},n),t!==void 0&&this.closed(t),this.sessions.changed(t=>t.folder===e)}this.closeUnheld()}release(e){this.holds.delete(e),this.closeUnheld()}declare(e,t,n){return this.sessions.declare(e,{folder:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({folder:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost}}close(){this.unsubscribe(),this.sessions.close(),this.holds.clear(),this.closeUnheld()}found(e){try{return madeOnce(e),{kind:`found`,identity:this.identityOf(e)}}catch(e){return{kind:`unusable`,reason:`could not be created or read: ${e.message}`}}}closeUnheld(){let e=new Set([...this.holds.values()].flat());for(let[t,n]of[...this.watched])e.has(t)||this.closed(n)}opened(e,t){let n={key:e,identity:t.kind===`found`?t.identity:`gone`,handle:this.watchers.acquire(`plugin-storage:${keyString(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(n,e)),stopSweep:this.clock.every(STORAGE_SWEEP_EVERY_MS,()=>void this.sweep(e),{unref:!0}),health:{kind:`watching`}};this.watched.set(e.folder,n),t.kind===`unusable`&&this.faulted(n,`unusable`,t.reason);for(let e of n.handle.deaf)this.faulted(n,`refused`,e.reason);return this.sweep(e),n}closed(e){this.watched.get(e.key.folder)===e&&this.watched.delete(e.key.folder),e.health={kind:`closed`},e.stopSweep(),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>e.folder===n.folder;switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.includes(path.join(n.folder,path.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.includes(fileOf(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}=e,i;try{i=this.identityOf(r.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let a=e.identity;if(i!==`gone`&&a!==`gone`&&sameIdentity(i,a)){t();return}e.health={kind:`lost`},this.lost++,this.logger(`info`,`plugin storage lost folder=${valueOf$1(r.folder)} generation=${r.generation} now=${i===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>e.folder===r.folder)}faulted(e,t,n){let{key:r}=e;e.health.kind===`watching`&&(e.health={kind:`faulted`,reason:n},this.faultCounts[t]++,this.logger(`warn`,`plugin storage fault folder=${valueOf$1(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>e.folder===r.folder))}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(e);if(t===void 0)return null;let{health:n}=t;switch(n.kind){case`faulted`:return`cannot refresh: ${e} ${n.reason}; reload the config or restart the daemon`;case`watching`:case`lost`:{let t=stallReason(this.fileEvents.delivery());return t===null?null:`cannot refresh: ${e}: ${t}`}case`closed`:return null}}async read(e){let t=this.standing(e.folder);if(t!==null)return failed$2(t,`read`);let n=fileOf(e),r;try{r=await fs.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?ABSENT$2:failed$2(`${n}: ${t.message}`,`read`)}if(r.trim()===``)return ABSENT$2;let i=jsonParser(r);return i.kind===`failed`?failed$2(`${n}: ${i.reason}`,i.failedAt):i}async sweep(e){let t=this.clock.monotonic(),n=this.clock.now()-STORAGE_FILE_MAX_AGE_MS,r=0,i=0,a=()=>`plugin storage sweep folder=${valueOf$1(e.folder)} scanned=${r} removed=${i} took=${elapsedMs(this.clock,t)}ms`;try{let t=await fs.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=path.join(e.folder,a.name);try{let{mtimeMs:r}=await fs.promises.stat(t),o=this.sessions.isHeld(t=>t.folder===e.folder&&fileName(t.sessionId)===a.name);if(r>=n||o)continue;await fs.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)}`)}}};const TRANSCRIPT_PERIOD={okMs:1e4,failedMs:1e4},MAX_UNHELD=16,keyOfFollowed=({session:e,transcript:t,settings:n})=>[e,t,n].join(`\0`);var TranscriptLanes=class{source;constructor(e){this.deps=e,this.source=new KeyedSource({name:`transcript`,scope:`session`,keyOf:keyOfFollowed,fields:({session:e})=>`sid=${valueOf$1(e)}`,read:(e,t,n)=>this.read(e,n),every:()=>e.every??TRANSCRIPT_PERIOD,watch:(e,t)=>this.watch(e,t),maxEntries:MAX_UNHELD,lines:[`first`,`change`,`supersede`],logger:e.logger,ledger:e.ledger,clock:e.clock})}declare(e,t){return this.source.declare(e,t)}stats(){return this.source.stats()}close(){this.source.close()}watch(e,t){let{transcript:n,settings:r}=e,i=this.deps.watchers.acquire(`transcript-lanes:${keyOfFollowed(e)}`,{dirs:[{path:dirname(n),filenames:[basename(n)]},{path:dirname(r),filenames:[basename(r)]}]},t);return()=>i.release()}async read({session:e,transcript:t,settings:n},r){let{owners:i,clock:a,logger:o}=this.deps,s=i.usageStore.refresh(e,t,r),c={session:()=>s.usage(),context:()=>i.contextProvider.refresh(e,t,r),metrics:()=>i.metricsProvider.refresh(e,t,r),activity:()=>i.activityProvider.refresh(e,t,r),cache:()=>i.cacheExpiry.refresh(e,t,r),speed:()=>s.speed(a.now()),autocompact:async()=>i.autoCompact.window(n,r)};return await Promise.all(REFRESH_LANES.map(async t=>{let n=null;try{await c[t]()}catch(e){o(`error`,`${t} lane threw: ${inspect(e)}`),n=`${t}: ${String(e)}`}i.faults.refreshed(e,t,n)})),ok$1(null)}};function createPayloadProviders(e){let{launcher:t,clock:n,logger:r,ledger:i}=e,a={usageStore:new SessionUsageStore({host:e.host,clock:n,logger:r,ledger:i}),contextProvider:new ContextProvider({clock:n,logger:r,ledger:i}),metricsProvider:new MetricsProvider({clock:n,logger:r,ledger:i}),activityProvider:new ActivityProvider({clock:n,logger:r,ledger:i}),autoCompact:new AutoCompactProvider(n,r,i),cacheExpiry:new CacheExpiryProvider(n,r,i),faults:new RefreshFaults},o={hostService:new HostService({clock:n,logger:r,ledger:i}),gitProvider:new GitDataProvider({inner:new GitService(t),watchers:e.watchers,clock:n,logger:r,ledger:i}),tmuxService:new TmuxService({launcher:t,clock:n,logger:r,ledger:i}),transcriptLanes:new TranscriptLanes({owners:a,watchers:e.watchers,clock:n,logger:r,ledger:i}),managedStorage:new ManagedStorage({watchers:e.watchers,fileEvents:e.fileEvents,clock:n,logger:r,ledger:i})};return{...a,...o,home:e.host.home,sourceRuns:e.sourceRuns,log:e.logger,closes:[[`gitProvider close`,()=>o.gitProvider.close()],[`transcriptLanes close`,()=>o.transcriptLanes.close()],[`usageStore close`,()=>a.usageStore.close()],[`tmuxService close`,()=>o.tmuxService.close()],[`hostService close`,()=>o.hostService.close()],[`managedStorage close`,()=>o.managedStorage.close()]]}}async function runTeardown(e,t){let n=[];for(let[r,i]of e)try{await i()}catch(e){t(`warn`,`${r} failed: ${inspect(e)}`),n.push(r)}return n}var require_ByteBuffer=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let{pow:t,floor:n}=Math,r=t(2,32);e.default=class e{static allocate(t=16){return new e(new Uint8Array(t))}constructor(e){this.position=0,this.data=e,this.int32ArrayForConvert=new Uint32Array(1),this.int8ArrayForConvert=new Uint8Array(this.int32ArrayForConvert.buffer)}put(e){if(this.position===this.data.length){let e=this.data;this.data=new Uint8Array(this.data.length*2),this.data.set(e)}this.data[this.position]=e,this.position++}putInt32(e){if(this.data.length-this.position<4){let e=this.data;this.data=new Uint8Array(this.data.length*2+4),this.data.set(e)}this.int32ArrayForConvert[0]=e,this.data.set(this.int8ArrayForConvert.reverse(),this.position),this.position+=4}putInt64(e){this.putInt32(n(e/r)),this.putInt32(e)}putArray(e){if(this.data.length-this.position<e.byteLength){let t=this.data;this.data=new Uint8Array(this.position+e.byteLength),this.data.set(t)}this.data.set(e,this.position),this.position+=e.byteLength}get(){let e=this.data[this.position];return this.position++,e}getInt32(){this.int8ArrayForConvert.set(this.data.slice(this.position,this.position+4).reverse());let e=this.int32ArrayForConvert[0];return this.position+=4,e}getInt64(){let e=this.getInt32(),t=this.getInt32();return e*r+t}resetPosition(){this.position=0}}})),require_HistogramIterationValue=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=class{constructor(){this.reset()}reset(){this.valueIteratedTo=0,this.valueIteratedFrom=0,this.countAtValueIteratedTo=0,this.countAddedInThisIterationStep=0,this.totalCountToThisValue=0,this.totalValueToThisValue=0,this.percentile=0,this.percentileLevelIteratedTo=0}}})),require_JsHistogramIterator=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_HistogramIterationValue();e.default=class{constructor(){this.currentIterationValue=new t.default}resetIterator(e){this.histogram=e,this.savedHistogramTotalRawCount=e.totalCount,this.arrayTotalCount=e.totalCount,this.currentIndex=0,this.currentValueAtIndex=0,this.nextValueAtIndex=2**e.unitMagnitude,this.prevValueIteratedTo=0,this.totalCountToPrevIndex=0,this.totalCountToCurrentIndex=0,this.totalValueToCurrentIndex=0,this.countAtThisValue=0,this.freshSubBucket=!0,this.currentIterationValue.reset()}hasNext(){if(this.histogram.totalCount!==this.savedHistogramTotalRawCount)throw`Concurrent Modification Exception`;return this.totalCountToCurrentIndex<this.arrayTotalCount}next(){for(;!this.exhaustedSubBuckets();){if(this.countAtThisValue=this.histogram.getCountAtIndex(this.currentIndex),this.freshSubBucket&&=(this.totalCountToCurrentIndex+=this.countAtThisValue,this.totalValueToCurrentIndex+=this.countAtThisValue*this.histogram.highestEquivalentValue(this.currentValueAtIndex),!1),this.reachedIterationLevel()){let e=this.getValueIteratedTo();if(Object.assign(this.currentIterationValue,{valueIteratedTo:e,valueIteratedFrom:this.prevValueIteratedTo,countAtValueIteratedTo:this.countAtThisValue,countAddedInThisIterationStep:this.totalCountToCurrentIndex-this.totalCountToPrevIndex,totalCountToThisValue:this.totalCountToCurrentIndex,totalValueToThisValue:this.totalValueToCurrentIndex,percentile:100*this.totalCountToCurrentIndex/this.arrayTotalCount,percentileLevelIteratedTo:this.getPercentileIteratedTo()}),this.prevValueIteratedTo=e,this.totalCountToPrevIndex=this.totalCountToCurrentIndex,this.incrementIterationLevel(),this.histogram.totalCount!==this.savedHistogramTotalRawCount)throw Error(`Concurrent Modification Exception`);return this.currentIterationValue}this.incrementSubBucket()}throw Error(`Index Out Of Bounds Exception`)}getPercentileIteratedTo(){return 100*this.totalCountToCurrentIndex/this.arrayTotalCount}getPercentileIteratedFrom(){return 100*this.totalCountToPrevIndex/this.arrayTotalCount}getValueIteratedTo(){return this.histogram.highestEquivalentValue(this.currentValueAtIndex)}exhaustedSubBuckets(){return this.currentIndex>=this.histogram.countsArrayLength}incrementSubBucket(){this.freshSubBucket=!0,this.currentIndex++,this.currentValueAtIndex=this.histogram.valueFromIndex(this.currentIndex),this.nextValueAtIndex=this.histogram.valueFromIndex(this.currentIndex+1)}}})),require_RecordedValuesIterator=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_JsHistogramIterator();e.default=class extends t.default{constructor(e){super(),this.doReset(e)}reset(){this.doReset(this.histogram)}doReset(e){super.resetIterator(e),this.visitedIndex=-1}incrementIterationLevel(){this.visitedIndex=this.currentIndex}reachedIterationLevel(){return this.histogram.getCountAtIndex(this.currentIndex)!=0&&this.visitedIndex!==this.currentIndex}}})),require_PercentileIterator=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=require_JsHistogramIterator(),{pow:n,floor:r,log2:i}=Math;e.default=class extends t.default{constructor(e,t){super(),this.percentileTicksPerHalfDistance=0,this.percentileLevelToIterateTo=0,this.percentileLevelToIterateFrom=0,this.reachedLastRecordedValue=!1,this.doReset(e,t)}reset(e){this.doReset(this.histogram,e)}doReset(e,t){super.resetIterator(e),this.percentileTicksPerHalfDistance=t,this.percentileLevelToIterateTo=0,this.percentileLevelToIterateFrom=0,this.reachedLastRecordedValue=!1}hasNext(){return super.hasNext()?!0:!this.reachedLastRecordedValue&&this.arrayTotalCount>0?(this.percentileLevelToIterateTo=100,this.reachedLastRecordedValue=!0,!0):!1}incrementIterationLevel(){this.percentileLevelToIterateFrom=this.percentileLevelToIterateTo;let e=this.percentileTicksPerHalfDistance*n(2,r(i(100/(100-this.percentileLevelToIterateTo)))+1);this.percentileLevelToIterateTo+=100/e}reachedIterationLevel(){return this.countAtThisValue===0?!1:100*this.totalCountToCurrentIndex/this.arrayTotalCount>=this.percentileLevelToIterateTo}getPercentileIteratedTo(){return this.percentileLevelToIterateTo}getPercentileIteratedFrom(){return this.percentileLevelToIterateFrom}}})),require_formatters=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.floatFormatter=e.keepSignificantDigits=e.integerFormatter=void 0;let t=e=>t=>t.length<e?` `.repeat(e-t.length)+t:t;e.integerFormatter=e=>{let n=t(e);return e=>n(``+e)};let{floor:n,log10:r,pow:i}=Math,a=e=>n(r(e)+1);e.keepSignificantDigits=e=>t=>{let n=a(t);return n>e?t-t%i(10,n-e):t},e.floatFormatter=(e,n)=>{let r=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:n,minimumFractionDigits:n,useGrouping:!1}),i=t(e);return e=>i(r.format(e))}})),require_ulp=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=e=>2**(Math.floor(Math.log2(e))-52)})),require_Histogram=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.toSummary=e.NO_TAG=void 0;let t=require_formatters();e.NO_TAG=`NO TAG`,e.toSummary=e=>{let{totalCount:n,maxValue:r,numberOfSignificantValueDigits:i}=e,a=(0,t.keepSignificantDigits)(i);return{p50:a(e.getValueAtPercentile(50)),p75:a(e.getValueAtPercentile(75)),p90:a(e.getValueAtPercentile(90)),p97_5:a(e.getValueAtPercentile(97.5)),p99:a(e.getValueAtPercentile(99)),p99_9:a(e.getValueAtPercentile(99.9)),p99_99:a(e.getValueAtPercentile(99.99)),p99_999:a(e.getValueAtPercentile(99.999)),max:r,totalCount:n}}})),require_JsHistogram=__commonJSMin((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.default=e.JsHistogram=void 0;let t=require_RecordedValuesIterator(),n=require_PercentileIterator(),r=require_formatters(),i=require_ulp(),a=require_Histogram(),{pow:o,floor:s,ceil:c,log2:l,max:u,min:d}=Math;var f=class e{incrementTotalCount(){this._totalCount++}addToTotalCount(e){this._totalCount+=e}setTotalCount(e){this._totalCount=e}get totalCount(){return this._totalCount}updatedMaxValue(e){let t=e+this.unitMagnitudeMask;this.maxValue=t}updateMinNonZeroValue(e){if(e<=this.unitMagnitudeMask)return;let t=s(e/this.lowestDiscernibleValueRounded)*this.lowestDiscernibleValueRounded;this.minNonZeroValue=t}constructor(t,n,r){if(this.autoResize=!1,this.startTimeStampMsec=2**53-1,this.endTimeStampMsec=0,this.tag=a.NO_TAG,this.maxValue=0,this.minNonZeroValue=2**53-1,this.identity=0,this.highestTrackableValue=0,this.lowestDiscernibleValue=0,this.numberOfSignificantValueDigits=0,this.bucketCount=0,this.subBucketCount=0,this.countsArrayLength=0,this.wordSizeInBytes=0,t<1)throw Error(`lowestDiscernibleValue must be >= 1`);if(n<2*t)throw Error(`highestTrackableValue must be >= 2 * lowestDiscernibleValue ( 2 * ${t} )`);if(r<0||r>5)throw Error(`numberOfSignificantValueDigits must be between 0 and 5`);this.identity=e.identityBuilder++,this.init(t,n,r)}init(e,r,i){this.lowestDiscernibleValue=e,this.highestTrackableValue=r,this.numberOfSignificantValueDigits=i;let a=2*s(o(10,i));this.unitMagnitude=s(l(e)),this.lowestDiscernibleValueRounded=o(2,this.unitMagnitude),this.unitMagnitudeMask=this.lowestDiscernibleValueRounded-1;let u=c(l(a));this.subBucketHalfCountMagnitude=(u>1?u:1)-1,this.subBucketCount=o(2,this.subBucketHalfCountMagnitude+1),this.subBucketHalfCount=this.subBucketCount/2,this.subBucketMask=(s(this.subBucketCount)-1)*o(2,this.unitMagnitude),this.establishSize(r),this.leadingZeroCountBase=53-this.unitMagnitude-this.subBucketHalfCountMagnitude-1,this.percentileIterator=new n.default(this,1),this.recordedValuesIterator=new t.default(this)}establishSize(e){this.countsArrayLength=this.determineArrayLengthNeeded(e),this.bucketCount=this.getBucketsNeededToCoverValue(e),this.highestTrackableValue=e}determineArrayLengthNeeded(e){if(e<2*this.lowestDiscernibleValue)throw Error(`highestTrackableValue (`+e+`) cannot be < (2 * lowestDiscernibleValue)`);return this.getLengthForNumberOfBuckets(this.getBucketsNeededToCoverValue(e))}getLengthForNumberOfBuckets(e){return(e+1)*(this.subBucketCount/2)}getBucketsNeededToCoverValue(e){let t=this.subBucketCount*o(2,this.unitMagnitude),n=1;for(;t<=e;){if(t>(2**53-1)/2)return n+1;t*=2,n++}return n}recordValue(e){this.recordSingleValue(e)}recordSingleValue(e){let t=this.countsArrayIndex(e);t>=this.countsArrayLength?this.handleRecordException(1,e):this.incrementCountAtIndex(t),this.updateMinAndMax(e),this.incrementTotalCount()}handleRecordException(e,t){if(!this.autoResize)throw Error(`Value `+t+` is outside of histogram covered range`);this.resize(t);var n=this.countsArrayIndex(t);this.addToCountAtIndex(n,e),this.highestTrackableValue=this.highestEquivalentValue(this.valueFromIndex(this.countsArrayLength-1))}countsArrayIndex(e){if(e<0)throw Error(`Histogram recorded value cannot be negative.`);let t=this.getBucketIndex(e),n=this.getSubBucketIndex(e,t);return this.computeCountsArrayIndex(t,n)}computeCountsArrayIndex(e,t){return(e+1)*o(2,this.subBucketHalfCountMagnitude)+(t-this.subBucketHalfCount)}getBucketIndex(e){return u(s(l(e))-this.subBucketHalfCountMagnitude-this.unitMagnitude,0)}getSubBucketIndex(e,t){return s(e/o(2,t+this.unitMagnitude))}updateMinAndMax(e){e>this.maxValue&&this.updatedMaxValue(e),e<this.minNonZeroValue&&e!==0&&this.updateMinNonZeroValue(e)}getValueAtPercentile(e){let t=d(e,100)/100*this.totalCount,n=u(c(t-(0,i.default)(t)),1),r=0;for(let t=0;t<this.countsArrayLength;t++)if(r+=this.getCountAtIndex(t),r>=n){var a=this.valueFromIndex(t);return e===0?this.lowestEquivalentValue(a):this.highestEquivalentValue(a)}return 0}valueFromIndexes(e,t){return t*o(2,e+this.unitMagnitude)}valueFromIndex(e){let t=s(e/this.subBucketHalfCount)-1,n=e%this.subBucketHalfCount+this.subBucketHalfCount;return t<0&&(n-=this.subBucketHalfCount,t=0),this.valueFromIndexes(t,n)}lowestEquivalentValue(e){let t=this.getBucketIndex(e),n=this.getSubBucketIndex(e,t);return this.valueFromIndexes(t,n)}highestEquivalentValue(e){return this.nextNonEquivalentValue(e)-1}nextNonEquivalentValue(e){return this.lowestEquivalentValue(e)+this.sizeOfEquivalentValueRange(e)}sizeOfEquivalentValueRange(e){let t=this.getBucketIndex(e),n=this.getSubBucketIndex(e,t);return o(2,this.unitMagnitude+(n>=this.subBucketCount?t+1:t))}medianEquivalentValue(e){return this.lowestEquivalentValue(e)+s(this.sizeOfEquivalentValueRange(e)/2)}get mean(){if(this.totalCount===0)return 0;this.recordedValuesIterator.reset();let e=0;for(;this.recordedValuesIterator.hasNext();){let t=this.recordedValuesIterator.next();e+=this.medianEquivalentValue(t.valueIteratedTo)*t.countAtValueIteratedTo}return e/this.totalCount}getStdDeviation(e=this.mean){if(this.totalCount===0)return 0;let t=0;for(this.recordedValuesIterator.reset();this.recordedValuesIterator.hasNext();){let n=this.recordedValuesIterator.next(),r=this.medianEquivalentValue(n.valueIteratedTo)-e;t+=r*r*n.countAddedInThisIterationStep}return Math.sqrt(t/this.totalCount)}get stdDeviation(){if(this.totalCount===0)return 0;let e=this.mean,t=0;for(this.recordedValuesIterator.reset();this.recordedValuesIterator.hasNext();){let n=this.recordedValuesIterator.next(),r=this.medianEquivalentValue(n.valueIteratedTo)-e;t+=r*r*n.countAddedInThisIterationStep}return Math.sqrt(t/this.totalCount)}outputPercentileDistribution(e=5,t=1,n=!1){let i=``;n?i+=`"Value","Percentile","TotalCount","1/(1-Percentile)"
|
|
189
189
|
`:i+=` Value Percentile TotalCount 1/(1-Percentile)
|
|
190
190
|
|
|
191
191
|
`;let a=this.percentileIterator;a.reset(e);let o,s;if(n){let e=(0,r.floatFormatter)(0,this.numberOfSignificantValueDigits),n=(0,r.floatFormatter)(0,12),i=(0,r.floatFormatter)(0,2);o=r=>e(r.valueIteratedTo/t)+`,`+n(r.percentileLevelIteratedTo/100)+`,`+r.totalCountToThisValue+`,`+i(1/(1-r.percentileLevelIteratedTo/100))+`
|
|
@@ -210,21 +210,24 @@ Config tooling:
|
|
|
210
210
|
`)){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(`
|
|
211
211
|
`)){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 PaneVisibility=class{servers=new Map;loop={kind:`idle`};constructor(e){this.deps=e}follow(){switch(this.loop.kind){case`idle`:this.deps.log(`info`,`visibility following`),this.ask();break;case`asking`:this.loop.following=!0;break;case`due`:break}return()=>this.stop()}stop(){switch(this.loop.kind){case`due`:this.loop.clear(),this.end();return;case`asking`:this.loop.following=!1;return;case`idle`:return}}ask(){let e={kind:`asking`,following:!0};this.loop=e,Promise.resolve().then(()=>this.refresh(this.deps.sockets())).catch(e=>this.deps.log(`error`,`visibility refresh threw: ${inspect(e)}`)).then(()=>{if(e.following){this.loop={kind:`due`,clear:this.deps.clock.after(this.deps.intervalMs,()=>this.ask(),{unref:!0})};return}this.end()})}end(){this.deps.log(`info`,`visibility stopped forgot=${this.servers.size}`),this.loop={kind:`idle`},this.servers.clear()}shown(e){if(e==null)return!0;let t=this.servers.get(e.socket);return t?.kind!==`asked`||t.shown.has(e.pane)}async refresh(e){for(let t of this.servers.keys())e.has(t)||this.servers.delete(t);let t=await Promise.all([...e].map(async e=>{let[t,n]=await Promise.all([this.deps.listPanes(e),this.deps.listClients(e)]);return[e,t.kind===`ok`?n.kind===`ok`?{kind:`asked`,shown:shownPanes(t.stdout,controlledSessions(n.stdout)),status:statusLinesOf(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),!sameView(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 sameView(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))}const RANGE_PREFIX=`ccb`,RANGE_HASH_HEX=12;function rangeOf(e){return`ccb`+createHash(`sha256`).update(e).digest(`hex`).slice(0,RANGE_HASH_HEX)}const STANDARD_NAMES$1=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function tmuxColor(e){if(e===void 0)return`terminal`;let t=ColorSpec.parse(e);if(t.isDefault)return`terminal`;switch(t.type){case ColorDepth.STANDARD:{let e=t.number===void 0?void 0:STANDARD_NAMES$1[t.number];if(e!==void 0)return e;break}case ColorDepth.EIGHT_BIT:if(t.number!==void 0)return`colour${t.number}`;break;case ColorDepth.TRUECOLOR:{let e=t.fixedValue;if(e!==void 0)return e.hex;break}case ColorDepth.DEFAULT:case ColorDepth.WINDOWS:break}throw Error(`frames: no tmux colour for ${t.name}`)}const ATTRIBUTES$1={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 escaped(e){return e.replaceAll(`#`,`##`)}function directive({fg:e,bg:t,attrs:n=[]}){let r=n.map(e=>{let t=ATTRIBUTES$1[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${tmuxColor(e)}`,`bg=${tmuxColor(t)}`,...r].join(`,`)}]`}function encode$1(e){let t={},n=e=>{let n=directive(e)+escaped(e.text);if(e.link===void 0)return n;let r=rangeOf(e.link);return t[r]=e.link,`#[range=user|${r}]${n}#[norange]`};return{rows:e.rows.map(e=>mergedRuns(e).map(n).join(``)),links:t}}function tmuxStatusFrame(e){return laneEncoded(encode$1,e)}const MAX_STATUS_ROWS=LANES.tmuxStatus.rows,PRIOR_OPTION=`@cc-candybar-status-prior`,WROTE_OPTION=`@cc-candybar-status-wrote`,BINDING_OPTION=`@cc-candybar-binding-prior`,CLICK_KEY=[`-T`,`root`,`MouseDown1Status`],INDICES=Array.from({length:MAX_STATUS_ROWS},(e,t)=>t),rowOption=e=>`@cc-candybar-row-${e}`,rowFormat=e=>`#[fill=terminal]#{${rowOption(e)}}`,formatOption=e=>`status-format[${e}]`;function statusWord(e){return e===0?`off`:e===1?`on`:String(e)}function statusRows(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 sameFormats(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 tmuxArg(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function chain(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function tmuxQuoted(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function commandText(e){return e.map(e=>e.map(tmuxQuoted).join(` `)).join(` ; `)}const SEPARATOR=`ccb:separator`;function readChain(e){return chain(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,SEPARATOR],e]))}function answersOf(e,t){let n=e.split(`${SEPARATOR}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const show=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],showGlobal=e=>[`show-options`,`-g`,`-q`,`-v`,e],ownQueries=e=>[[`show-options`,`-t`,e],show(e,`status`),...INDICES.map(t=>show(e,formatOption(t)))];function ownOf(e){let[t=``,n=``,...r]=e,i=t.split(`
|
|
212
212
|
`).map(e=>e.split(` `)[0]??``),a={};for(let e of INDICES)i.includes(formatOption(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 arrayWrite(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,formatOption(Number(t)),tmuxArg(n)])]}const INSTALL_QUERIES=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...ownQueries(e),...INDICES.map(e=>showGlobal(formatOption(e))),show(e,PRIOR_OPTION),show(e,WROTE_OPTION)];function leftBehind(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:statusRows(t)}catch(e){return{kind:`theirs`,why:`${PRIOR_OPTION} 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 installPlan(e,t,n){let[r=``,...i]=t,a=ownOf(i.slice(0,2+MAX_STATUS_ROWS)),o=i.slice(2+MAX_STATUS_ROWS,2+2*MAX_STATUS_ROWS),[s=``,c=``]=i.slice(2+2*MAX_STATUS_ROWS);if(s!==``)return leftBehind(s,c,n);let l=statusRows(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:MAX_STATUS_ROWS-l},(e,t)=>[l+t,rowFormat(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,PRIOR_OPTION,JSON.stringify(f)],...arrayWrite(e,d)]}}const RESTORE_QUERIES=e=>[...ownQueries(e),show(e,WROTE_OPTION)];function restorePlan(e,t,n){let r=ownOf(n.slice(0,2+MAX_STATUS_ROWS)),i=n[2+MAX_STATUS_ROWS]??``,a=[],o=[];if(sameFormats(r.formats,t.wrote))a.push(...arrayWrite(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,formatOption(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,tmuxArg(t.status)]):o.push(`status`)),a.push(...INDICES.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,rowOption(t)]),[`set-option`,`-q`,`-u`,`-t`,e,PRIOR_OPTION],[`set-option`,`-q`,`-u`,`-t`,e,WROTE_OPTION]),{commands:a,kept:o}}const BOUND=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,ROOT_KEYS=[[`list-keys`,`-T`,`root`]];function boundOf(e){let t=BOUND.exec(e);return t===null?null:{line:t[0],command:t[1]}}const clickUrl=e=>`${STATUS_LINE_CLICK_PREFIX}${encodeSegments([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,isClickBinding=e=>e?.command.includes(STATUS_LINE_CLICK_PREFIX)??!1;function bindingRestorePlan(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,BINDING_OPTION]};return isClickBinding(boundOf(t))?{steps:[e===null?{command:[`unbind-key`,...CLICK_KEY]}:{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 DeclaredStatusLines=class{declared=new Set;constructor(e,t){this.lines=e,this.paneOf=t}declare(e){let t=new Set(e);for(let e of this.declared)t.has(e)||this.lines.observe(e,null,!1);for(let e of t)this.declared.has(e)||this.lines.observe(e,this.paneOf(e),!0);this.declared=t}arrived(e){this.declared.has(e)&&this.lines.observe(e,this.paneOf(e),!0)}},TmuxStatusLines=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=tmuxStatusFrame(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}async close(){this.closed=!0;for(let e of this.held.values())e.unsubscribe?.();this.held.clear(),await Promise.all([...this.servers].map(([e,t])=>this.closeServer(e,t)))}async closeServer(e,t){try{await t.running;for(let n of[...t.layouts.keys()])await this.restore(e,t,n);await this.restoreBinding(e,t)}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} restore at close threw: ${String(t)}`)}}linkAt(e){let t=segmentsOf(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||this.closed)continue;let c=a.find(e=>e.pane===n.shownBy.get(i))?.frame?.rows.slice(0,MAX_STATUS_ROWS-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#{${PRIOR_OPTION}}\t#{${WROTE_OPTION}}`]);if(n.kind===`ok`)for(let r of n.stdout.split(`
|
|
213
|
-
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=leftBehind(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,[showGlobal(`@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)} ${BINDING_OPTION} 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,INSTALL_QUERIES(n));if(r===null||this.closed)return null;let i=installPlan(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,rowOption(r),e])}),i!==n.status){let e=statusWord(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,WROTE_OPTION,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,commandText(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,RESTORE_QUERIES(n));if(i===null)return;let a=restorePlan(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,ROOT_KEYS);if(r===null||this.closed)return;let i=boundOf(r[0]??``);if(n.kind===`none`&&isClickBinding(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`&&isClickBinding(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...CLICK_KEY,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${tmuxQuoted(`${this.deps.handler} ${clickUrl(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,ROOT_KEYS);if(r===null)return;let i=bindingRestorePlan(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}`)}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,readChain(t));return n.kind===`ok`?answersOf(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,chain(t),n)).kind===`ok`)}};function segmentsOf(e){try{return decodeSegments(e)}catch(e){if(e instanceof URIError)return null;throw e}}const RULE=/^─{20,}/,PROMPT=/^❯(\s|$)/,STASHED=/›\s*stashed$/;function inputBox(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>RULE.test(e)?[t]:[]).at(-2);return n===void 0||!PROMPT.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function promptState(e){if(e.inMode)return{kind:`in-mode`};let t=inputBox(e);return t===null?{kind:`no-prompt`}:STASHED.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function draftShown(e){return/^❯\s*\S/u.test(inputBox(e)?.prompt??``)}const TURN_RUNNING=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function turnRunning(e){return e.screen.some(e=>TURN_RUNNING.test(e))}const REFUSALS={"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 tmuxPaneOf(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 typeSlash(e,t,n){return t.kind===`refused`?t:e(t.hint,n)}const typeInPane=e=>async(t,n)=>{let r=promptState(await e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:REFUSALS[r.kind]};let i=await e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i},keep=e=>({arity:e,keep:!0}),drop=e=>({arity:e,keep:!1}),FLAGS={"--add-dir":keep(`variadic`),"--agent":keep(`one`),"--agents":keep(`one`),"--allow-dangerously-skip-permissions":keep(`none`),"--allowedTools":keep(`variadic`),"--allowed-tools":keep(`variadic`),"--append-system-prompt":keep(`one`),"--autocompact":keep(`one`),"--ax-screen-reader":keep(`none`),"--bg":drop(`none`),"--background":drop(`none`),"--bare":keep(`none`),"--betas":keep(`variadic`),"--brief":keep(`none`),"--chrome":keep(`none`),"--cloud":drop(`optional`),"-c":drop(`none`),"--continue":drop(`none`),"--dangerously-skip-permissions":keep(`none`),"-d":keep(`optional`),"--debug":keep(`optional`),"--debug-file":keep(`one`),"--desktop":drop(`none`),"--disable-slash-commands":keep(`none`),"--disallowedTools":keep(`variadic`),"--disallowed-tools":keep(`variadic`),"--effort":keep(`one`),"--environment":drop(`one`),"--exclude-dynamic-system-prompt-sections":keep(`none`),"--fallback-model":keep(`one`),"--file":keep(`variadic`),"--fork-session":drop(`none`),"--forward-subagent-text":keep(`none`),"--from-pr":drop(`optional`),"-h":drop(`none`),"--help":drop(`none`),"--ide":keep(`none`),"--include-hook-events":keep(`none`),"--include-partial-messages":keep(`none`),"--input-format":keep(`one`),"--json-schema":keep(`one`),"--max-budget-usd":keep(`one`),"--mcp-config":keep(`variadic`),"--model":keep(`one`),"-n":keep(`one`),"--name":keep(`one`),"--no-chrome":keep(`none`),"--no-session-persistence":keep(`none`),"--output-format":keep(`one`),"--permission-mode":keep(`one`),"--permission-prompts":keep(`one`),"--plugin-dir":keep(`one`),"--plugin-url":keep(`one`),"-p":drop(`none`),"--print":drop(`none`),"--prompt-suggestions":keep(`optional`),"--remote-control":keep(`optional`),"--remote-control-session-name-prefix":keep(`one`),"--replay-user-messages":keep(`none`),"--restricted":keep(`none`),"-r":drop(`optional`),"--resume":drop(`optional`),"--safe-mode":keep(`none`),"--session-id":drop(`one`),"--setting-sources":keep(`one`),"--settings":keep(`one`),"--strict-mcp-config":keep(`none`),"--system-prompt":keep(`one`),"--system-prompt-snapshot":keep(`one`),"--teleport":drop(`optional`),"--tmux":drop(`none`),"--tools":keep(`variadic`),"--verbose":keep(`none`),"-v":drop(`none`),"--version":drop(`none`),"-w":drop(`optional`),"--worktree":drop(`optional`)},SESSION_FLAG={resume:`--resume`,fresh:`--session-id`};function sessionArgs(e){return[SESSION_FLAG[e.kind],e.sessionId]}const isFlag=e=>e.startsWith(`-`)&&e!==`-`;function startPlace(e,t){let n=worktreeOf(t);return n===null?{dir:e??t,args:[]}:e!==null&&within$1(e,n.top)?{dir:e,args:[]}:{dir:e===null||worktreeOf(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const within$1=(e,t)=>e===t||e.startsWith(t+path.sep);function relaunchArgs(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!isFlag(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=FLAGS[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=>!isFlag(e)):o.arity===`variadic`?takeWhile(n.slice(r),e=>!isFlag(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 worktreeOf(e){let t=e.split(path.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(path.sep),repo:t.slice(0,n-1).join(path.sep)||path.sep}}function takeWhile(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const BAND_PLUGIN=`candybar-band@cc-candybar`,BAND_CLIENT=path.join(`bin`,`cc-candybar-native`),EXIT_PATIENCE_MS=15e3,ATTACH_PATIENCE_MS=3e4,RELOAD_PLUGINS=slashLine(`/reload-plugins`);async function bandOn(e,t,n,r,i){let a=sourceCheckoutOf(r.bundle);if(a===null)throw new BadVerbArgs(`${LANES.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${r.bundle} — run the daemon from a checkout (mod/README.md)`);let o=path.join(a,BAND_CLIENT);if(!i.fileExists(o))throw new BadVerbArgs(`the band mod starts ${o}, which is not built — run \`just install-rust\` in ${a}`);return installBand(e,t,n,a,i)}async function restartClaude(e,t,n,r){let i=attachLauncherOf(n.preload),a=[n.preload,i].find(e=>!r.fileExists(e));if(a!==void 0)throw new BadVerbArgs(`${LANES.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return restartUnderAttach(e,t,{node:n.node[0],launcher:i,preload:n.preload},r)}async function paneOn(e,t,n){let r=await n.barPanes(e);return r.length>0?`bar pane ${r.join(`, `)} already draws ${e.pane}'s bar`:`opened bar pane ${await n.openBarPane(e,[...t.node,t.bundle,`bar-pane`,e.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${e.pane}`}async function paneOff(e,t){let n=await t.barPanes(e);for(let r of n)await t.closePane(e,r);return n.length===0?`no bar pane draws ${e.pane}'s bar`:`closed bar pane ${n.join(`, `)}`}async function installBand(e,t,n,r,i){let a={sessionId:e.sessionId,projectDir:e.projectDir,claudeConfigDir:e.claudeConfigDir??void 0};await i.claude([`plugin`,`marketplace`,`add`,r],a),await i.claude([`plugin`,`install`,BAND_PLUGIN],a);let o=await typeSlash(n,t,RELOAD_PLUGINS);if(o.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${o.reason} — or type /reload-plugins yourself`);return`installed ${BAND_PLUGIN} from ${r} and typed /reload-plugins into ${o.pane}`}const CARRIED_ENV=new Set([CLAUDE_CONFIG_DIR_ENV,CONFIG_ENV]);function environmentOf(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function restartUnderAttach(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,moduleGraphReaderOf(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}) — ${LANES.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=endingLoses(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${LANES.statusline.label} off and on again`);let s=conversationLost(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=relaunchArgs(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=environmentOf(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])=>CARRIED_ENV.has(e)),m=(e,t)=>attachCommandLine(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...sessionArgs(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${EXIT_PATIENCE_MS/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=sessionStartOf(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(startPlace(null,i.cwd),_))}let y=m(startPlace(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 ${ATTACH_PATIENCE_MS/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${STARTED[g.kind](e.sessionId)}, and its statusline follows lane B`}function conversationLost(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 sessionStartOf(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const STARTED={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},UNREADABLE={"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 endingLoses(e){let t=promptState(e);return t.kind===`ready`?turnRunning(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:draftShown(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:UNREADABLE[t.kind]}const OUTLIVES={copy:!1,open:!1,"type-slash":!1,"apply-update":!1,run:!0,"restart-claude":!0,surface:!0},outlives=e=>OUTLIVES[e.kind];function nameOf(e){switch(e.kind){case`copy`:case`open`:case`apply-update`:return e.kind;case`type-slash`:return e.line;case`run`:return`run ${e.action}`;case`restart-claude`:return`lane: statusline on`;case`surface`:return`lane: ${e.surface} ${e.on?`on`:`off`}`}}const paneKey=e=>`${e.socket}\0${e.pane}`,did=e=>({outcome:{kind:`ok`},said:e}),not=e=>({outcome:e,said:e.reason});var Acts=class{inPane=new KeyedSerialQueue;setups=new KeyedSerialQueue;restarting=new Map;performers;constructor(e){this.deps=e;let{lanes:t}=e;this.performers={copy:t=>clickLaunch(e.launch,{bin:`/usr/bin/pbcopy`,stdinInput:t.text,category:`click.pbcopy`},`pbcopy`,`copied`),open:t=>clickLaunch(e.launch,{bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,t.target],category:`click.open`},`open -a "Visual Studio Code"`,`opened ${t.target}`),"type-slash":async e=>{if(this.restarting.has(e.session))return not({kind:`refused`,reason:`a restart holds pane ${e.pane.pane} — click again once it has finished`});let t=await this.typed(e.pane,e.line);return t.kind===`typed`?did(`typed into ${t.pane}`):not({kind:`refused`,reason:t.reason})},run:t=>e.run(t),"apply-update":async()=>(await e.applyUpdate(),did(`applied`)),"restart-claude":e=>this.restart(e.session,e.pane,()=>restartClaude({...e.at,sessionId:e.session},e.pane,t.host,t.edge)),surface:async e=>{switch(e.surface){case`band`:return did(await this.setups.run(e.session,()=>bandOn({...e.at,sessionId:e.session},e.pane,(e,t)=>this.typed(e,t),t.host,t.edge)));case`pane`:return did(await this.setups.run(e.session,()=>this.inPane.run(paneKey(e.pane),()=>e.on?paneOn(e.pane,t.host,t.edge):paneOff(e.pane,t.edge))))}}}}typed(e,t){return this.inPane.run(paneKey(e),()=>this.deps.type(e,t))}async perform(e){let{outcome:t,said:n}=this.deps.closing()?not({kind:`closing`,reason:`the daemon is closing`}):await this.performed(e);return this.deps.log(t.kind===`ok`||t.kind===`closing`?`info`:`warn`,`act kind=${e.kind} sid=${valueOf$1(e.session??`-`)} id=${e.id} outcome=${t.kind} — ${nameOf(e)}: ${n}`),t.kind===`ok`?t:{...t,reason:`${nameOf(e)}: ${t.reason}`}}async performed(e){try{return await this.performers[e.kind](e)}catch(e){let t=failureOf(e);switch(t.kind){case`bad-request`:return not({kind:`refused`,reason:t.message});case`closing`:return not({kind:`closing`,reason:t.message});default:return not({kind:`failed`,reason:t.message})}}}async restart(e,t,n){this.restarting.set(e,(this.restarting.get(e)??0)+1);try{return did(await this.setups.run(e,()=>this.inPane.run(paneKey(t),n)))}finally{let t=this.restarting.get(e)-1;t===0?this.restarting.delete(e):this.restarting.set(e,t)}}};const ABSENT={kind:`absent`};function parse$1(e){if(e===null||/^\s*$/.test(e))return{kind:`none`};try{return{kind:`document`,root:parseDocument(e)}}catch(e){if(!(e instanceof Json5EditError))throw e;return{kind:`unparsed`}}}function readAt(e,t,n){return e===null?ABSENT:n.length===0||t.kind!==`document`?{kind:`file`,text:e}:readOf(e,nodeAt(t.root,n))}function readOf(e,t){return t===void 0?ABSENT:{kind:`value`,text:movableTextOf(e,t)}}function sameRead(e,t){return e.kind===`value`&&t.kind===`value`?sameValue(import_lib.default.parse(e.text),import_lib.default.parse(t.text)):e.kind===`file`&&t.kind===`file`?e.text===t.text:e.kind===`absent`&&t.kind===`absent`}function sameValue(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&sameValue(e[n],t[n]))}function diffChanges(e,t){if(e===t)return[];if(e===null)return[{op:`insert`,at:[],text:t,precedes:null}];let n={kind:`file`,text:e};if(t===null)return[{op:`remove`,at:[],read:n}];let r=[{op:`replace`,at:[],text:t,read:n}],i=parse$1(e),a=parse$1(t);if(i.kind!==`document`||a.kind!==`document`)return r;let o=diffNode([],e,i.root,t,a.root),s=applyChanges(e,o);return s.kind===`applied`&&s.text===t?o:r}function diffNode(e,t,n,r,i){let a=textOf$1(r,i);if(textOf$1(t,n)===a)return[];let o=e.length===0?[{op:`replace`,at:e,text:r,read:{kind:`file`,text:t}}]:[{op:`replace`,at:e,text:movableTextOf(r,i),read:readOf(t,n)}];if(n.kind!==`object`||i.kind!==`object`)return o;let s=diffMembers(e,t,n,r,i);return rebuilds(t,s,e,a)?s:o}function rebuilds(e,t,n,r){let i=applyChanges(e,t);if(i.kind!==`applied`)return!1;let a=parse$1(i.text);if(a.kind!==`document`)return!1;let o=nodeAt(a.root,n);return o!==void 0&&textOf$1(i.text,o)===r}function diffMembers(e,t,n,r,i){let a=new Map(n.entries.map(e=>[e.key,e.value])),o=new Set(i.entries.map(e=>e.key)),s=n.entries.filter(e=>!o.has(e.key)).map(n=>({op:`remove`,at:[...e,n.key],read:readOf(t,n.value)})),c=i.entries.map((e,t)=>i.entries.slice(t+1).find(e=>a.has(e.key))?.key??null),l=i.entries.flatMap((n,i)=>{let o=a.get(n.key);return o===void 0?[{op:`insert`,at:[...e,n.key],text:movableTextOf(r,n.value),precedes:c[i]}]:diffNode([...e,n.key],t,o,r,n.value)});return[...s,...l]}function applyChanges(e,t){let n=e;for(let e of t){let t=parse$1(n),r=movedAncestor(t,e.at);if(r!==null)return{kind:`moved`,at:r,read:`object`,found:readAt(n,t,r)};let i=e.op===`insert`?ABSENT:e.read,a=readAt(n,t,e.at);if(!sameRead(a,i))return{kind:`moved`,at:e.at,read:i,found:a};n=applied(n,e)}return{kind:`applied`,text:n}}function movedAncestor(e,t){if(t.length===0)return null;if(e.kind!==`document`)return[];for(let n=0;n<t.length;n++){let r=t.slice(0,n);if(nodeAt(e.root,r)?.kind!==`object`)return r}return null}function applied(e,t){if(t.at.length===0)return t.op===`remove`?null:t.text;switch(t.op){case`replace`:return setValue(e,t.at,t.text,JSON5_DIALECT);case`insert`:return insertValue(e,t.at,t.text,JSON5_DIALECT,t.precedes);case`remove`:return deleteValue(e,t.at,t.at.length-1)}}function addressText(e){return e.length===0?`the whole file`:e.join(`.`)}const REPO_ANSWERS=[`approved`,`declined`];function answerDir(e){return e.link.kind===`linked`?e.link.main:e.dir}const answerOf$1=(e,t)=>Object.hasOwn(e,t)?e[t]:null;function ruling(e,t){let n=answerDir(t);if(e.kind===`failed`)return{standing:`unread`,under:n};let r=answerOf$1(e.value,n),i=answerOf$1(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 gateRepos(e,t,n){let r=[...new Map([...t,...n?.ships?[n]:[]].map(e=>[e.dir,e])).values()],i=r.map(t=>({dir:t.dir,...ruling(e,t)})),a=e=>i.filter(t=>t.standing===e),o=e=>[...new Set(a(e).map(e=>e.under))];return{plugins:n!==null&&ruling(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 withAnswer(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 parseRepoConfigBook(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(!REPO_ANSWERS.includes(n))return{kind:`failed`,reason:`answers ${JSON.stringify(t)} ${JSON.stringify(n)}, not ${REPO_ANSWERS.join(` or `)}`};return{kind:`ok`,value:e}}function repoUnreadNotice(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 repoGateLines(e){let t=repoUnreadNotice(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}`)]}function presence(e){try{return fs.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const textOf=e=>`${JSON.stringify(e,null,2)}\n`;function stateFile(e,t,n,r){let i=path.join(e,t),a=()=>{let e;try{e=fs.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}`}},o=e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return{kind:`ok`,value:{file:i,text:n===t.value?null:textOf(n),value:n}}};return{read:a,plan:o,update:e=>written$1(o(e))}}function written$1(e){if(e.kind===`failed`)return e;let{file:t,text:n,value:r}=e.value;return n!==null&&writeAtomic(t,n),{kind:`ok`,value:r}}const REPO_CONFIGS_FILE=`repo-configs.json`,REPO_CONFIGS_DIR=`repo-configs`;function repoConfigsDir(e){return path.join(e,REPO_CONFIGS_DIR)}function repoConfigsPath(e){return path.join(repoConfigsDir(e),REPO_CONFIGS_FILE)}const repoConfigs=e=>{let t=stateFile(repoConfigsDir(e),REPO_CONFIGS_FILE,{},parseRepoConfigBook),n=stateFile(e,REPO_CONFIGS_FILE,{},parseRepoConfigBook),r=()=>fs.existsSync(repoConfigsPath(e)),i=e=>{if(r())return t.plan(e);let i=n.read();return i.kind===`failed`?i:t.plan(()=>e(i.value))};return{read:()=>(r()?t:n).read(),plan:i,update:e=>written$1(i(e))}};function answering(e,t,n){let r=Object.keys(e).filter(e=>e!==t).map(e=>({d:e,found:presence(e)})),i={superseded:r.filter(({d:e,found:n})=>n===`present`&&answerDir({dir:e,link:worktreeLink(e)})===t).map(({d:e})=>e),absent:r.filter(({found:e})=>e===`absent`).map(({d:e})=>e),unchecked:r.flatMap(({found:e})=>typeof e==`object`?[e]:[])};return{book:withAnswer(e,t,n,i.superseded),recorded:i}}function answeredBook(e,t){let n=[],r=repoConfigs(e).plan(e=>t.reduce((e,{session:t,dir:r,answer:i})=>{let a=answering(e,r,i),{superseded:o,absent:s,unchecked:c}=a.recorded;return n.push(`repo-config: ${r} ${i} superseded=${o.join(`,`)||`-`} absent=${s.join(`,`)||`-`} unchecked=${c.length===0?`-`:JSON.stringify(c)} (session=${t})`),a.book},e));return r.kind===`failed`?r:ok$1({...r.value,said:n})}function repoAnswerFields(e,t,n){return{sessionId:e,action:VERB_REPO_CONFIG,declaration:t,evaluated:n}}function repoQuestions(e,t,n){return e.awaiting.map(e=>{let r=`a cc-candybar config for ${e} — run it?`,i=REPO_ANSWERS.map(r=>diagnosticSpan(`[${r===`approved`?`approve`:`decline`}]`,effectsUrl([{verb:VERB_REPO_CONFIG,args:[t,e,r,n.sign(repoAnswerFields(t,e,r))]}]))),a=[diagnosticSpan(r,null),...i];return{severity:APPROVAL_SEVERITY,about:`repo-question\0${e}`,message:r,copy:r,lines:[a]}})}const writeText=(e,t)=>t===null?fs.rmSync(resolvedTarget(e),{force:!0}):writeAtomic(e,t),said=e=>e===`object`?`an object`:e.kind===`absent`?`nothing`:e.kind===`file`?`the file as it was read`:e.text;function performChanges(e,t){let n=new Map,r=[];try{for(let{target:t,changes:r}of e){let e=resolvedTarget(t.path),i=n.get(e),a=i===void 0?readConfigText(e):i.was,o=applyChanges(i===void 0?a:i.will,r);if(o.kind===`moved`)return{kind:`refused`,reason:`${addressText(o.at)} in ${e} changed since it was read (it was ${said(o.read)}, it is ${said(o.found)}) — nothing was written`};n.set(e,{file:e,was:a,will:o.text})}if(t!==null&&t.answers.length>0){let e=answeredBook(t.stateDir,t.answers);if(e.kind===`failed`)return{kind:`failed`,reason:`the repository answers were not recorded: ${e.reason} — nothing was written`};let{file:i,text:a}=e.value;if(r=e.value.said,a!==null){let e=resolvedTarget(i);n.set(e,{file:e,was:readConfigText(e),will:a})}}}catch(e){return{kind:`failed`,reason:`config read failed: ${message(e)}`}}let i=[];try{for(let e of n.values())writeText(e.file,e.will),i.push(e);for(let e of r)t.said(e);return{kind:`ok`}}catch(e){return{kind:`failed`,reason:putBack(i,e)}}}function putBack(e,t){let n=`config write failed: ${message(t)}`;try{for(let{file:t,was:n}of[...e].reverse())writeText(t,n);return`${n} — nothing was written`}catch(e){return`${n}; and putting back what was written failed, so it is half-written: ${message(e)}`}}const message=e=>e instanceof Error?e.message:String(e),performed=e=>e.kind!==`present`&&e.kind!==`change`&&e.kind!==`approve-repo`;function rendererHost(e,t,n,r,i,a){let o=async e=>{let o=sessionOf(e.event),s=o===null?()=>{}:i.holding(o);try{let o=t.monotonic(),{subscriptions:s,turnMs:l,...u}=await n.answer(e),d={...u,hopMs:elapsedMs(t,o)-l},f=d.effects.filter(e=>e.kind===`change`),p=d.effects.filter(e=>e.kind===`approve-repo`),m=a.closing()?{kind:`closing`,reason:`the daemon is closing`}:f.length+p.length===0?{kind:`ok`}:performChanges(f,{stateDir:a.stateDir,answers:p,said:e=>r(`info`,e)}),h=m.kind===`ok`||m.kind===`closing`?m:{kind:`skipped`,reason:`not performed: ${m.reason}`},g=[],_=Promise.resolve();for(let t of d.effects)if(t.kind===`present`)e.event.kind!==`request`&&g.push(c(t,{kind:`failed`,reason:`a ${e.event.kind} turn answers no request`}));else if(t.kind===`change`||t.kind===`approve-repo`)g.push(c(t,m));else{let e=m.kind===`ok`?_.then(()=>a.perform(t)):Promise.resolve(h),n=e.then(e=>c(t,e));outlives(t)||(g.push(n),_=e)}return i.subscribed(s),{...d,settled:await Promise.all(g)}}finally{s()}},s=e=>o(e).catch(e=>({kind:`threw`,failure:failureOf(e),record:[],effects:[],hopMs:null,settled:[]})),c=async(e,n)=>{let r=performed(e)&&(n.kind===`failed`||n.kind===`refused`);r&&e.session===null&&a.unheard(n.reason);let i=await u({kind:`event`,at:instantAt(t),event:{kind:`effect-done`,session:e.session,of:e.id,outcome:n}},[[`effect`,String(e.id)]]);return r&&e.session!==null&&i.kind===`threw`&&i.failure.kind===`down`&&a.unheard(n.reason),n},l=(t,n,i)=>{let a=sessionOf(t.event),o=[[`renderer`,e],[`input`,t.event.kind],...a===null?[]:[[`sid`,a]],...n];switch(i.kind){case`answered`:i.record.length>0&&r(`info`,eventLine(`turn`,[...o,...i.record]));return;case`threw`:if(i.failure.kind===`down`)return;r(LEVEL[i.failure.kind],eventLine(`turn`,[...o,...i.record,[`error`,i.failure.detail]]))}},u=async(e,t)=>{let n=await s(e);return l(e,t,n),n},d=async(t,r)=>{let i=await n.answer({kind:`adapter`,push:t,at:r}).catch(e=>({kind:`threw`,failure:failureOf(e)}));if(i.kind===`threw`)throw new CrossedFailure({...i.failure,message:`renderer ${e} push ${t.kind} threw: ${i.failure.message}`,detail:`renderer ${e} push ${t.kind} threw: ${i.failure.detail}`});if(i.reply.kind!==t.kind)throw Error(`renderer ${e} answered push ${t.kind} with a ${i.reply.kind} reply`);return i.reply};return{name:e,answer:s,deliver:u,ask:d,tell:(e,t)=>void d(e,t).catch(e=>{let t=failureOf(e);t.kind!==`down`&&r(`error`,t.detail)})}}function sessionOf(e){switch(e.kind){case`start`:return null;case`config`:case`request`:return e.context.hookData.session_id;case`world-state`:return e.worldState.session;case`click`:return e.session?.ok?e.session.id:null;case`retire`:case`effect-done`:case`menu-idle`:return e.session}}function encodeRenderOrigin({projectDir:e,cwd:t,target:n}){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path??null,source:n.source})}const SESSION_RENDER_ORIGIN_KEY=`render-origin`,SESSION_CLIENT_HINTS_KEY=`client-hints`;function applyStyleToFragment(e,t){let n=asFragment(e),r=n.copy();return r.style=layerStyle(n.style,t),r}function asFragment(e){if(!(e instanceof RichText))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function attrFunc(e){return{fn:(t=>applyStyleToFragment(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function colorSinkFunc(e){return{fn:((t,n)=>applyStyleToFragment(n,new Style({[e]:ColorSpec.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function attrStyle(e,t){return new Style({[e]:t})}function attributeFuncs(){let e={};for(let t of ATTRIBUTE_NAMES)e[t]=attrFunc(attrStyle(t,!0)),e[`not_${t}`]=attrFunc(attrStyle(t,!1));for(let[t,n]of Object.entries(ATTRIBUTE_SHORT_ALIASES))e[t]=attrFunc(attrStyle(n,!0));return e}const styleSpecFunc={fn:((e,t)=>applyStyleToFragment(t,Style.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},linkFunc={fn:((e,t)=>applyStyleToFragment(t,new Style({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function richTextStyleFuncs(){return{fg:colorSinkFunc(`color`),bg:colorSinkFunc(`bgcolor`),...attributeFuncs(),link:linkFunc,style:styleSpecFunc}}function asColor(e,t){let n;try{n=parseHexColor(e.trim())}catch(n){throw n instanceof ColorParseError?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 computable(n,t,JSON.stringify(e))}function computable(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 colorFunc(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function asAmount(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 darkenFunc=colorFunc([`string`,`int`],((e,t)=>darken(asColor(e,`darken`),t).hex)),lightenFunc=colorFunc([`string`,`int`],((e,t)=>darken(asColor(e,`lighten`),-t).hex)),MIX_PCT_MAX=100,MIX_RANGE={min:0,max:MIX_PCT_MAX,note:`0 = from, 100 = toward`},mixFunc=colorFunc([`string`,`string`,`float`],((e,t,n)=>blendRgb(asColor(e,`mix`),asColor(t,`mix`),asAmount(n,`mix`,`percentage`,MIX_RANGE)/MIX_PCT_MAX).hex)),RATIO_RANGE={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},contrastOnFunc=colorFunc([`string`],(e=>contrastFor(asColor(e,`contrastOn`)).hex)),TRUECOLOR={depth:ColorDepth.TRUECOLOR},readableOnFunc=e=>colorFunc([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return ensureContrast(asColor(t,`readableOn`),asColor(n,`readableOn`),asAmount(r,`readableOn`,`ratio`,RATIO_RANGE),i,void 0,a).hex})),OKLCH_AXIS_FUNCS={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function oklchAxisFuncs(){let e={};for(let[t,n]of Object.entries(OKLCH_AXIS_FUNCS)){let r=t;e[n]=colorFunc([`string`,`float`],((e,t)=>{let i={...IDENTITY,[r]:asAmount(t,n,`amount`)};return Oklch.fromRgba(asColor(e,n)).applyKey(i).toRgba().hex}))}return e}function colorFuncs(e=()=>TRUECOLOR){return{darken:darkenFunc,lighten:lightenFunc,mix:mixFunc,contrastOn:contrastOnFunc,readableOn:readableOnFunc(e),...oklchAxisFuncs()}}function colorStops(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:computable(resolveColorRef(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function paletteFuncs(e){return{color:{fn:(t=>resolveColorRef(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new ColorRamp(parseEase(n),colorStops(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}const HOST_CLOCK=Timeline.play(0);function pairs(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 GLYPH_EFFECTS={...GLYPH_EFFECT_CATALOGUE.loops,typewriter:e=>GLYPH_EFFECT_CATALOGUE.transitions.typewriter(e).effect,scramble:e=>GLYPH_EFFECT_CATALOGUE.transitions.scramble(e).effect,backspace:e=>GLYPH_EFFECT_CATALOGUE.transitions.backspace(e).effect,scrambleOut:e=>GLYPH_EFFECT_CATALOGUE.transitions.scrambleOut(e).effect};function glyphEffect(e){if(!Object.hasOwn(GLYPH_EFFECTS,e))throw RangeError(`unknown glyph effect ${JSON.stringify(e)}; expected one of ${Object.keys(GLYPH_EFFECTS).map(e=>JSON.stringify(e)).join(`, `)}`);return GLYPH_EFFECTS[e]}function animationFuncs(e,t={}){let n=t.timeline??(()=>HOST_CLOCK),r=(e,t,r)=>[Timeline.run(n(),t),finiteTime(e,r.time)],i=(t,n)=>{let i=e(),[a,o]=r(t,n,i),s=shownAt(a,o,i);return i.onHold?.(holdOf(s,o)),s.value},a=(e,t)=>Timeline.run(Timeline.play(e),t);return{frames:{fn:((...t)=>{let n=pairs(`frame`,t,asFragment).map(({seconds:e,value:t})=>({seconds:e,text:t})),i=e();return textFrameAt(...r(`frames`,new FrameSequence(n),i),i)}),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...e)=>{let t=pairs(`color`,e,e=>asColor(e,`stepped`));return t[i(`stepped`,beat(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,tween(r,o,{seconds:e,ease:parseEase(t)})))),argTypes:[`float`,`string`,`float`,`float`,`float`],arity:{kind:`exact`},returnType:`float`},loop:{fn:((e,t)=>i(`loop`,a(t,Animation.continuous(Phase.loop(e))))),argTypes:[`float`,`float`],arity:{kind:`exact`},returnType:`float`},glyphs:{fn:((t,n,i)=>{let o=glyphEffect(t),s=asFragment(i),c=s.plain,l=e();return textFrameAt(...r(`glyphs`,a(n,reglyphText(s,o({z:cellSeed(c,0,0)}),{key:c,asciiOnly:l.asciiOnly===!0})),l),l)}),argTypes:[`string`,`float`,`liftable`],arity:{kind:`exact`},returnType:`T`}}}function richTextFuncs(e){return{...richTextStyleFuncs(),...colorFuncs(e)}}const FALLBACK_ERROR_STYLE=new Style({color:`red`,dim:!0}),CLAUDE_MODEL_PATTERN=/^(?:(?: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,FRIENDLY_MODEL_PATTERN=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function formatModelName(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(CLAUDE_MODEL_PATTERN);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(FRIENDLY_MODEL_PATTERN);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 shortenModelName(e){let t=e.match(FRIENDLY_MODEL_PATTERN);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 abbreviatePath(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 formatInteger(e){return e.toLocaleString()}function parseCascadeStops(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 cascadeAt(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 SPARK_LEVELS=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],LEVELS=SPARK_LEVELS.length;function renderSparkline(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*(LEVELS-1));o+=SPARK_LEVELS[t]}return o}function parseSeries(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 refuseSurplus(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 THEMES_LIST=listResolvablePaletteNames(),ENDCAPS_LIST=[...ENDCAPS_SHAPES];function ccCandybarFuncs(){return{basename:{fn:e=>basename(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>dirname(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>abbreviatePath(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(toNumber(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>toString(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>toBool(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>THEMES_LIST,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>ENDCAPS_LIST,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(refuseSurplus(`sparkline`,[`width`],n),renderSparkline(parseSeries(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>cascadeAt(e,parseCascadeStops(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}const MIN_PROJECTABLE_ELAPSED_MS=300*1e3;function etaMinutes(e,t,n,r){let i=n*6e4-(t*1e3-r);if(i<MIN_PROJECTABLE_ELAPSED_MS||e<=0)return-1;let a=e/i;return Math.max(0,Math.round((100-e)/a/6e4))}const relativeTimeFuncs=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)=>etaMinutes(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function formatterFuncs(){return{formatInteger:{fn:e=>formatInteger(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>formatModelName(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>shortenModelName(e),argTypes:[`string`],arity:{kind:`exact`}}}}let drawing=null;function bindClock(e,t){if(drawing!==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 drawing=n,{heard:()=>n.soonest,[Symbol.dispose]:()=>{drawing=null}}}function drawInProgress(e){if((0,import_dist$1._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(drawing===null)throw Error(`the clock was read outside a draw (${e})`);return drawing}const CLOCK={now:()=>dateOf(drawInProgress(`now`).at),frame:()=>drawInProgress(`frame`).frame,timeline:()=>drawInProgress(`timeline`).timeline};function animationPair(e,t){let{frames:n,stepped:r}=animationFuncs(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 SPRIG_CLOCK_READERS=new Set([`now`,`ago`]);function sprigDatetimeWhere(e,t){return Object.fromEntries(Object.entries(sprigDatetime(e)).filter(([e])=>SPRIG_CLOCK_READERS.has(e)===t))}const SPRIG_DATE_FUNCS=sprigDatetimeWhere(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),CLOCK_FACTORIES=[e=>sprigDatetimeWhere(e.now,!0),e=>animationPair(e.frame,e.timeline),e=>Object.fromEntries(Object.entries(animationPair(e.frame)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),relativeTimeFuncs];function clockFuncs(e){return Object.assign({},...e.map(e=>e(CLOCK)))}const CLOCK_FUNCTIONS=new Set(Object.keys(clockFuncs(CLOCK_FACTORIES)));function engineClockFunctions(e){return new Set([...CLOCK_FUNCTIONS,...Object.keys(clockFuncs(e))])}const DEPTH_BINDINGS={readableOn:readableOnFunc};function createCcCandybarEngine(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return createEngine({fromString:e=>new RichText(e),toString:e=>e.plain,isT:e=>e instanceof RichText,missingKey:`error`,funcs:{...sprigDefaults(),...sprigStrings(),...sprigLists(),...sprigMath(),...sprigConversions(),...sprigFlow(),...sprigDicts(),...SPRIG_DATE_FUNCS,...richTextFuncs(r),...Object.fromEntries(Object.entries(DEPTH_BINDINGS).map(([e,t])=>[e,t(r)])),...clockFuncs([...CLOCK_FACTORIES,...e.clockFuncs??[]]),...ccCandybarFuncs(),...formatterFuncs(),...n??{}}})}function buildScope(e){return makeProxy(e,new Set(e.names()),``)}function makeProxy(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!absentDocument(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:unwrapDocument(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return makeProxy(e,t,a)}})}function placementScope(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 absentDocument(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function unwrapDocument(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new PendingValueError(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}function digestOf(e){return createHash(`sha256`).update(JSON.stringify(canonical$1(e))).digest(`hex`)}function canonical$1(e){return Array.isArray(e)?e.map(canonical$1):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,canonical$1(t)])):e}const runOf$1=e=>({digest:digestOf(e),identity:e});function keyHashOf(e){return crypto.createHash(`sha256`).update(e).digest(`hex`)}const TORN_WRITE_SETTLE_MS=250;function parseDuration(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]}"`)}}function parserIdOf(e){switch(e.kind){case`text`:return{kind:`text`};case`regex`:return{kind:`regex`,pattern:e.pattern};case`json`:return{kind:`json`}}}const UNBOUND={session:()=>{throw new PendingValueError(`session_id`,`the view's session has no value yet: no view source is bound`)},read:()=>pendingOf(`unread`),run:()=>UNREAD_RUN,drawnAt:()=>{throw new PendingValueError(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}},found=e=>({kind:`found`,value:e});function resolvePath(e,t){let n=e,r=!1;for(let e of t.split(`.`)){if(!r&&isPending(n))return n;if(typeof n!=`object`||!n)return found(void 0);r||=e===`value`&&n.kind===`ok`,n=n[e]}return!r&&isPending(n)?n:found(n)}function sourceReading(e,t){if(t.kind===`pending`)return t;let n=t.value;if(n===void 0)return failed$2(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the config declares`,`read`);switch(typeof n==`object`&&n?n.kind:void 0){case`ok`:case`absent`:case`failed`:return n;default:return failed$2(`variable "${e}": the view's payload holds no source reading at "${e}"`,`read`)}}function coerceToType(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`?toString(e):t===`number`?toNumber(e):toBool(e)}function zeroValue(e){return e===`number`?0:e===`boolean`?!1:``}var SourceRegistry=class e{lastErrors=new Map;policyFaults=import_dist$1.observable.map(void 0,{deep:!1});runFaults=import_dist$1.observable.map(void 0,{deep:!1});cleanups=[];runs=import_dist$1.observable.map(void 0,{deep:!1});runSourcesNow=(0,import_dist$1.computed)(()=>new Map([...this.runs].map(([e,t])=>[e,t.get()])));namedNow=(0,import_dist$1.computed)(()=>new Map([...this.runSourcesNow.get()].flatMap(([e,t])=>t.kind===`ok`?[[e,t.value]]:[])));runSources(){return this.runSourcesNow.get()}namedRuns(){return this.namedNow.get()}subscriptionsNow=(0,import_dist$1.computed)(()=>[...new Map([...this.namedNow.get().values()].map(e=>[e.digest,e]))].sort(([e],[t])=>e<t?-1:+(e>t)).map(([,e])=>e));subscriptions(){return this.subscriptionsNow.get()}inputs=import_dist$1.observable.box(UNBOUND,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=createCcCandybarEngine({drawnAt:this.drawnAt});sourceNames=import_dist$1.observable.array([],{deep:!1});publishedNow=(0,import_dist$1.computed)(()=>({values:this.sourceNames.map(e=>this.store.stored(e)),faults:[...this.policyFaults.values(),...this.runFaults.values()]}));published(){return this.publishedNow.get()}sessionState;constructor(e,t=``,n,r=null,i={}){this.store=e,this.defaultEmptyValue=t,this.parent=r,this.env=i,this.sessionState=n,this.cleanups.push((0,import_dist$1.observe)(this.subscriptionsNow,()=>{}))}view(){return new e(new VariableStore(this.store.clock,this.store),this.defaultEmptyValue,this.sessionState,this,this.env)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,typeOf(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,failed$2(t,`parse`))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>sourceReading(e,this.inputs.get().read(e)))}own(e){this.cleanups.push(e)}declareInput(e,t,n,r,i){this.store.defineDerived(e,n,i,()=>this.inputAt(e,t,n,r))}inputAt(e,t,n,r){let i=this.inputs.get().read(t);if(i.kind===`pending`)throw this.lastErrors.delete(e),new PendingValueError(e,`variable "${e}" has no value yet: its source has not answered`);let a=i.value;if(a===void 0)return this.fallbackOf(e,n,r,`input path "${t}" not found in payload`);try{let t=coerceToType(a,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=this.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,{kind:`shell`,command:t,cwd:n.cwd},n.cache,n.parse)}declareFile(e,t,n){this.declareSource(e,{kind:`file`,path:t,readMode:n.readMode??`whole`},n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r),a=this.registerCachePolicy(e,n),o=(0,import_dist$1.computed)(()=>{let e=a();return e.kind===`ok`?ok$1(runOf$1({read:t,parse:parserIdOf(r),refresh:e.value})):e},{equals:(e,t)=>e.kind===`ok`&&t.kind===`ok`?e.value.digest===t.value.digest:e.kind===t.kind});(0,import_dist$1.runInAction)(()=>{this.sourceNames.push(e),this.runs.set(e,o)}),this.cleanups.push((0,import_dist$1.reaction)(()=>this.runFact(e)?.fault??null,t=>this.noteFault(this.runFaults,e,t===null?ok$1(void 0):failed$2(t,`read`)),{fireImmediately:!0}),(0,import_dist$1.reaction)(()=>this.runFact(e)?.reading,e=>{if(e===void 0||e.kind===`pending`)return;let{at:t,...n}=e;i(n)},{fireImmediately:!0}))}runFact(e){let t=this.runs.get(e)?.get();return t?.kind===`ok`?this.inputs.get().run(t.value.digest):void 0}publisherFor(e,t){switch(t.kind){case`text`:case`regex`:return this.scalarPublisher(e,t.default);case`json`:return this.documentPublisher(e,t.default)}}scalarPublisher(e,t){let n=this.stringInitial(t);return this.store.defineBox(e,`string`,n),t=>{this.noteOutcome(e,t),this.store.setBox(e,orElse(t,n))}}documentPublisher(e,t){let n=t===void 0?pendingOf(`unread`):ok$1(t);this.store.defineDocument(e,n);let r,i=!1;return this.cleanups.push(()=>r?.()),a=>{r?.();let o=a;this.noteOutcome(e,o);let s=o.kind===`ok`||o.kind===`failed`&&o.failedAt===`parse`,c=s||t===void 0?o:n,l=i&&s&&o.kind!==`ok`,u=()=>{i=o.kind===`ok`,this.store.setDocument(e,c)};l?r=this.store.clock.after(250,u):u()}}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(buildScope(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=coerceToType(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=readPending(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`,()=>{let e=n.get(this.session(),t.key);return e===null?r:e})}stateRevision(){return this.sessionState===void 0?0:this.sessionState.revision(this.session())}session(){return this.inputs.get().session()}bindInputs(e){(0,import_dist$1.runInAction)(()=>this.inputs.set(e))}getLastError(e){if(!this.declaredHere(e))return this.parent?.getLastError(e);let t=this.lastErrors.get(e),n=this.standingFault(e);return n===void 0?t:t===void 0||t.message===n.message?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){let e=new Set([...this.policyFaults.keys(),...this.runFaults.keys()]);return new Map([...this.parent?.cachePolicyFaults()??[],...[...e].map(e=>[e,this.standingFault(e)])])}standingFault(e){let t=this.policyFaults.get(e),n=this.runFaults.get(e);return t===void 0||n===void 0?t??n:{timestamp:t.timestamp,message:`${t.message}; ${n.message}`}}declaredHere(e){return this.store.has(e)&&!(this.parent?.store.has(e)??!1)}dispose(){for(let e of this.cleanups)e();return this.cleanups.length=0,this.store.dispose()}registerCachePolicy(e,t){switch(t.kind){case`never`:return()=>ok$1({kind:`never`});case`ttl`:return()=>ok$1({kind:`ttl`,durationMs:t.durationMs});case`watch_file`:return()=>ok$1({kind:`watch_file`,path:t.path});case`key`:{let n=this.engine.parse(t.template);return this.answeredUnder(e,()=>{try{return ok$1(n.evaluate(buildScope(this.store)).map(e=>e.plain).join(``))}catch(e){return readPending(e)===void 0?failed$2(`cache key: ${e instanceof Error?e.message:String(e)}`,`read`):pendingOf(`unread`)}})}case`depends_on`:return this.answeredUnder(e,()=>{let e=t.varNames.map(e=>this.store.changeKey(e));return e.every(e=>e.kind===`ok`)?ok$1(e.map(e=>e.value).join(`,`)):pendingOf(`unread`)})}}answeredUnder(e,t){let n=(0,import_dist$1.computed)(t,{equals:import_dist$1.compareStructural});this.cleanups.push((0,import_dist$1.reaction)(()=>n.get(),t=>this.noteFault(this.policyFaults,e,t),{fireImmediately:!0}));let r;return()=>{let e=n.get();return e.kind===`ok`&&(r=e.value),r===void 0?e.kind===`failed`?e:pendingOf(`unread`):ok$1({kind:`key`,hash:keyHashOf(r)})}}fallbackOf(e,t,n,r){if(this.recordError(e,r),n!==void 0)return n;try{return coerceToType(this.defaultEmptyValue,t)}catch{return zeroValue(t)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:this.store.clock.now(),message:t})}noteFault(e,t,n){(0,import_dist$1.runInAction)(()=>{n.kind===`failed`?e.get(t)?.message!==n.reason&&e.set(t,{timestamp:this.store.clock.now(),message:n.reason}):e.delete(t)})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function evaluateWhen(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const HIDDEN={kind:`hidden`},SHOWN={kind:`shown`};function gateOf(e,t){try{return evaluateWhen(e,t)?SHOWN:HIDDEN}catch(e){let t=readPending(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function collapseToCell(e,t){let n=RichText.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function sizeCell(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function cellParts({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function heldCell({text:e,placement:t,lead:n,trail:r}){return{text:unlinked(e),placement:t,...n!==void 0&&{lead:unlinked(n)},...r!==void 0&&{trail:unlinked(r)}}}function unlinked(e){let t=e.blankCopy(e.plain);t.style=resolvedStyle(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(resolvedStyle(i).clearMetaAndLinks(),n,r);return t}function stripItem(e){let t=cellParts(e);if(t.length===1)return e.text;let n=collapseToCell(t);return n.style=e.text.style,n}function applySegmentLayout(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=collapseToCell(e,a).pad(o),d=new RichText(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:collapseToCell([d,...c],a)},...l.length>0&&{trail:collapseToCell([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(sizeCell(u,n,p),[{text:u,...f}])}function wrapOffsets(e,t,n){let r=`x`.repeat(Math.min(n,t)).replace(/x$/,` `),i=r+e,a=[],o=0;return wrappedLines(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 takenOnLine(e,t){if(e.length===0)return 0;let{lines:n}=drawStripCells(e.map(({owner:e})=>e),t),r=cellLen(plainOf(n[n.length-1]));return Math.max(0,r-stripChromeCols(t)+stripSeamCols(t))}function fits(e,t,n){if(e.cellLength<=t)return!0;let{lines:r}=drawStripCells([e],{...n,width:1/0});return cellLen(plainOf(r.flat()))<=n.width}function dividedToLine(e,t,n,r){if(fits(e.owner,t,r))return[e];let i=e.owner.copy().expandTabs(),a=takenOnLine(n,r);return i.divide(wrapOffsets(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 fitRow(e,t){let n=Math.max(2,lineWidth(t)-stripChromeCols(t)-t.padding);return filled(e,t).reduce((e,r)=>[...e,...dividedToLine(r,n,e,t)],[])}function filled(e,t){let n=()=>e.map(e=>({owner:stripItem(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=drawStripCells(e.map(stripItem),t).lines;if(i.length>1)return n();let a=Math.max(0,t.width-cellLen(plainOf(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];sizeCell(c,c.cellLength+a,n)}),n()}function fragmentsToCells(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=buildCell(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:resolvedStyle(a.style)};if(e.style.link){i();let r=buildCell([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function buildCell(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>withStyle(e.frag,n?n.add(e.style):e.style)),i=RichText.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function withStyle(e,t){let n=e.copy();return n.style=t,n}function renderBinding(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 renderLook(e,t){let{look:n}=renderBinding(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function renderLayout(e,t){let{layout:n}=renderBinding(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function bindRender(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 compileActions(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,compileAction(e,t,o,n,r,i));return i}function compileAction(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=resolveOptionDomain(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=CONFIG_KEY_TO_EFFECTIVE_VAR.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=resolveOptionDomain(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=resolveOptionDomain(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:parseActionTemplate(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:parseActionTemplate(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:runDeclaration(n),argv:n.run.map(n=>parseActionTemplate(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,parseActionTemplate(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:parseActionTemplate(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 presentedAction(e){return e.kind===`do`?presentedAction(e.head):e}function bindsTemplateValue(e){switch(presentedAction(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 parseActionTemplate(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function readVar(e,t){return e.has(t)?toString(e.read(t)):``}function clickSession(e,t){return renderBinding(e,t).registry.session()}function evalTemplate(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function linkFragment(e,t,n,r){let i=new RichText(e,{style:Style.combine([r,new Style({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function linkOver(e,t,n=!1){let r=new Style({link:t,bold:n?!0:void 0}),i=new RichText(e.plain,{style:Style.combine([resolvedStyle(e.style),r])});for(let t of e.spans)i.stylize(Style.combine([resolvedStyle(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function cycleIndex(e,t){return Math.max(e.members.indexOf(readVar(t,e.stateVar)),0)}function realize(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=readVar(r,e.stateVar);return{effects:[{verb:VERB_SET_STATE,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=readVar(r,e.stateVar);return{effects:[{verb:VERB_SET_STATE,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=readVar(r,e.stateVar);return{effects:[{verb:VERB_SET_STATE,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(cycleIndex(e,r)+1)%e.members.length];return{effects:[{verb:VERB_SET_STATE,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:VERB_STEP_STATE,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:VERB_COPY,args:[evalTemplate(e.text,buildScope(r))]}],active:!1};case`open`:return{effects:[{verb:VERB_OPEN_VSCODE,args:[evalTemplate(e.target,buildScope(r))]}],active:!1};case`persist-literal`:{let t=readVar(r,e.stateVar);return{effects:[{verb:VERB_SET_CONFIG,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=readVar(r,e.stateVar);return{effects:[{verb:VERB_SET_CONFIG,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(cycleIndex(e,r)+1)%e.members.length];return{effects:[{verb:VERB_SET_CONFIG,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:VERB_STEP_CONFIG,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:VERB_RESET_CONFIG,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:VERB_UNDO,args:[i]}],active:!1};case`redo`:return{effects:[{verb:VERB_REDO,args:[i]}],active:!1};case`back`:return{effects:[{verb:VERB_BACK,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:VERB_REWIND,args:[i]}],active:!1};case`save`:return{effects:[{verb:VERB_SAVE,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:VERB_SAVE_PRESET,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:VERB_SAVE_THEME_DEFAULT,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:VERB_DELETE_PRESET,args:[i,evalTemplate(e.name,buildScope(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:VERB_DOCTOR_RUN,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:VERB_DOCTOR_FIX,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:VERB_DOCTOR_MARK,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:VERB_SLASH,args:[i,e.line]}],active:!1};case`run`:{let t=buildScope(r),n=JSON.stringify({run:e.argv.map(e=>evalTemplate(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,evalTemplate(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:VERB_APPLY_LAYOUT_OP,args:[i,e.key,encodeLayoutOp(e.op)]}],active:!1};case`do`:{let o=realize(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>realize(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:VERB_APPLY_LAYOUT_OP,args:[i,e.key,encodeLayoutOp(r)]}],active:!1}}}}function selectDisplay(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:pickCycleDisplay(`action "${e}"`,n,t.members.length,cycleIndex(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 renderAction(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=renderBinding(n,`action "${e}"`).store,{display:a,boundValue:o}=selectDisplay(e,presentedAction(r),t,i),s=clickSession(n,`action "${e}"`),{effects:c,active:l}=realize(r,a.plain,o,i,s,n.signer);return linkOver(a,effectsUrl(c),l)}function actionFuncs(e){return{action:{fn:(t,...n)=>renderAction(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function disclosureCloseFragment(e,t){return linkFragment(`✕`,effectsUrl([{verb:VERB_SET_STATE,args:[e,t,DISCLOSURE_CLOSED]}]),!1)}function stateCell(e,t,n){return new Style({bgcolor:ColorSpec.fromRgba(t),color:ColorSpec.fromRgba(textOn(e,t,n))})}function decoratedCell({tint:e,text:t}){return new Style({bgcolor:ColorSpec.fromRgba(e),color:ColorSpec.fromRgba(t)})}function closeOn(e,t,n){return new Style({color:ColorSpec.fromRgba(ensureContrast(e.get(DISCLOSURE_CLOSE_ROLE),t,TEXT_MIN_CONTRAST,n))})}function closeCell(e,t,n){return Style.combine([stateCell(e,t,n),closeOn(e,t,n)])}function bandItemStyle(e,t,n){return decoratedCell(bandItem(e.palette,e.disclosure,t,n))}const SWATCH_GLYPH=`▀`;function swatch(e){let t=ColorSpec.fromRgba(e.get(`background`)),n=RichText.fromFragments(DECOR_HUES.map(n=>new RichText(`▀`,{style:new Style({color:ColorSpec.fromRgba(e.get(n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const cell=(e,t)=>{let n=typeof e==`string`?new RichText(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},currentMark=e=>new Style({bold:e});function optionPaint(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>cell(a,Style.combine([bandItemStyle(e,{...n,distribution:t},i),currentMark(o)]));let o=stateCell(e.palette,a,i);return(e,t,i,a)=>named(i,Style.combine([o,currentMark(a)]),r(t,n))}const named=(e,t,n)=>cell(RichText.fromFragments([cell(e,t),cell(` `,t),swatch(n)]));function labelPaint(e,t,n,r){return t===void 0?cell(r):named(r,void 0,t(n,e))}function swatchPaint(e,t,n,r,i){let a=stateCell(e.palette,i,r);return(e,r,i,o)=>cell(RichText.fromFragments([cell(o?`[`:` `,a),swatch(n(r,t)),cell(o?`]`:` `,a)]))}const LIBRARY_PAGE_ROWS=8;function libraryLayout(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=>chunk(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function chunk(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function fitCells(e,t){return new RichText(e).truncate(t,{marker:`…`}).plain}function createActiveSegmentRef(e){return{current:null,drawnAt:e}}function openSegment(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 inSegment(e,t,n){return publishing(e,()=>n(openSegment(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function outsideSegments(e,t){return publishing(e,()=>(e.current=null,t()))}function publishing(e,t){let n=e.current;try{return t()}finally{e.current=n}}function requireActiveSegment(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}const PICKER_PREV=`←`,PICKER_NEXT=`→`;function cellWidth(e){return new RichText(e).cellLength}function rowBudget(e){let{width:t,chromeCols:n,padding:r}=renderBinding(e,`a row fit`);return Math.max(1,t-n-2*r)}function ledRowBudget(e){let{padding:t,seamCols:n}=renderBinding(e,`a row fit`);return Math.max(1,rowBudget(e)-(cellWidth(`✕`)+2*t+n))}function paginate(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 gridPages(e,t,n){let r=cellWidth(PICKER_PREV)+1+cellWidth(PICKER_NEXT)+1,i=paginate(e,t,n);return(i.length>1?paginate(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function assemble(e){let t=[];for(let n of e)t.length>0&&t.push(new RichText(` `)),t.push(n);let n=RichText.fromFragments(t);return n.overflow=`ignore`,n.end=``,n}function requireKind(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 requireOptionKind(e,t,n){let r=e.compiled.get(t),i=r&&presentedAction(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 renderPicker(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=renderBinding(a,`picker`).store,d=clickSession(a,`picker`),f=`stateVar`in t?readVar(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`?ledRowBudget(a):rowBudget(a):1/0,h=(r.kind===`led`?0:cellWidth(`✕`)+1)+c.reduce((e,t)=>e+cellWidth(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?gridPages(v.map(e=>e.cellLength),m,h):libraryLayout(g.entries,g.groups,i),b=parseInt(readVar(u,n.stateVar),10),x=e=>Math.max(0,y.findIndex(t=>t.some(t=>t.indices.includes(e)))),S=x(f===void 0?-1:t.options.indexOf(f)),C=Number.isInteger(b)?b<0?S:Math.min(b,y.length-1):0,w=y[C]??[],T=e=>effectsUrl([{verb:VERB_SET_STATE,args:[d,n.key,String(e)]}]),E=r.kind===`led`?[]:[{verb:VERB_SET_STATE,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],D=r.kind===`own`&&r.onPick?E:[],O=e=>effectsUrl([...realize(l,e,e,u,d,a.signer).effects,...D]),k=(e,n)=>linkOver(e,O(t.options[n])),A=r.kind===`led`?[]:[linkFragment(`✕`,effectsUrl(E),!1,s)];A.push(...c.map(({glyph:e,option:r})=>linkFragment(e,effectsUrl([...realize(l,r,r,u,d,a.signer).effects,{verb:VERB_SET_STATE,args:[d,n.key,String(x(t.options.indexOf(r)))]}]),!1))),C>0&&A.push(linkFragment(PICKER_PREV,T(C-1),!1));let j=C<y.length-1?[linkFragment(PICKER_NEXT,T(C+1),!1)]:[];if(g===void 0){let e=w.flatMap(e=>e.indices);return[assemble([...A,...e.map(e=>k(v[e],e)),...j])]}let M=new Style({bold:!0}),N=y.length>1?` ${C+1}/${y.length}`:``,F=w.length===1?[new RichText(`${w[0].label}${N}`,{style:M})]:[],ee=[assemble([...A,...F,...j])];for(let e of w){w.length>1&&ee.push(assemble([new RichText(e.label,{style:M})]));let n=Math.max(...e.indices.map(e=>cellWidth(_(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:sanitizeText(i),o=` `.repeat(n-cellWidth(e)+2),s=a===void 0?e:`${e}${o}${a}`;ee.push(assemble([k(p(r,fitCells(s,m)),r)]))}}return ee}function pickerFuncs(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{refuseSurplus(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=requireKind(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=requireOptionKind(e,n,`picker`),u=requireActiveSegment(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=>renderPicker(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,optionPaint(u,placedBy(void 0),renderLook(e,`{{ picker }}`),l.paletteOf,d,t),closeOn(u.palette,t,d)),p=bandFor(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`}}}const CAROUSEL_PREV=`◀`,CAROUSEL_NEXT=`▶`;function ringAround(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function renderCarousel(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=renderBinding(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=clickSession(i,`carousel`),{options:c}=t;if(c.length===0)return assemble([]);let l=ringAround(c,readVar(a,t.stateVar)),u=e=>c[l(e)],d=e=>effectsUrl(realize(o,u(e),u(e),a,s,i.signer).effects);return assemble([linkFragment(`◀`,d(-1),!1),linkOver(labelPaint(renderLook(i,`{{ carousel }}`),t.paletteOf,u(0),r),effectsUrl(realize(i.compiled.get(n),u(0),void 0,a,s,i.signer).effects)),linkFragment(`▶`,d(1),!1)])}function carouselFuncs(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(bindsTemplateValue(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 renderCarousel(t,requireOptionKind(e,t,`carousel`),n,r,e)},argTypes:[`string`,`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const SWATCHES_RANDOM=`?`;function requireSwatchable(e,t,n){let r=requireOptionKind(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 randomOther(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 optionPalette(e,t,n,r){let i=requireSwatchable(e,t,n),a=r??readVar(renderBinding(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,renderLook(e,`{{ ${n} }}`))}function swatchFuncs(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(refuseSurplus(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return swatch(optionPalette(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function swatchesFuncs(e,t,n){return{swatches:{fn:(r,i)=>{let a=requireSwatchable(e,r,`swatches`),o=requireKind(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=requireActiveSegment(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]=renderPicker(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,swatchPaint(s,renderLook(e,`{{ swatches }}`),a.paletteOf,c,s.bg),closeOn(s.palette,s.bg,c),u===0?[]:(()=>{let t=ringAround(l,readVar(renderBinding(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[randomOther(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const BAR_WORDS=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function previewRows(e,t,n,r){let i=bandFor(e,n,r),a=(t,n)=>({text:t,colour:n,ink:textOn(e,n,r)});return[[vocabularyOf(e,t,r).map((n,i)=>{let a=decorEntryColour(e,n);return{text:BAR_WORDS[i%BAR_WORDS.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 renderRow(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new RichText(` ${e} `,{style:decoratedCell({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 RichText(e)),r.push(a)}return r}function renderThemePreview(e,t,n,r,i){let a=previewRows(e,t,n,r).map(e=>renderRow(e,i)),o=RichText.fromFragments(a.flatMap((e,t)=>t===0?e:[new RichText(`
|
|
213
|
+
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=leftBehind(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,[showGlobal(`@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)} ${BINDING_OPTION} 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,INSTALL_QUERIES(n));if(r===null||this.closed)return null;let i=installPlan(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,rowOption(r),e])}),i!==n.status){let e=statusWord(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,WROTE_OPTION,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,commandText(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,RESTORE_QUERIES(n));if(i===null)return;let a=restorePlan(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,ROOT_KEYS);if(r===null||this.closed)return;let i=boundOf(r[0]??``);if(n.kind===`none`&&isClickBinding(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`&&isClickBinding(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...CLICK_KEY,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${tmuxQuoted(`${this.deps.handler} ${clickUrl(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,ROOT_KEYS);if(r===null)return;let i=bindingRestorePlan(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}`)}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,readChain(t));return n.kind===`ok`?answersOf(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,chain(t),n)).kind===`ok`)}};function segmentsOf(e){try{return decodeSegments(e)}catch(e){if(e instanceof URIError)return null;throw e}}const RULE=/^─{20,}/,PROMPT=/^❯(\s|$)/,STASHED=/›\s*stashed$/;function inputBox(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>RULE.test(e)?[t]:[]).at(-2);return n===void 0||!PROMPT.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function promptState(e){if(e.inMode)return{kind:`in-mode`};let t=inputBox(e);return t===null?{kind:`no-prompt`}:STASHED.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function draftShown(e){return/^❯\s*\S/u.test(inputBox(e)?.prompt??``)}const TURN_RUNNING=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function turnRunning(e){return e.screen.some(e=>TURN_RUNNING.test(e))}const REFUSALS={"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 tmuxPaneOf(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 typeSlash(e,t,n){return t.kind===`refused`?t:e(t.hint,n)}const typeInPane=e=>async(t,n)=>{let r=promptState(await e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:REFUSALS[r.kind]};let i=await e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i},keep=e=>({arity:e,keep:!0}),drop=e=>({arity:e,keep:!1}),FLAGS={"--add-dir":keep(`variadic`),"--agent":keep(`one`),"--agents":keep(`one`),"--allow-dangerously-skip-permissions":keep(`none`),"--allowedTools":keep(`variadic`),"--allowed-tools":keep(`variadic`),"--append-system-prompt":keep(`one`),"--autocompact":keep(`one`),"--ax-screen-reader":keep(`none`),"--bg":drop(`none`),"--background":drop(`none`),"--bare":keep(`none`),"--betas":keep(`variadic`),"--brief":keep(`none`),"--chrome":keep(`none`),"--cloud":drop(`optional`),"-c":drop(`none`),"--continue":drop(`none`),"--dangerously-skip-permissions":keep(`none`),"-d":keep(`optional`),"--debug":keep(`optional`),"--debug-file":keep(`one`),"--desktop":drop(`none`),"--disable-slash-commands":keep(`none`),"--disallowedTools":keep(`variadic`),"--disallowed-tools":keep(`variadic`),"--effort":keep(`one`),"--environment":drop(`one`),"--exclude-dynamic-system-prompt-sections":keep(`none`),"--fallback-model":keep(`one`),"--file":keep(`variadic`),"--fork-session":drop(`none`),"--forward-subagent-text":keep(`none`),"--from-pr":drop(`optional`),"-h":drop(`none`),"--help":drop(`none`),"--ide":keep(`none`),"--include-hook-events":keep(`none`),"--include-partial-messages":keep(`none`),"--input-format":keep(`one`),"--json-schema":keep(`one`),"--max-budget-usd":keep(`one`),"--mcp-config":keep(`variadic`),"--model":keep(`one`),"-n":keep(`one`),"--name":keep(`one`),"--no-chrome":keep(`none`),"--no-session-persistence":keep(`none`),"--output-format":keep(`one`),"--permission-mode":keep(`one`),"--permission-prompts":keep(`one`),"--plugin-dir":keep(`one`),"--plugin-url":keep(`one`),"-p":drop(`none`),"--print":drop(`none`),"--prompt-suggestions":keep(`optional`),"--remote-control":keep(`optional`),"--remote-control-session-name-prefix":keep(`one`),"--replay-user-messages":keep(`none`),"--restricted":keep(`none`),"-r":drop(`optional`),"--resume":drop(`optional`),"--safe-mode":keep(`none`),"--session-id":drop(`one`),"--setting-sources":keep(`one`),"--settings":keep(`one`),"--strict-mcp-config":keep(`none`),"--system-prompt":keep(`one`),"--system-prompt-snapshot":keep(`one`),"--teleport":drop(`optional`),"--tmux":drop(`none`),"--tools":keep(`variadic`),"--verbose":keep(`none`),"-v":drop(`none`),"--version":drop(`none`),"-w":drop(`optional`),"--worktree":drop(`optional`)},SESSION_FLAG={resume:`--resume`,fresh:`--session-id`};function sessionArgs(e){return[SESSION_FLAG[e.kind],e.sessionId]}const isFlag=e=>e.startsWith(`-`)&&e!==`-`;function startPlace(e,t){let n=worktreeOf(t);return n===null?{dir:e??t,args:[]}:e!==null&&within$1(e,n.top)?{dir:e,args:[]}:{dir:e===null||worktreeOf(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const within$1=(e,t)=>e===t||e.startsWith(t+path.sep);function relaunchArgs(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!isFlag(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=FLAGS[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=>!isFlag(e)):o.arity===`variadic`?takeWhile(n.slice(r),e=>!isFlag(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 worktreeOf(e){let t=e.split(path.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(path.sep),repo:t.slice(0,n-1).join(path.sep)||path.sep}}function takeWhile(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const BAND_PLUGIN=`candybar-band@cc-candybar`,BAND_CLIENT=path.join(`bin`,`cc-candybar-native`),EXIT_PATIENCE_MS=15e3,ATTACH_PATIENCE_MS=3e4,RELOAD_PLUGINS=slashLine(`/reload-plugins`);async function bandOn(e,t,n,r,i){let a=sourceCheckoutOf(r.bundle);if(a===null)throw new BadVerbArgs(`${LANES.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${r.bundle} — run the daemon from a checkout (mod/README.md)`);let o=path.join(a,BAND_CLIENT);if(!i.fileExists(o))throw new BadVerbArgs(`the band mod starts ${o}, which is not built — run \`just install-rust\` in ${a}`);return installBand(e,t,n,a,i)}async function restartClaude(e,t,n,r){let i=attachLauncherOf(n.preload),a=[n.preload,i].find(e=>!r.fileExists(e));if(a!==void 0)throw new BadVerbArgs(`${LANES.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return restartUnderAttach(e,t,{node:n.node[0],launcher:i,preload:n.preload},r)}async function paneOn(e,t,n){let r=await n.barPanes(e);return r.length>0?`bar pane ${r.join(`, `)} already draws ${e.pane}'s bar`:`opened bar pane ${await n.openBarPane(e,[...t.node,t.bundle,`bar-pane`,e.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${e.pane}`}async function paneOff(e,t){let n=await t.barPanes(e);for(let r of n)await t.closePane(e,r);return n.length===0?`no bar pane draws ${e.pane}'s bar`:`closed bar pane ${n.join(`, `)}`}async function installBand(e,t,n,r,i){let a={sessionId:e.sessionId,projectDir:e.projectDir,claudeConfigDir:e.claudeConfigDir??void 0};await i.claude([`plugin`,`marketplace`,`add`,r],a),await i.claude([`plugin`,`install`,BAND_PLUGIN],a);let o=await typeSlash(n,t,RELOAD_PLUGINS);if(o.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${o.reason} — or type /reload-plugins yourself`);return`installed ${BAND_PLUGIN} from ${r} and typed /reload-plugins into ${o.pane}`}const CARRIED_ENV=new Set([CLAUDE_CONFIG_DIR_ENV,CONFIG_ENV]);function environmentOf(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function restartUnderAttach(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,moduleGraphReaderOf(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}) — ${LANES.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=endingLoses(await r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${LANES.statusline.label} off and on again`);let s=conversationLost(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=relaunchArgs(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=environmentOf(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])=>CARRIED_ENV.has(e)),m=(e,t)=>attachCommandLine(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...sessionArgs(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${EXIT_PATIENCE_MS/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=sessionStartOf(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(startPlace(null,i.cwd),_))}let y=m(startPlace(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 ${ATTACH_PATIENCE_MS/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${STARTED[g.kind](e.sessionId)}, and its statusline follows lane B`}function conversationLost(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 sessionStartOf(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const STARTED={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},UNREADABLE={"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 endingLoses(e){let t=promptState(e);return t.kind===`ready`?turnRunning(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:draftShown(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:UNREADABLE[t.kind]}const OUTLIVES={copy:!1,open:!1,"type-slash":!1,"apply-update":!1,run:!0,"restart-claude":!0,surface:!0},outlives=e=>OUTLIVES[e.kind];function nameOf(e){switch(e.kind){case`copy`:case`open`:case`apply-update`:return e.kind;case`type-slash`:return e.line;case`run`:return`run ${e.action}`;case`restart-claude`:return`lane: statusline on`;case`surface`:return`lane: ${e.surface} ${e.on?`on`:`off`}`}}const paneKey=e=>`${e.socket}\0${e.pane}`,did=e=>({outcome:{kind:`ok`},said:e}),not=e=>({outcome:e,said:e.reason});var Acts=class{inPane=new KeyedSerialQueue;setups=new KeyedSerialQueue;restarting=new Map;performers;constructor(e){this.deps=e;let{lanes:t}=e;this.performers={copy:t=>clickLaunch(e.launch,{bin:`/usr/bin/pbcopy`,stdinInput:t.text,category:`click.pbcopy`},`pbcopy`,`copied`),open:t=>clickLaunch(e.launch,{bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,t.target],category:`click.open`},`open -a "Visual Studio Code"`,`opened ${t.target}`),"type-slash":async e=>{if(this.restarting.has(e.session))return not({kind:`refused`,reason:`a restart holds pane ${e.pane.pane} — click again once it has finished`});let t=await this.typed(e.pane,e.line);return t.kind===`typed`?did(`typed into ${t.pane}`):not({kind:`refused`,reason:t.reason})},run:t=>e.run(t),"apply-update":async()=>(await e.applyUpdate(),did(`applied`)),"restart-claude":e=>this.restart(e.session,e.pane,()=>restartClaude({...e.at,sessionId:e.session},e.pane,t.host,t.edge)),surface:async e=>{switch(e.surface){case`band`:return did(await this.setups.run(e.session,()=>bandOn({...e.at,sessionId:e.session},e.pane,(e,t)=>this.typed(e,t),t.host,t.edge)));case`pane`:return did(await this.setups.run(e.session,()=>this.inPane.run(paneKey(e.pane),()=>e.on?paneOn(e.pane,t.host,t.edge):paneOff(e.pane,t.edge))))}}}}typed(e,t){return this.inPane.run(paneKey(e),()=>this.deps.type(e,t))}async perform(e){let{outcome:t,said:n}=this.deps.closing()?not({kind:`closing`,reason:`the daemon is closing`}):await this.performed(e);return this.deps.log(t.kind===`ok`||t.kind===`closing`?`info`:`warn`,`act kind=${e.kind} sid=${valueOf$1(e.session??`-`)} id=${e.id} outcome=${t.kind} — ${nameOf(e)}: ${n}`),t.kind===`ok`?t:{...t,reason:`${nameOf(e)}: ${t.reason}`}}async performed(e){try{return await this.performers[e.kind](e)}catch(e){let t=failureOf(e);switch(t.kind){case`bad-request`:return not({kind:`refused`,reason:t.message});case`closing`:return not({kind:`closing`,reason:t.message});default:return not({kind:`failed`,reason:t.message})}}}async restart(e,t,n){this.restarting.set(e,(this.restarting.get(e)??0)+1);try{return did(await this.setups.run(e,()=>this.inPane.run(paneKey(t),n)))}finally{let t=this.restarting.get(e)-1;t===0?this.restarting.delete(e):this.restarting.set(e,t)}}};const ABSENT={kind:`absent`};function parse$1(e){if(e===null||/^\s*$/.test(e))return{kind:`none`};try{return{kind:`document`,root:parseDocument(e)}}catch(e){if(!(e instanceof Json5EditError))throw e;return{kind:`unparsed`}}}function readAt(e,t,n){return e===null?ABSENT:n.length===0||t.kind!==`document`?{kind:`file`,text:e}:readOf(e,nodeAt(t.root,n))}function readOf(e,t){return t===void 0?ABSENT:{kind:`value`,text:movableTextOf(e,t)}}function sameRead(e,t){return e.kind===`value`&&t.kind===`value`?sameValue(import_lib.default.parse(e.text),import_lib.default.parse(t.text)):e.kind===`file`&&t.kind===`file`?e.text===t.text:e.kind===`absent`&&t.kind===`absent`}function sameValue(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Array.isArray(e)!==Array.isArray(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&sameValue(e[n],t[n]))}function diffChanges(e,t){if(e===t)return[];if(e===null)return[{op:`insert`,at:[],text:t,precedes:null}];let n={kind:`file`,text:e};if(t===null)return[{op:`remove`,at:[],read:n}];let r=[{op:`replace`,at:[],text:t,read:n}],i=parse$1(e),a=parse$1(t);if(i.kind!==`document`||a.kind!==`document`)return r;let o=diffNode([],e,i.root,t,a.root),s=applyChanges(e,o);return s.kind===`applied`&&s.text===t?o:r}function diffNode(e,t,n,r,i){let a=textOf$1(r,i);if(textOf$1(t,n)===a)return[];let o=e.length===0?[{op:`replace`,at:e,text:r,read:{kind:`file`,text:t}}]:[{op:`replace`,at:e,text:movableTextOf(r,i),read:readOf(t,n)}];if(n.kind!==`object`||i.kind!==`object`)return o;let s=diffMembers(e,t,n,r,i);return rebuilds(t,s,e,a)?s:o}function rebuilds(e,t,n,r){let i=applyChanges(e,t);if(i.kind!==`applied`)return!1;let a=parse$1(i.text);if(a.kind!==`document`)return!1;let o=nodeAt(a.root,n);return o!==void 0&&textOf$1(i.text,o)===r}function diffMembers(e,t,n,r,i){let a=new Map(n.entries.map(e=>[e.key,e.value])),o=new Set(i.entries.map(e=>e.key)),s=n.entries.filter(e=>!o.has(e.key)).map(n=>({op:`remove`,at:[...e,n.key],read:readOf(t,n.value)})),c=i.entries.map((e,t)=>i.entries.slice(t+1).find(e=>a.has(e.key))?.key??null),l=i.entries.flatMap((n,i)=>{let o=a.get(n.key);return o===void 0?[{op:`insert`,at:[...e,n.key],text:movableTextOf(r,n.value),precedes:c[i]}]:diffNode([...e,n.key],t,o,r,n.value)});return[...s,...l]}function applyChanges(e,t){let n=e;for(let e of t){let t=parse$1(n),r=movedAncestor(t,e.at);if(r!==null)return{kind:`moved`,at:r,read:`object`,found:readAt(n,t,r)};let i=e.op===`insert`?ABSENT:e.read,a=readAt(n,t,e.at);if(!sameRead(a,i))return{kind:`moved`,at:e.at,read:i,found:a};n=applied(n,e)}return{kind:`applied`,text:n}}function movedAncestor(e,t){if(t.length===0)return null;if(e.kind!==`document`)return[];for(let n=0;n<t.length;n++){let r=t.slice(0,n);if(nodeAt(e.root,r)?.kind!==`object`)return r}return null}function applied(e,t){if(t.at.length===0)return t.op===`remove`?null:t.text;switch(t.op){case`replace`:return setValue(e,t.at,t.text,JSON5_DIALECT);case`insert`:return insertValue(e,t.at,t.text,JSON5_DIALECT,t.precedes);case`remove`:return deleteValue(e,t.at,t.at.length-1)}}function addressText(e){return e.length===0?`the whole file`:e.join(`.`)}const REPO_ANSWERS=[`approved`,`declined`];function answerDir(e){return e.link.kind===`linked`?e.link.main:e.dir}const answerOf$1=(e,t)=>Object.hasOwn(e,t)?e[t]:null;function ruling(e,t){let n=answerDir(t);if(e.kind===`failed`)return{standing:`unread`,under:n};let r=answerOf$1(e.value,n),i=answerOf$1(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 gateRepos(e,t,n){let r=[...new Map([...t,...n?.ships?[n]:[]].map(e=>[e.dir,e])).values()],i=r.map(t=>({dir:t.dir,...ruling(e,t)})),a=e=>i.filter(t=>t.standing===e),o=e=>[...new Set(a(e).map(e=>e.under))];return{plugins:n!==null&&ruling(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 withAnswer(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 parseRepoConfigBook(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(!REPO_ANSWERS.includes(n))return{kind:`failed`,reason:`answers ${JSON.stringify(t)} ${JSON.stringify(n)}, not ${REPO_ANSWERS.join(` or `)}`};return{kind:`ok`,value:e}}function repoUnreadNotice(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 repoGateLines(e){let t=repoUnreadNotice(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}`)]}function presence(e){try{return fs.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const textOf=e=>`${JSON.stringify(e,null,2)}\n`;function stateFile(e,t,n,r){let i=path.join(e,t),a=()=>{let e;try{e=fs.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}`}},o=e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return{kind:`ok`,value:{file:i,text:n===t.value?null:textOf(n),value:n}}};return{read:a,plan:o,update:e=>written$1(o(e))}}function written$1(e){if(e.kind===`failed`)return e;let{file:t,text:n,value:r}=e.value;return n!==null&&writeAtomic(t,n),{kind:`ok`,value:r}}const REPO_CONFIGS_FILE=`repo-configs.json`,REPO_CONFIGS_DIR=`repo-configs`;function repoConfigsDir(e){return path.join(e,REPO_CONFIGS_DIR)}function repoConfigsPath(e){return path.join(repoConfigsDir(e),REPO_CONFIGS_FILE)}const repoConfigs=e=>{let t=stateFile(repoConfigsDir(e),REPO_CONFIGS_FILE,{},parseRepoConfigBook),n=stateFile(e,REPO_CONFIGS_FILE,{},parseRepoConfigBook),r=()=>fs.existsSync(repoConfigsPath(e)),i=e=>{if(r())return t.plan(e);let i=n.read();return i.kind===`failed`?i:t.plan(()=>e(i.value))};return{read:()=>(r()?t:n).read(),plan:i,update:e=>written$1(i(e))}};function answering(e,t,n){let r=Object.keys(e).filter(e=>e!==t).map(e=>({d:e,found:presence(e)})),i={superseded:r.filter(({d:e,found:n})=>n===`present`&&answerDir({dir:e,link:worktreeLink(e)})===t).map(({d:e})=>e),absent:r.filter(({found:e})=>e===`absent`).map(({d:e})=>e),unchecked:r.flatMap(({found:e})=>typeof e==`object`?[e]:[])};return{book:withAnswer(e,t,n,i.superseded),recorded:i}}function answeredBook(e,t){let n=[],r=repoConfigs(e).plan(e=>t.reduce((e,{session:t,dir:r,answer:i})=>{let a=answering(e,r,i),{superseded:o,absent:s,unchecked:c}=a.recorded;return n.push(`repo-config: ${r} ${i} superseded=${o.join(`,`)||`-`} absent=${s.join(`,`)||`-`} unchecked=${c.length===0?`-`:JSON.stringify(c)} (session=${t})`),a.book},e));return r.kind===`failed`?r:ok$1({...r.value,said:n})}function repoAnswerFields(e,t,n){return{sessionId:e,action:VERB_REPO_CONFIG,declaration:t,evaluated:n}}function repoQuestions(e,t,n){return e.awaiting.map(e=>{let r=`a cc-candybar config for ${e} — run it?`,i=REPO_ANSWERS.map(r=>diagnosticSpan(`[${r===`approved`?`approve`:`decline`}]`,effectsUrl([{verb:VERB_REPO_CONFIG,args:[t,e,r,n.sign(repoAnswerFields(t,e,r))]}]))),a=[diagnosticSpan(r,null),...i];return{severity:APPROVAL_SEVERITY,about:`repo-question\0${e}`,message:r,copy:r,lines:[a]}})}function pluginRoots(e,t){let n=[...[...e.dataDirs].reverse().map(e=>path.join(e,`cc-candybar`,`plugins`)),userPluginRoot(e)];return[...n.filter((e,t)=>n.lastIndexOf(e)===t).map(e=>({dir:e,scope:`plugins`})),...t===null?[]:[{dir:path.join(t,REPO_PLUGIN_DIR),scope:`repo`}]]}function userPluginRoot(e){return path.join(e.dataHome,`cc-candybar`,`plugins`)}const REPO_PLUGIN_DIR=path.join(`.cc-candybar`,`plugins`);function installedPlugins(e,t){let n=pluginRoots(e,t),r=new Map,i=[],a=[];for(let{dir:e,scope:t}of n){let n=listFolders(e);if(`error`in n){i.push(n);continue}for(let i of n.folders){let n=pluginDefinition(path.join(e,i,DEFINITION_FILE),t),a=`${t}\0${i}`;r.delete(a),r.set(a,n)}for(let r of n.files)a.push({path:path.join(e,r),scope:t,name:void 0,reason:`a plugin is a folder holding its ${DEFINITION_FILE}: move this file to ${path.join(e,`<name>`,DEFINITION_FILE)}`})}return{roots:n.map(e=>e.dir),definitions:[...r.values()],unchecked:i,strays:a}}function listFolders(e){try{let t=fs.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()||isDirectoryLink(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 isDirectoryLink(e,t){if(!t.isSymbolicLink())return!1;try{return fs.statSync(path.join(e,t.name)).isDirectory()}catch{return!0}}const CONFIG_EXTENSIONS=[`json5`,`json`];function configLocations(e,t){return[...t?[{role:`local`,base:path.join(t,PROJECT_BASES.local)},{role:`project`,base:path.join(t,PROJECT_BASES.project)}]:[],{role:`user`,base:xdgConfigBase(e)}]}function configCandidates(e,{projectDir:t,configFile:n}){return n===void 0?configLocations(e,t).flatMap(({role:e,base:t})=>CONFIG_EXTENSIONS.map(n=>({file:`${t}.${n}`,role:e}))):[{file:n,role:`user`}]}function dslConfigCandidatePaths(e,t){return configCandidates(e,t).map(({file:e})=>e)}const PROJECT_BASES={project:`.cc-candybar`,local:`.cc-candybar.local`};function isLocalConfigFile(e){return CONFIG_EXTENSIONS.some(t=>path.basename(e)===`${PROJECT_BASES.local}.${t}`)}function xdgConfigBase(e){return path.join(e.configHome,`cc-candybar`,`config`)}const scopeOf=e=>e===`user`?`plugins`:`repo`;function homeLayer(e){return{path:e,role:`user`}}function resolveDslConfig(e,t,n){let{projectDir:r,configFile:i}=n,a=[],o=new Map;for(let{file:t,role:r}of configCandidates(e,n)){let e=presence(t);if(e===`absent`)continue;if(e!==`present`){a.push(e);continue}let n=fs.realpathSync.native(path.dirname(t)),i=path.join(n,path.basename(t).replace(/\.(json5|json)$/,``));o.has(i)||o.set(i,{file:t,role:r,repo:r===`user`?null:{dir:n,link:worktreeLink(n)}})}let s=[...o.values()],c=gateRepos(t,[...new Map(s.flatMap(e=>e.repo===null?[]:[[e.repo.dir,e.repo]])).values()],repoProject(r)),l=s.filter(e=>e.repo===null||c.approved.includes(e.repo.dir)).reverse().map(e=>({path:e.file,role:e.role}));if(i===void 0)return{kind:`chain`,layers:l,home:userHome(e,l),unchecked:a,repos:c};let[u]=a,d=i;return l.length>0?{kind:`chain`,layers:l,home:d,unchecked:a,repos:c}:u===void 0?{kind:`missing`,path:i,home:d,repos:c}:{kind:`unreadable`,...u,home:d,repos:c}}function isUserFile(e,t){return CONFIG_EXTENSIONS.some(n=>t===`${xdgConfigBase(e)}.${n}`)}function repoProject(e){if(e===void 0||presence(e)!==`present`)return null;let t=listFolders(path.join(e,REPO_PLUGIN_DIR)),n=fs.realpathSync.native(e);return{dir:n,link:worktreeLink(n),path:e,ships:!(`error`in t)&&t.folders.length>0}}function userHome(e,t){return t.find(t=>isUserFile(e,t.path))?.path??`${xdgConfigBase(e)}.${CONFIG_EXTENSIONS[0]}`}const rank=e=>LAYER_ROLES.indexOf(e);function writeLayer(e,t,n,r){return writeLayers(e,t,n)[r]}function writeLayers(e,t,n){let r=resolveDslConfig(e,t,n),i=r.kind===`chain`?r.layers:[],a=LAYER_ROLES.flatMap(e=>{let t=placeOf$1(r,i,n,e);return t.kind===`at`?[{path:t.path,role:e}]:[]}),o=t=>{let o=placeOf$1(r,i,n,t);return o.kind===`refused`?o:{kind:`layer`,path:o.path,role:t,below:a.filter(e=>rank(e.role)<rank(t)),above:a.filter(e=>rank(e.role)>rank(t)),repo:r.repos.plugins,cwd:n.cwd??null,locs:e}};return Object.fromEntries(LAYER_ROLES.map(e=>[e,o(e)]))}function placeOf$1(e,t,{projectDir:n,configFile:r},i){return i===`user`?{kind:`at`,path:e.home}:r===void 0?n===void 0||e.repos.plugins===null?refused(`the ${i} layer is the project's, and this session has no approved project`):{kind:`at`,path:t.find(e=>e.role===i)?.path??`${path.join(n,PROJECT_BASES[i])}.${CONFIG_EXTENSIONS[0]}`}:refused(`${r} is the session's one config layer (it was named explicitly), so there is no ${i} layer to write`)}const refused=e=>({kind:`refused`,why:e});function writableRoles(e,t){let n=e.kind===`chain`?e.layers:[];return LAYER_ROLES.filter(r=>placeOf$1(e,n,t,r).kind===`at`)}function configResolutionNotice(e){return noticeLines(e).join(`
|
|
214
|
+
`)||null}function noticeLines(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 detectConfigCollisions(e,t){let n=dslConfigCandidatePaths(e,{projectDir:t}).filter(e=>presence(e)===`present`),r=new Map;for(let e of n){let t=path.dirname(e),n=path.basename(e).replace(/\.(json5|json)$/,``),i=path.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`}const writeText=(e,t)=>t===null?fs.rmSync(resolvedTarget(e),{force:!0}):writeAtomic(e,t),said=e=>e===`object`?`an object`:e.kind===`absent`?`nothing`:e.kind===`file`?`the file as it was read`:e.text;function performChanges(e,t){let n=new Map,r=[];try{for(let{target:t,changes:r}of e){let e=resolvedTarget(t.path),i=n.get(e),a=i===void 0?readConfigText(e):i.was,o=applyChanges(i===void 0?a:i.will,r);if(o.kind===`moved`)return{kind:`refused`,reason:`${addressText(o.at)} in ${e} changed since it was read (it was ${said(o.read)}, it is ${said(o.found)}) — nothing was written`};n.set(e,{file:e,was:a,will:o.text})}for(let{file:e,was:t,will:r}of[...n.values()]){if(t!==null||r===null||!isLocalConfigFile(e))continue;let i=excludeRewrite(e,n);if(i.kind===`failed`)return{kind:`failed`,reason:`${e} could not be kept out of git: ${i.reason} — nothing was written`};i.kind===`ok`&&n.set(i.value.file,i.value)}if(t!==null&&t.answers.length>0){let e=answeredBook(t.stateDir,t.answers);if(e.kind===`failed`)return{kind:`failed`,reason:`the repository answers were not recorded: ${e.reason} — nothing was written`};let{file:i,text:a}=e.value;if(r=e.value.said,a!==null){let e=resolvedTarget(i);n.set(e,{file:e,was:readConfigText(e),will:a})}}}catch(e){return{kind:`failed`,reason:`config read failed: ${message(e)}`}}let i=[];try{for(let e of n.values())writeText(e.file,e.will),i.push(e);for(let e of r)t.said(e);return{kind:`ok`}}catch(e){return{kind:`failed`,reason:putBack(i,e)}}}function excludeRewrite(e,t){let n=gitRootOf(path.dirname(e));if(n===void 0)return ABSENT$2;let r=sharedExcludeOf(n);if(r.kind!==`ok`)return r.kind===`absent`?ABSENT$2:r;let i=resolvedTarget(r.value),a=t.get(i),o=a===void 0?readConfigText(i):a.was,s=a===void 0?o??``:a.will??``,c=`/${path.relative(n,e).split(path.sep).join(`/`).replace(/[\\*?[]/g,`\\$&`)}`;return s.split(`
|
|
215
|
+
`).some(e=>e.trimEnd()===c)?ABSENT$2:ok$1({file:i,was:o,will:`${s}${s===``||s.endsWith(`
|
|
216
|
+
`)?``:`
|
|
217
|
+
`}${c}\n`})}function putBack(e,t){let n=`config write failed: ${message(t)}`;try{for(let{file:t,was:n}of[...e].reverse())writeText(t,n);return`${n} — nothing was written`}catch(e){return`${n}; and putting back what was written failed, so it is half-written: ${message(e)}`}}const message=e=>e instanceof Error?e.message:String(e),performed=e=>e.kind!==`present`&&e.kind!==`change`&&e.kind!==`approve-repo`;function rendererHost(e,t,n,r,i,a){let o=async e=>{let o=sessionOf(e.event),s=o===null?()=>{}:i.holding(o);try{let o=t.monotonic(),{subscriptions:s,turnMs:l,...u}=await n.answer(e),d={...u,hopMs:elapsedMs(t,o)-l},f=d.effects.filter(e=>e.kind===`change`),p=d.effects.filter(e=>e.kind===`approve-repo`),m=a.closing()?{kind:`closing`,reason:`the daemon is closing`}:f.length+p.length===0?{kind:`ok`}:performChanges(f,{stateDir:a.stateDir,answers:p,said:e=>r(`info`,e)}),h=m.kind===`ok`||m.kind===`closing`?m:{kind:`skipped`,reason:`not performed: ${m.reason}`},g=[],_=Promise.resolve();for(let t of d.effects)if(t.kind===`present`)e.event.kind!==`request`&&g.push(c(t,{kind:`failed`,reason:`a ${e.event.kind} turn answers no request`}));else if(t.kind===`change`||t.kind===`approve-repo`)g.push(c(t,m));else{let e=m.kind===`ok`?_.then(()=>a.perform(t)):Promise.resolve(h),n=e.then(e=>c(t,e));outlives(t)||(g.push(n),_=e)}return i.subscribed(s),{...d,settled:await Promise.all(g)}}finally{s()}},s=e=>o(e).catch(e=>({kind:`threw`,failure:failureOf(e),record:[],effects:[],hopMs:null,settled:[]})),c=async(e,n)=>{let r=performed(e)&&(n.kind===`failed`||n.kind===`refused`);r&&e.session===null&&a.unheard(n.reason);let i=await u({kind:`event`,at:instantAt(t),event:{kind:`effect-done`,session:e.session,of:e.id,outcome:n}},[[`effect`,String(e.id)]]);return r&&e.session!==null&&i.kind===`threw`&&i.failure.kind===`down`&&a.unheard(n.reason),n},l=(t,n,i)=>{let a=sessionOf(t.event),o=[[`renderer`,e],[`input`,t.event.kind],...a===null?[]:[[`sid`,a]],...n];switch(i.kind){case`answered`:i.record.length>0&&r(`info`,eventLine(`turn`,[...o,...i.record]));return;case`threw`:if(i.failure.kind===`down`)return;r(LEVEL[i.failure.kind],eventLine(`turn`,[...o,...i.record,[`error`,i.failure.detail]]))}},u=async(e,t)=>{let n=await s(e);return l(e,t,n),n},d=async(t,r)=>{let i=await n.answer({kind:`adapter`,push:t,at:r}).catch(e=>({kind:`threw`,failure:failureOf(e)}));if(i.kind===`threw`)throw new CrossedFailure({...i.failure,message:`renderer ${e} push ${t.kind} threw: ${i.failure.message}`,detail:`renderer ${e} push ${t.kind} threw: ${i.failure.detail}`});if(i.reply.kind!==t.kind)throw Error(`renderer ${e} answered push ${t.kind} with a ${i.reply.kind} reply`);return i.reply};return{name:e,answer:s,deliver:u,ask:d,tell:(e,t)=>void d(e,t).catch(e=>{let t=failureOf(e);t.kind!==`down`&&r(`error`,t.detail)})}}function sessionOf(e){switch(e.kind){case`start`:return null;case`config`:case`request`:return e.context.hookData.session_id;case`world-state`:return e.worldState.session;case`click`:return e.session?.ok?e.session.id:null;case`retire`:case`effect-done`:case`menu-idle`:return e.session}}function encodeRenderOrigin({projectDir:e,cwd:t,target:n}){return JSON.stringify({projectDir:e,cwd:t,configFile:n.path??null,source:n.source})}const SESSION_RENDER_ORIGIN_KEY=`render-origin`,SESSION_CLIENT_HINTS_KEY=`client-hints`;function applyStyleToFragment(e,t){let n=asFragment(e),r=n.copy();return r.style=layerStyle(n.style,t),r}function asFragment(e){if(!(e instanceof RichText))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function attrFunc(e){return{fn:(t=>applyStyleToFragment(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function colorSinkFunc(e){return{fn:((t,n)=>applyStyleToFragment(n,new Style({[e]:ColorSpec.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function attrStyle(e,t){return new Style({[e]:t})}function attributeFuncs(){let e={};for(let t of ATTRIBUTE_NAMES)e[t]=attrFunc(attrStyle(t,!0)),e[`not_${t}`]=attrFunc(attrStyle(t,!1));for(let[t,n]of Object.entries(ATTRIBUTE_SHORT_ALIASES))e[t]=attrFunc(attrStyle(n,!0));return e}const styleSpecFunc={fn:((e,t)=>applyStyleToFragment(t,Style.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},linkFunc={fn:((e,t)=>applyStyleToFragment(t,new Style({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function richTextStyleFuncs(){return{fg:colorSinkFunc(`color`),bg:colorSinkFunc(`bgcolor`),...attributeFuncs(),link:linkFunc,style:styleSpecFunc}}function asColor(e,t){let n;try{n=parseHexColor(e.trim())}catch(n){throw n instanceof ColorParseError?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 computable(n,t,JSON.stringify(e))}function computable(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 colorFunc(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function asAmount(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 darkenFunc=colorFunc([`string`,`int`],((e,t)=>darken(asColor(e,`darken`),t).hex)),lightenFunc=colorFunc([`string`,`int`],((e,t)=>darken(asColor(e,`lighten`),-t).hex)),MIX_PCT_MAX=100,MIX_RANGE={min:0,max:MIX_PCT_MAX,note:`0 = from, 100 = toward`},mixFunc=colorFunc([`string`,`string`,`float`],((e,t,n)=>blendRgb(asColor(e,`mix`),asColor(t,`mix`),asAmount(n,`mix`,`percentage`,MIX_RANGE)/MIX_PCT_MAX).hex)),RATIO_RANGE={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},contrastOnFunc=colorFunc([`string`],(e=>contrastFor(asColor(e,`contrastOn`)).hex)),TRUECOLOR={depth:ColorDepth.TRUECOLOR},readableOnFunc=e=>colorFunc([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return ensureContrast(asColor(t,`readableOn`),asColor(n,`readableOn`),asAmount(r,`readableOn`,`ratio`,RATIO_RANGE),i,void 0,a).hex})),OKLCH_AXIS_FUNCS={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function oklchAxisFuncs(){let e={};for(let[t,n]of Object.entries(OKLCH_AXIS_FUNCS)){let r=t;e[n]=colorFunc([`string`,`float`],((e,t)=>{let i={...IDENTITY,[r]:asAmount(t,n,`amount`)};return Oklch.fromRgba(asColor(e,n)).applyKey(i).toRgba().hex}))}return e}function colorFuncs(e=()=>TRUECOLOR){return{darken:darkenFunc,lighten:lightenFunc,mix:mixFunc,contrastOn:contrastOnFunc,readableOn:readableOnFunc(e),...oklchAxisFuncs()}}function colorStops(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:computable(resolveColorRef(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function paletteFuncs(e){return{color:{fn:(t=>resolveColorRef(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new ColorRamp(parseEase(n),colorStops(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}const HOST_CLOCK=Timeline.play(0);function pairs(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 GLYPH_EFFECTS={...GLYPH_EFFECT_CATALOGUE.loops,typewriter:e=>GLYPH_EFFECT_CATALOGUE.transitions.typewriter(e).effect,scramble:e=>GLYPH_EFFECT_CATALOGUE.transitions.scramble(e).effect,backspace:e=>GLYPH_EFFECT_CATALOGUE.transitions.backspace(e).effect,scrambleOut:e=>GLYPH_EFFECT_CATALOGUE.transitions.scrambleOut(e).effect};function glyphEffect(e){if(!Object.hasOwn(GLYPH_EFFECTS,e))throw RangeError(`unknown glyph effect ${JSON.stringify(e)}; expected one of ${Object.keys(GLYPH_EFFECTS).map(e=>JSON.stringify(e)).join(`, `)}`);return GLYPH_EFFECTS[e]}function animationFuncs(e,t={}){let n=t.timeline??(()=>HOST_CLOCK),r=(e,t,r)=>[Timeline.run(n(),t),finiteTime(e,r.time)],i=(t,n)=>{let i=e(),[a,o]=r(t,n,i),s=shownAt(a,o,i);return i.onHold?.(holdOf(s,o)),s.value},a=(e,t)=>Timeline.run(Timeline.play(e),t);return{frames:{fn:((...t)=>{let n=pairs(`frame`,t,asFragment).map(({seconds:e,value:t})=>({seconds:e,text:t})),i=e();return textFrameAt(...r(`frames`,new FrameSequence(n),i),i)}),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...e)=>{let t=pairs(`color`,e,e=>asColor(e,`stepped`));return t[i(`stepped`,beat(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,tween(r,o,{seconds:e,ease:parseEase(t)})))),argTypes:[`float`,`string`,`float`,`float`,`float`],arity:{kind:`exact`},returnType:`float`},loop:{fn:((e,t)=>i(`loop`,a(t,Animation.continuous(Phase.loop(e))))),argTypes:[`float`,`float`],arity:{kind:`exact`},returnType:`float`},glyphs:{fn:((t,n,i)=>{let o=glyphEffect(t),s=asFragment(i),c=s.plain,l=e();return textFrameAt(...r(`glyphs`,a(n,reglyphText(s,o({z:cellSeed(c,0,0)}),{key:c,asciiOnly:l.asciiOnly===!0})),l),l)}),argTypes:[`string`,`float`,`liftable`],arity:{kind:`exact`},returnType:`T`}}}function richTextFuncs(e){return{...richTextStyleFuncs(),...colorFuncs(e)}}const FALLBACK_ERROR_STYLE=new Style({color:`red`,dim:!0}),CLAUDE_MODEL_PATTERN=/^(?:(?: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,FRIENDLY_MODEL_PATTERN=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function formatModelName(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(CLAUDE_MODEL_PATTERN);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(FRIENDLY_MODEL_PATTERN);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 shortenModelName(e){let t=e.match(FRIENDLY_MODEL_PATTERN);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 abbreviatePath(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 formatInteger(e){return e.toLocaleString()}function parseCascadeStops(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 cascadeAt(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 SPARK_LEVELS=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],LEVELS=SPARK_LEVELS.length;function renderSparkline(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*(LEVELS-1));o+=SPARK_LEVELS[t]}return o}function parseSeries(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 refuseSurplus(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 THEMES_LIST=listResolvablePaletteNames(),ENDCAPS_LIST=[...ENDCAPS_SHAPES];function ccCandybarFuncs(){return{basename:{fn:e=>basename(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>dirname(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>abbreviatePath(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(toNumber(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>toString(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>toBool(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>THEMES_LIST,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>ENDCAPS_LIST,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(refuseSurplus(`sparkline`,[`width`],n),renderSparkline(parseSeries(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>cascadeAt(e,parseCascadeStops(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}const MIN_PROJECTABLE_ELAPSED_MS=300*1e3;function etaMinutes(e,t,n,r){let i=n*6e4-(t*1e3-r);if(i<MIN_PROJECTABLE_ELAPSED_MS||e<=0)return-1;let a=e/i;return Math.max(0,Math.round((100-e)/a/6e4))}const relativeTimeFuncs=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)=>etaMinutes(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function formatterFuncs(){return{formatInteger:{fn:e=>formatInteger(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>formatModelName(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>shortenModelName(e),argTypes:[`string`],arity:{kind:`exact`}}}}let drawing=null;function bindClock(e,t){if(drawing!==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 drawing=n,{heard:()=>n.soonest,[Symbol.dispose]:()=>{drawing=null}}}function drawInProgress(e){if((0,import_dist$1._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(drawing===null)throw Error(`the clock was read outside a draw (${e})`);return drawing}const CLOCK={now:()=>dateOf(drawInProgress(`now`).at),frame:()=>drawInProgress(`frame`).frame,timeline:()=>drawInProgress(`timeline`).timeline};function animationPair(e,t){let{frames:n,stepped:r}=animationFuncs(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 SPRIG_CLOCK_READERS=new Set([`now`,`ago`]);function sprigDatetimeWhere(e,t){return Object.fromEntries(Object.entries(sprigDatetime(e)).filter(([e])=>SPRIG_CLOCK_READERS.has(e)===t))}const SPRIG_DATE_FUNCS=sprigDatetimeWhere(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),CLOCK_FACTORIES=[e=>sprigDatetimeWhere(e.now,!0),e=>animationPair(e.frame,e.timeline),e=>Object.fromEntries(Object.entries(animationPair(e.frame)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),relativeTimeFuncs];function clockFuncs(e){return Object.assign({},...e.map(e=>e(CLOCK)))}const CLOCK_FUNCTIONS=new Set(Object.keys(clockFuncs(CLOCK_FACTORIES)));function engineClockFunctions(e){return new Set([...CLOCK_FUNCTIONS,...Object.keys(clockFuncs(e))])}const DEPTH_BINDINGS={readableOn:readableOnFunc};function createCcCandybarEngine(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return createEngine({fromString:e=>new RichText(e),toString:e=>e.plain,isT:e=>e instanceof RichText,missingKey:`error`,funcs:{...sprigDefaults(),...sprigStrings(),...sprigLists(),...sprigMath(),...sprigConversions(),...sprigFlow(),...sprigDicts(),...SPRIG_DATE_FUNCS,...richTextFuncs(r),...Object.fromEntries(Object.entries(DEPTH_BINDINGS).map(([e,t])=>[e,t(r)])),...clockFuncs([...CLOCK_FACTORIES,...e.clockFuncs??[]]),...ccCandybarFuncs(),...formatterFuncs(),...n??{}}})}function buildScope(e){return makeProxy(e,new Set(e.names()),``)}function makeProxy(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!absentDocument(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:unwrapDocument(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return makeProxy(e,t,a)}})}function placementScope(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 absentDocument(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function unwrapDocument(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new PendingValueError(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}function digestOf(e){return createHash(`sha256`).update(JSON.stringify(canonical$1(e))).digest(`hex`)}function canonical$1(e){return Array.isArray(e)?e.map(canonical$1):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,canonical$1(t)])):e}const runOf$1=e=>({digest:digestOf(e),identity:e});function keyHashOf(e){return crypto.createHash(`sha256`).update(e).digest(`hex`)}const TORN_WRITE_SETTLE_MS=250;function parseDuration(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]}"`)}}function parserIdOf(e){switch(e.kind){case`text`:return{kind:`text`};case`regex`:return{kind:`regex`,pattern:e.pattern};case`json`:return{kind:`json`}}}const UNBOUND={session:()=>{throw new PendingValueError(`session_id`,`the view's session has no value yet: no view source is bound`)},read:()=>pendingOf(`unread`),run:()=>UNREAD_RUN,drawnAt:()=>{throw new PendingValueError(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}},found=e=>({kind:`found`,value:e});function resolvePath(e,t){let n=e,r=!1;for(let e of t.split(`.`)){if(!r&&isPending(n))return n;if(typeof n!=`object`||!n)return found(void 0);r||=e===`value`&&n.kind===`ok`,n=n[e]}return!r&&isPending(n)?n:found(n)}function sourceReading(e,t){if(t.kind===`pending`)return t;let n=t.value;if(n===void 0)return failed$2(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the config declares`,`read`);switch(typeof n==`object`&&n?n.kind:void 0){case`ok`:case`absent`:case`failed`:return n;default:return failed$2(`variable "${e}": the view's payload holds no source reading at "${e}"`,`read`)}}function coerceToType(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`?toString(e):t===`number`?toNumber(e):toBool(e)}function zeroValue(e){return e===`number`?0:e===`boolean`?!1:``}var SourceRegistry=class e{lastErrors=new Map;policyFaults=import_dist$1.observable.map(void 0,{deep:!1});runFaults=import_dist$1.observable.map(void 0,{deep:!1});cleanups=[];runs=import_dist$1.observable.map(void 0,{deep:!1});runSourcesNow=(0,import_dist$1.computed)(()=>new Map([...this.runs].map(([e,t])=>[e,t.get()])));namedNow=(0,import_dist$1.computed)(()=>new Map([...this.runSourcesNow.get()].flatMap(([e,t])=>t.kind===`ok`?[[e,t.value]]:[])));runSources(){return this.runSourcesNow.get()}namedRuns(){return this.namedNow.get()}subscriptionsNow=(0,import_dist$1.computed)(()=>[...new Map([...this.namedNow.get().values()].map(e=>[e.digest,e]))].sort(([e],[t])=>e<t?-1:+(e>t)).map(([,e])=>e));subscriptions(){return this.subscriptionsNow.get()}inputs=import_dist$1.observable.box(UNBOUND,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=createCcCandybarEngine({drawnAt:this.drawnAt});sourceNames=import_dist$1.observable.array([],{deep:!1});publishedNow=(0,import_dist$1.computed)(()=>({values:this.sourceNames.map(e=>this.store.stored(e)),faults:[...this.policyFaults.values(),...this.runFaults.values()]}));published(){return this.publishedNow.get()}sessionState;constructor(e,t=``,n,r=null,i={}){this.store=e,this.defaultEmptyValue=t,this.parent=r,this.env=i,this.sessionState=n,this.cleanups.push((0,import_dist$1.observe)(this.subscriptionsNow,()=>{}))}view(){return new e(new VariableStore(this.store.clock,this.store),this.defaultEmptyValue,this.sessionState,this,this.env)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,typeOf(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,failed$2(t,`parse`))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>sourceReading(e,this.inputs.get().read(e)))}own(e){this.cleanups.push(e)}declareInput(e,t,n,r,i){this.store.defineDerived(e,n,i,()=>this.inputAt(e,t,n,r))}inputAt(e,t,n,r){let i=this.inputs.get().read(t);if(i.kind===`pending`)throw this.lastErrors.delete(e),new PendingValueError(e,`variable "${e}" has no value yet: its source has not answered`);let a=i.value;if(a===void 0)return this.fallbackOf(e,n,r,`input path "${t}" not found in payload`);try{let t=coerceToType(a,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=this.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,{kind:`shell`,command:t,cwd:n.cwd},n.cache,n.parse)}declareFile(e,t,n){this.declareSource(e,{kind:`file`,path:t,readMode:n.readMode??`whole`},n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r),a=this.registerCachePolicy(e,n),o=(0,import_dist$1.computed)(()=>{let e=a();return e.kind===`ok`?ok$1(runOf$1({read:t,parse:parserIdOf(r),refresh:e.value})):e},{equals:(e,t)=>e.kind===`ok`&&t.kind===`ok`?e.value.digest===t.value.digest:e.kind===t.kind});(0,import_dist$1.runInAction)(()=>{this.sourceNames.push(e),this.runs.set(e,o)}),this.cleanups.push((0,import_dist$1.reaction)(()=>this.runFact(e)?.fault??null,t=>this.noteFault(this.runFaults,e,t===null?ok$1(void 0):failed$2(t,`read`)),{fireImmediately:!0}),(0,import_dist$1.reaction)(()=>this.runFact(e)?.reading,e=>{if(e===void 0||e.kind===`pending`)return;let{at:t,...n}=e;i(n)},{fireImmediately:!0}))}runFact(e){let t=this.runs.get(e)?.get();return t?.kind===`ok`?this.inputs.get().run(t.value.digest):void 0}publisherFor(e,t){switch(t.kind){case`text`:case`regex`:return this.scalarPublisher(e,t.default);case`json`:return this.documentPublisher(e,t.default)}}scalarPublisher(e,t){let n=this.stringInitial(t);return this.store.defineBox(e,`string`,n),t=>{this.noteOutcome(e,t),this.store.setBox(e,orElse(t,n))}}documentPublisher(e,t){let n=t===void 0?pendingOf(`unread`):ok$1(t);this.store.defineDocument(e,n);let r,i=!1;return this.cleanups.push(()=>r?.()),a=>{r?.();let o=a;this.noteOutcome(e,o);let s=o.kind===`ok`||o.kind===`failed`&&o.failedAt===`parse`,c=s||t===void 0?o:n,l=i&&s&&o.kind!==`ok`,u=()=>{i=o.kind===`ok`,this.store.setDocument(e,c)};l?r=this.store.clock.after(250,u):u()}}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(buildScope(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=coerceToType(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=readPending(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`,()=>{let e=n.get(this.session(),t.key);return e===null?r:e})}stateRevision(){return this.sessionState===void 0?0:this.sessionState.revision(this.session())}session(){return this.inputs.get().session()}bindInputs(e){(0,import_dist$1.runInAction)(()=>this.inputs.set(e))}getLastError(e){if(!this.declaredHere(e))return this.parent?.getLastError(e);let t=this.lastErrors.get(e),n=this.standingFault(e);return n===void 0?t:t===void 0||t.message===n.message?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){let e=new Set([...this.policyFaults.keys(),...this.runFaults.keys()]);return new Map([...this.parent?.cachePolicyFaults()??[],...[...e].map(e=>[e,this.standingFault(e)])])}standingFault(e){let t=this.policyFaults.get(e),n=this.runFaults.get(e);return t===void 0||n===void 0?t??n:{timestamp:t.timestamp,message:`${t.message}; ${n.message}`}}declaredHere(e){return this.store.has(e)&&!(this.parent?.store.has(e)??!1)}dispose(){for(let e of this.cleanups)e();return this.cleanups.length=0,this.store.dispose()}registerCachePolicy(e,t){switch(t.kind){case`never`:return()=>ok$1({kind:`never`});case`ttl`:return()=>ok$1({kind:`ttl`,durationMs:t.durationMs});case`watch_file`:return()=>ok$1({kind:`watch_file`,path:t.path});case`key`:{let n=this.engine.parse(t.template);return this.answeredUnder(e,()=>{try{return ok$1(n.evaluate(buildScope(this.store)).map(e=>e.plain).join(``))}catch(e){return readPending(e)===void 0?failed$2(`cache key: ${e instanceof Error?e.message:String(e)}`,`read`):pendingOf(`unread`)}})}case`depends_on`:return this.answeredUnder(e,()=>{let e=t.varNames.map(e=>this.store.changeKey(e));return e.every(e=>e.kind===`ok`)?ok$1(e.map(e=>e.value).join(`,`)):pendingOf(`unread`)})}}answeredUnder(e,t){let n=(0,import_dist$1.computed)(t,{equals:import_dist$1.compareStructural});this.cleanups.push((0,import_dist$1.reaction)(()=>n.get(),t=>this.noteFault(this.policyFaults,e,t),{fireImmediately:!0}));let r;return()=>{let e=n.get();return e.kind===`ok`&&(r=e.value),r===void 0?e.kind===`failed`?e:pendingOf(`unread`):ok$1({kind:`key`,hash:keyHashOf(r)})}}fallbackOf(e,t,n,r){if(this.recordError(e,r),n!==void 0)return n;try{return coerceToType(this.defaultEmptyValue,t)}catch{return zeroValue(t)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:this.store.clock.now(),message:t})}noteFault(e,t,n){(0,import_dist$1.runInAction)(()=>{n.kind===`failed`?e.get(t)?.message!==n.reason&&e.set(t,{timestamp:this.store.clock.now(),message:n.reason}):e.delete(t)})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function evaluateWhen(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const HIDDEN={kind:`hidden`},SHOWN={kind:`shown`};function gateOf(e,t){try{return evaluateWhen(e,t)?SHOWN:HIDDEN}catch(e){let t=readPending(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function collapseToCell(e,t){let n=RichText.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function sizeCell(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function cellParts({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function heldCell({text:e,placement:t,lead:n,trail:r}){return{text:unlinked(e),placement:t,...n!==void 0&&{lead:unlinked(n)},...r!==void 0&&{trail:unlinked(r)}}}function unlinked(e){let t=e.blankCopy(e.plain);t.style=resolvedStyle(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(resolvedStyle(i).clearMetaAndLinks(),n,r);return t}function stripItem(e){let t=cellParts(e);if(t.length===1)return e.text;let n=collapseToCell(t);return n.style=e.text.style,n}function applySegmentLayout(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=collapseToCell(e,a).pad(o),d=new RichText(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:collapseToCell([d,...c],a)},...l.length>0&&{trail:collapseToCell([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(sizeCell(u,n,p),[{text:u,...f}])}function wrapOffsets(e,t,n){let r=`x`.repeat(Math.min(n,t)).replace(/x$/,` `),i=r+e,a=[],o=0;return wrappedLines(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 takenOnLine(e,t){if(e.length===0)return 0;let{lines:n}=drawStripCells(e.map(({owner:e})=>e),t),r=cellLen(plainOf(n[n.length-1]));return Math.max(0,r-stripChromeCols(t)+stripSeamCols(t))}function fits(e,t,n){if(e.cellLength<=t)return!0;let{lines:r}=drawStripCells([e],{...n,width:1/0});return cellLen(plainOf(r.flat()))<=n.width}function dividedToLine(e,t,n,r){if(fits(e.owner,t,r))return[e];let i=e.owner.copy().expandTabs(),a=takenOnLine(n,r);return i.divide(wrapOffsets(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 fitRow(e,t){let n=Math.max(2,lineWidth(t)-stripChromeCols(t)-t.padding);return filled(e,t).reduce((e,r)=>[...e,...dividedToLine(r,n,e,t)],[])}function filled(e,t){let n=()=>e.map(e=>({owner:stripItem(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=drawStripCells(e.map(stripItem),t).lines;if(i.length>1)return n();let a=Math.max(0,t.width-cellLen(plainOf(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];sizeCell(c,c.cellLength+a,n)}),n()}function fragmentsToCells(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=buildCell(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:resolvedStyle(a.style)};if(e.style.link){i();let r=buildCell([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function buildCell(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>withStyle(e.frag,n?n.add(e.style):e.style)),i=RichText.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function withStyle(e,t){let n=e.copy();return n.style=t,n}function renderBinding(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 renderLook(e,t){let{look:n}=renderBinding(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function renderLayout(e,t){let{layout:n}=renderBinding(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function bindRender(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 compileActions(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,compileAction(e,t,o,n,r,i));return i}function compileAction(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=resolveOptionDomain(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=n.layer??`user`,t=CONFIG_KEY_TO_EFFECTIVE_VAR.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,layer:e,value:n.to,stateVar:t};if(`from`in n){let r=resolveOptionDomain(n.from,i);return{kind:`persist-option`,key:n.persist,layer:e,stateVar:t,options:[...r.members],paletteOf:r.paletteOf,labelOf:r.labelOf,library:r.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,layer:e,stateVar:t,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,layer:e,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,layer:e,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let t=resolveOptionDomain(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,layer:e,anchor:n.anchor,relation:n.relation,options:[...t.members],paletteOf:t.paletteOf,labelOf:t.labelOf,library:t.library}}return{kind:`persist-bounded`,key:n.persist,layer:e,by:n.by}}if(`copy`in n)return{kind:`copy`,text:parseActionTemplate(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:parseActionTemplate(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset,layer:n.layer??`user`};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:runDeclaration(n),argv:n.run.map(n=>parseActionTemplate(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,parseActionTemplate(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`,layer:n.layer??`user`};if(`preset`in n){let r=n.layer??`user`;return n.preset===`save`?{kind:`preset-save`,layer:r}:{kind:`preset-delete`,layer:r,name:parseActionTemplate(e,n.name,t)}}if(`themeDefault`in n)return{kind:`theme-default-save`,layer:n.layer??`user`};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 presentedAction(e){return e.kind===`do`?presentedAction(e.head):e}function bindsTemplateValue(e){switch(presentedAction(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 parseActionTemplate(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function readVar(e,t){return e.has(t)?toString(e.read(t)):``}function clickSession(e,t){return renderBinding(e,t).registry.session()}function evalTemplate(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function linkFragment(e,t,n,r){let i=new RichText(e,{style:Style.combine([r,new Style({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function linkOver(e,t,n=!1){let r=new Style({link:t,bold:n?!0:void 0}),i=new RichText(e.plain,{style:Style.combine([resolvedStyle(e.style),r])});for(let t of e.spans)i.stylize(Style.combine([resolvedStyle(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function cycleIndex(e,t){return Math.max(e.members.indexOf(readVar(t,e.stateVar)),0)}function realize(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=readVar(r,e.stateVar);return{effects:[{verb:VERB_SET_STATE,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=readVar(r,e.stateVar);return{effects:[{verb:VERB_SET_STATE,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=readVar(r,e.stateVar);return{effects:[{verb:VERB_SET_STATE,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(cycleIndex(e,r)+1)%e.members.length];return{effects:[{verb:VERB_SET_STATE,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:VERB_STEP_STATE,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:VERB_COPY,args:[evalTemplate(e.text,buildScope(r))]}],active:!1};case`open`:return{effects:[{verb:VERB_OPEN_VSCODE,args:[evalTemplate(e.target,buildScope(r))]}],active:!1};case`persist-literal`:{let t=readVar(r,e.stateVar);return{effects:[{verb:VERB_SET_CONFIG,args:[i,e.layer,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=readVar(r,e.stateVar);return{effects:[{verb:VERB_SET_CONFIG,args:[i,e.layer,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(cycleIndex(e,r)+1)%e.members.length];return{effects:[{verb:VERB_SET_CONFIG,args:[i,e.layer,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:VERB_STEP_CONFIG,args:[i,e.layer,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:VERB_RESET_CONFIG,args:[i,e.layer,e.key]}],active:!1};case`undo`:return{effects:[{verb:VERB_UNDO,args:[i]}],active:!1};case`redo`:return{effects:[{verb:VERB_REDO,args:[i]}],active:!1};case`back`:return{effects:[{verb:VERB_BACK,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:VERB_REWIND,args:[i]}],active:!1};case`save`:{let t=e.layer===`ask`?layerRoleOf(n):e.layer;if(t===null)throw Error(`a save that asks which layer it writes binds the layer as its value — {{ action "<save>" "💾 project" "project" }} — and ${n===void 0?`none was bound`:`${JSON.stringify(n)} is not one of ${LAYER_ROLES.join(`, `)}`}`);return{effects:[{verb:VERB_SAVE,args:[i,t]}],active:!1}}case`preset-save`:return{effects:[{verb:VERB_SAVE_PRESET,args:[i,e.layer]}],active:!1};case`theme-default-save`:return{effects:[{verb:VERB_SAVE_THEME_DEFAULT,args:[i,e.layer]}],active:!1};case`preset-delete`:return{effects:[{verb:VERB_DELETE_PRESET,args:[i,e.layer,evalTemplate(e.name,buildScope(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:VERB_DOCTOR_RUN,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:VERB_DOCTOR_FIX,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:VERB_DOCTOR_MARK,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:VERB_SLASH,args:[i,e.line]}],active:!1};case`run`:{let t=buildScope(r),n=JSON.stringify({run:e.argv.map(e=>evalTemplate(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,evalTemplate(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:VERB_APPLY_LAYOUT_OP,args:[i,e.layer,e.key,encodeLayoutOp(e.op)]}],active:!1};case`do`:{let o=realize(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>realize(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:VERB_APPLY_LAYOUT_OP,args:[i,e.layer,e.key,encodeLayoutOp(r)]}],active:!1}}}}function selectDisplay(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:pickCycleDisplay(`action "${e}"`,n,t.members.length,cycleIndex(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 renderAction(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=renderBinding(n,`action "${e}"`).store,{display:a,boundValue:o}=selectDisplay(e,presentedAction(r),t,i),s=clickSession(n,`action "${e}"`),{effects:c,active:l}=realize(r,a.plain,o,i,s,n.signer);return linkOver(a,effectsUrl(c),l)}function actionFuncs(e){return{action:{fn:(t,...n)=>renderAction(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function disclosureCloseFragment(e,t){return linkFragment(`✕`,effectsUrl([{verb:VERB_SET_STATE,args:[e,t,DISCLOSURE_CLOSED]}]),!1)}function stateCell(e,t,n){return new Style({bgcolor:ColorSpec.fromRgba(t),color:ColorSpec.fromRgba(textOn(e,t,n))})}function decoratedCell({tint:e,text:t}){return new Style({bgcolor:ColorSpec.fromRgba(e),color:ColorSpec.fromRgba(t)})}function closeOn(e,t,n){return new Style({color:ColorSpec.fromRgba(ensureContrast(e.get(DISCLOSURE_CLOSE_ROLE),t,TEXT_MIN_CONTRAST,n))})}function closeCell(e,t,n){return Style.combine([stateCell(e,t,n),closeOn(e,t,n)])}function bandItemStyle(e,t,n){return decoratedCell(bandItem(e.palette,e.disclosure,t,n))}const SWATCH_GLYPH=`▀`;function swatch(e){let t=ColorSpec.fromRgba(e.get(`background`)),n=RichText.fromFragments(DECOR_HUES.map(n=>new RichText(`▀`,{style:new Style({color:ColorSpec.fromRgba(e.get(n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const cell=(e,t)=>{let n=typeof e==`string`?new RichText(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},currentMark=e=>new Style({bold:e});function optionPaint(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>cell(a,Style.combine([bandItemStyle(e,{...n,distribution:t},i),currentMark(o)]));let o=stateCell(e.palette,a,i);return(e,t,i,a)=>named(i,Style.combine([o,currentMark(a)]),r(t,n))}const named=(e,t,n)=>cell(RichText.fromFragments([cell(e,t),cell(` `,t),swatch(n)]));function labelPaint(e,t,n,r){return t===void 0?cell(r):named(r,void 0,t(n,e))}function swatchPaint(e,t,n,r,i){let a=stateCell(e.palette,i,r);return(e,r,i,o)=>cell(RichText.fromFragments([cell(o?`[`:` `,a),swatch(n(r,t)),cell(o?`]`:` `,a)]))}const LIBRARY_PAGE_ROWS=8;function libraryLayout(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=>chunk(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function chunk(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function fitCells(e,t){return new RichText(e).truncate(t,{marker:`…`}).plain}function createActiveSegmentRef(e){return{current:null,drawnAt:e}}function openSegment(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 inSegment(e,t,n){return publishing(e,()=>n(openSegment(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function outsideSegments(e,t){return publishing(e,()=>(e.current=null,t()))}function publishing(e,t){let n=e.current;try{return t()}finally{e.current=n}}function requireActiveSegment(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}const PICKER_PREV=`←`,PICKER_NEXT=`→`;function cellWidth(e){return new RichText(e).cellLength}function rowBudget(e){let{width:t,chromeCols:n,padding:r}=renderBinding(e,`a row fit`);return Math.max(1,t-n-2*r)}function ledRowBudget(e){let{padding:t,seamCols:n}=renderBinding(e,`a row fit`);return Math.max(1,rowBudget(e)-(cellWidth(`✕`)+2*t+n))}function paginate(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 gridPages(e,t,n){let r=cellWidth(PICKER_PREV)+1+cellWidth(PICKER_NEXT)+1,i=paginate(e,t,n);return(i.length>1?paginate(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function assemble(e){let t=[];for(let n of e)t.length>0&&t.push(new RichText(` `)),t.push(n);let n=RichText.fromFragments(t);return n.overflow=`ignore`,n.end=``,n}function requireKind(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 requireOptionKind(e,t,n){let r=e.compiled.get(t),i=r&&presentedAction(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 renderPicker(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=renderBinding(a,`picker`).store,d=clickSession(a,`picker`),f=`stateVar`in t?readVar(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`?ledRowBudget(a):rowBudget(a):1/0,h=(r.kind===`led`?0:cellWidth(`✕`)+1)+c.reduce((e,t)=>e+cellWidth(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?gridPages(v.map(e=>e.cellLength),m,h):libraryLayout(g.entries,g.groups,i),b=parseInt(readVar(u,n.stateVar),10),x=e=>Math.max(0,y.findIndex(t=>t.some(t=>t.indices.includes(e)))),S=x(f===void 0?-1:t.options.indexOf(f)),C=Number.isInteger(b)?b<0?S:Math.min(b,y.length-1):0,w=y[C]??[],T=e=>effectsUrl([{verb:VERB_SET_STATE,args:[d,n.key,String(e)]}]),E=r.kind===`led`?[]:[{verb:VERB_SET_STATE,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],D=r.kind===`own`&&r.onPick?E:[],O=e=>effectsUrl([...realize(l,e,e,u,d,a.signer).effects,...D]),k=(e,n)=>linkOver(e,O(t.options[n])),A=r.kind===`led`?[]:[linkFragment(`✕`,effectsUrl(E),!1,s)];A.push(...c.map(({glyph:e,option:r})=>linkFragment(e,effectsUrl([...realize(l,r,r,u,d,a.signer).effects,{verb:VERB_SET_STATE,args:[d,n.key,String(x(t.options.indexOf(r)))]}]),!1))),C>0&&A.push(linkFragment(PICKER_PREV,T(C-1),!1));let j=C<y.length-1?[linkFragment(PICKER_NEXT,T(C+1),!1)]:[];if(g===void 0){let e=w.flatMap(e=>e.indices);return[assemble([...A,...e.map(e=>k(v[e],e)),...j])]}let M=new Style({bold:!0}),N=y.length>1?` ${C+1}/${y.length}`:``,F=w.length===1?[new RichText(`${w[0].label}${N}`,{style:M})]:[],ee=[assemble([...A,...F,...j])];for(let e of w){w.length>1&&ee.push(assemble([new RichText(e.label,{style:M})]));let n=Math.max(...e.indices.map(e=>cellWidth(_(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:sanitizeText(i),o=` `.repeat(n-cellWidth(e)+2),s=a===void 0?e:`${e}${o}${a}`;ee.push(assemble([k(p(r,fitCells(s,m)),r)]))}}return ee}function pickerFuncs(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{refuseSurplus(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=requireKind(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=requireOptionKind(e,n,`picker`),u=requireActiveSegment(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=>renderPicker(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,optionPaint(u,placedBy(void 0),renderLook(e,`{{ picker }}`),l.paletteOf,d,t),closeOn(u.palette,t,d)),p=bandFor(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`}}}const CAROUSEL_PREV=`◀`,CAROUSEL_NEXT=`▶`;function ringAround(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function renderCarousel(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=renderBinding(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=clickSession(i,`carousel`),{options:c}=t;if(c.length===0)return assemble([]);let l=ringAround(c,readVar(a,t.stateVar)),u=e=>c[l(e)],d=e=>effectsUrl(realize(o,u(e),u(e),a,s,i.signer).effects);return assemble([linkFragment(`◀`,d(-1),!1),linkOver(labelPaint(renderLook(i,`{{ carousel }}`),t.paletteOf,u(0),r),effectsUrl(realize(i.compiled.get(n),u(0),void 0,a,s,i.signer).effects)),linkFragment(`▶`,d(1),!1)])}function carouselFuncs(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(bindsTemplateValue(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 renderCarousel(t,requireOptionKind(e,t,`carousel`),n,r,e)},argTypes:[`string`,`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const SWATCHES_RANDOM=`?`;function requireSwatchable(e,t,n){let r=requireOptionKind(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 randomOther(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 optionPalette(e,t,n,r){let i=requireSwatchable(e,t,n),a=r??readVar(renderBinding(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,renderLook(e,`{{ ${n} }}`))}function swatchFuncs(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(refuseSurplus(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return swatch(optionPalette(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function swatchesFuncs(e,t,n){return{swatches:{fn:(r,i)=>{let a=requireSwatchable(e,r,`swatches`),o=requireKind(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=requireActiveSegment(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]=renderPicker(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,swatchPaint(s,renderLook(e,`{{ swatches }}`),a.paletteOf,c,s.bg),closeOn(s.palette,s.bg,c),u===0?[]:(()=>{let t=ringAround(l,readVar(renderBinding(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[randomOther(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const BAR_WORDS=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function previewRows(e,t,n,r){let i=bandFor(e,n,r),a=(t,n)=>({text:t,colour:n,ink:textOn(e,n,r)});return[[vocabularyOf(e,t,r).map((n,i)=>{let a=decorEntryColour(e,n);return{text:BAR_WORDS[i%BAR_WORDS.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 renderRow(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new RichText(` ${e} `,{style:decoratedCell({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 RichText(e)),r.push(a)}return r}function renderThemePreview(e,t,n,r,i){let a=previewRows(e,t,n,r).map(e=>renderRow(e,i)),o=RichText.fromFragments(a.flatMap((e,t)=>t===0?e:[new RichText(`
|
|
214
218
|
`),...e]));return o.overflow=`ignore`,o.end=``,o}function themePreviewFuncs(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(refuseSurplus(`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}=renderLook(e,`{{ themePreview }}`);return renderThemePreview(r===void 0?a:optionPalette(e,r,`themePreview`),o,{...requireActiveSegment(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),ledRowBudget(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const blockLabel=e=>e.slice(e.lastIndexOf(`.`)+1),clippedLabel=(e,t)=>{let n=new RichText(blockLabel(e));return n.truncate(t,{marker:`…`}),n.plain};function labelBudget(e,t){let n=e.map(e=>e.map(({name:e})=>cellWidth(blockLabel(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 renderLayoutPreview(e,t,n,r){let i=labelBudget(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new RichText(` ${clippedLabel(s,i)} `,{style:decoratedCell(decorationFor(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=RichText.fromFragments(a.flatMap((e,t)=>t===0?e:[new RichText(`
|
|
215
219
|
`),...e]));return o.overflow=`ignore`,o.end=``,o}const LAYOUT_PREVIEW=`layoutPreview`;function layoutPreviewFuncs(e,t){return{[LAYOUT_PREVIEW]:{fn:()=>renderLayoutPreview(renderLayout(e,`{{ layoutPreview }}`),renderLook(e,`{{ layoutPreview }}`).decor,t.drawnAt(),ledRowBudget(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function renderMenu(e,t,n,r){let i=requireActiveSegment(r.activeSegment,`{{ menu }}`),a=r.action,o=menuStateKey(i.placementId,e,n.key),s=menuPageKey(o),c=menuMember(e),l=renderBinding(a,`menu`).store,u=readVar(l,o)===c,d=clickSession(a,`menu`),f=u?DISCLOSURE_CLOSED:c,p=linkFragment(pickCycleDisplay(`{{ menu "${e}" }}`,t,2,+!!u),effectsUrl([{verb:VERB_SET_STATE,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=bandFor(i.palette,i.disclosure,t).plane,l=requireOptionKind(a,e,`menu`);return renderPicker(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,DISCLOSURE_CLOSED],[s,`0`]],onPick:n.closeOnPick},n.paged,a,optionPaint(i,n.distribution,renderLook(a,`{{ menu }}`),l.paletteOf,t,c),closeOn(i.palette,c,t))})():[]),p}const isDict=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function parseMenuArgs(e,t){let n=t[t.length-1],r=isDict(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:parseMenuOptions(r??{})}}function menuFuncs(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=parseMenuArgs(t,n);return renderMenu(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function renderGauge(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=litCells(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 RichText(t?i:a,{style:l===void 0?void 0:new Style({color:l})}))}let l=RichText.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function litCells(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 segmentColorFuncs(e){let t={fn:(()=>{let t=requireActiveSegment(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:(()=>requireActiveSegment(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=requireActiveSegment(e,`{{ roleTextOn }}`);return namedRoleText(r,t,resolveColorRef(r,n)).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i={fn:((t,n)=>{let{palette:r}=requireActiveSegment(e,`{{ keptOn }}`),i=resolveColorRef(r,t),a=resolveColorRef(r,n),o=contrastRatio(drawnColour(i,ColorDepth.TRUECOLOR),drawnColour(a,ColorDepth.TRUECOLOR)),s=Math.min(TEXT_MIN_CONTRAST,o),c=e.drawnAt(),l=ensureDrawn(i,c,(e,t)=>contrastRatio(e,t(a))>=s);if(l===void 0)throw Error(`keptOn: nothing drawn at ${ColorDepth[c]} stands ${s.toFixed(2)}:1 off ${a.hex} (drawn ${drawnColour(a,c).hex})`);return l.hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},a=paletteFuncs(()=>requireActiveSegment(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),o={fn:((e,t,n,r,i,o,...s)=>{let c=o===void 0?void 0:[o,...flattenStops(s)];return renderGauge({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 RUNGS_OUT={"#000000":[`darken-1`,`darken-2`,`darken-3`],"#ffffff":[`lighten-1`,`lighten-2`,`lighten-3`]},RUNGS=Object.values(RUNGS_OUT).flat();function namedRoleText(e,t,n){let r=drawnColour(n,ColorDepth.TRUECOLOR),i=t=>{let n=resolveColorRef(e,t);return{colour:n,ratio:contrastRatio(drawnColour(n,ColorDepth.TRUECOLOR),r)}},a=contrastFor(r).hex,o=RUNGS_OUT[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,...RUNGS.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 flattenStops(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}const KIND_SCOPE={input:`view`,state:`view`,template:`view`,time:`view`,source:`view`,shell:`view`,file:`view`,literal:`directory`,env:`directory`,dropped:`directory`},SCOPES=new WeakMap;function variableScopes(e){let t=SCOPES.get(e);return t===void 0&&(t=new Map([...declaredVariables(e)].map(([e,t])=>[e,KIND_SCOPE[t.kind]])),SCOPES.set(e,t)),t}function splitCellsIntoLines(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
216
220
|
`)){n.push(r);continue}let e=r.split(`
|
|
217
221
|
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function rowIdentities(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 visibilityOf=e=>e.kind===`failed`?HIDDEN:e;function within(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function returnedBy(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 heldLine(e){return{...e,cells:e.cells.map(heldCell)}}function composeBlocks(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,...composeFlow(e,r)]}function composeFlow(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 layoutRows(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:composeBlocks(e.direction,e.children.map((t,i)=>n(t,[...r,childStep(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function childStep(e,t){return e.steps[t]}function spanOf(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=laidOut(e);return{width:widthOf$1(t),reach:reachOf(t)}}function laidOut(e){let t=e.children.map(spanOf),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 widthOf$1=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),reachOf=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function placeChildren(e,t){let n=laidOut(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=AXIS_OF[e.direction],i=placedBy(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),reachOf(n),widthOf$1(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const containerType={compile(e,t){let n=placeChildren(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,childPath(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),composeBlocks(e.direction,e.children.map((n,r)=>t.renderChild(n,visibilityOf(t.gate),childStep(e,r))))}},BODY_PLACE={drop:e=>e.place,above:()=>`above`},OPEN_LEAD={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},segmentType={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:placementId(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(disclosureGate(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,bodyPath(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,drawSegment(e,t))};function drawSegment(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=placementScope(t.scope,e.settings);if(t.gate.kind===`failed`)return brokenSegment(e,r,t,t.gate.message);try{let i=t.placement(e),a=within(t.gate,i.gate());if(a.kind===`failed`)return brokenSegment(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 brokenSegment(e,r,t,s.message);let c=placementPalette(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:groundOf(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`?waitingOn(f.variable):ownAnswer(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?drawnRows(p.segment,u):waitingRows(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:HIDDEN,h.disclosure).map(e=>({...e,place:BODY_PLACE[v.placement](e)})),b=(e,t,n)=>applySegmentLayout(fragmentsToCells([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?OPEN_LEAD[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},w=S.flatMap(e=>b(new RichText(` `.repeat(cellsWidth(cellParts(e)))),h.trigger,0)),T=(e,t)=>e.band===`own`?t===x?S:w:[],E=y.map((e,t)=>({cells:[...T(e,t),...e.cells],band:`deeper`,place:e.place})),D=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...D.flatMap(e=>e.cells),...y.flatMap(T)].flatMap(cellParts)),[...D,...E]}catch(n){return brokenSegment(e,r,t,n.message??String(n))}}const waitingOn=e=>({kind:`waiting`,variable:e});function ownAnswer(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=readPending(e);if(t===void 0)throw e;return waitingOn(t.variable)}}function drawnRows(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:splitCellsIntoLines(fragmentsToCells(r,c)).map((e,t)=>({cells:applySegmentLayout(e,{...l,lead:t===0?fragmentsToCells(i,c):[],trail:t===0?fragmentsToCells(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:applySegmentLayout(fragmentsToCells([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}const LOADING_GLYPH=`…`;function waitingRows(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=fragmentsToCells(errorAffix(e.lead,e,t,n),l),d=fragmentsToCells(errorAffix(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 applySegmentLayout(fragmentsToCells([new RichText(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function cellsWidth(e){return e.reduce((e,t)=>e+t.cellLength,0)}function brokenSegment(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:applySegmentLayout([new RichText(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:groundOf(n.palette)},lead:errorAffix(e.lead,e,t,n),trail:errorAffix(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function errorAffix(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=readPending(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const REGISTRY={container:containerType,segment:segmentType};function nodeType(e){return REGISTRY[e]}var FrameMemory=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?HIDDEN_RECORD:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const HIDDEN_RECORD={kind:`hidden`},SELECTION_OF={palette:`theme`,style:`style`,effect:`effect`},COLOR_PATH=CONFIG_KEY_TO_EFFECTIVE_VAR.get(`colorCompatibility`),COLOR_FLOOR=`truecolor`,UNDRAWN={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function answerOf(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function unwrap(e){if(e.ok)return e.value;throw e.error}const always=e=>({read:()=>e}),sameLook=sameBy({basePalette:is,palette:is,decor:sameDecor});var ViewParts=class{evaluated=0;memory=new FrameMemory;scope;binding;facts;look=import_dist$1.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&sameLook(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=import_dist$1.observable.box(r,{deep:!1}),this.scope=buildScope(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(COLOR_PATH);return e.kind===`found`&&typeof e.value==`string`&&isColorCompatibility(e.value)?e.value:COLOR_FLOOR});let i=(0,import_dist$1.observable)(UNDRAWN,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 layoutRows(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=arrangedSegment(e);return i===void 0?[]:[{name:i,address:n,palette:placementPalette(r.theme,t)}]}))}),t.bindInputs({session:()=>this.view.get().session,read:e=>this.inputAt(e),run:e=>this.view.get().run(e),drawnAt:()=>drawnDepth(this.colorCompatibility())})}bind(e){(0,import_dist$1.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,import_dist$1.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=slotAt(e);return t===void 0?drawProjectionAt(e)===void 0?resolvePath(this.view.get().payload(),e):resolvePath(this.projected,e):found(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()[SELECTION_OF[e]];if(t.kind===`decided`)return settled(t.name,null,null);let r=compiledRule(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=decideSlot(this.source,e,i.name,r.where,e=>{t=e}),settled(n,t,null)}case`pending`:return settled(n??SLOT_FLOORS[e],null,i.variable);case`failed`:return n=SLOT_FLOORS[e],settled(n,ruleFloorMessage(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!sameSlot(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)??SLOT_FLOORS[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,import_dist$1.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return gateOf(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>outsideSegments(this.source.activeSegment,()=>gateOf(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new Placement(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:bindRender(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=readPending(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:answerOf(e)}),unwrap(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:arrangedSegment(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function bindView(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new ViewParts(t,n,e,r);return e.views.set(t,a),a}function partsOf(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 settled=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),sameSlot=(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 compiledRule(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 decideSlot(e,t,n,r,i){switch(t){case`palette`:return decideThemeName(n,r,i).name;case`style`:return decideStyleName(n,e.styles).name;case`effect`:return decideEffectName(n).name}}var Placement=class{where=inlet(sameBy({palette:is,region:sameRegion}));ground=inlet(sameBy({colours:sameDealt,bodyOpen:is}));opened=inlet(sameBy({colours:sameDealt,open:is}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=placementScope(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?always(SHOWN):e.derive(`${t.id} when`,e.readsInstant(a),()=>outsideSegments(r,()=>gateOf(a,i))),this.open=d===void 0?always(HIDDEN):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>outsideSegments(r,()=>gateOf(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return coloursOf(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 bodyOf(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?always(NO_AFFIXES):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return affixesOf(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}),evaluated(n,r,this.affixes.read())}};function inlet(e){let t=import_dist$1.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,import_dist$1.runInAction)(()=>t.set(e)),get:()=>t.get()}}const sameHex=(e,t)=>e.hex===t.hex,sameDealt=sameBy({palette:is,drawnAt:is,tint:sameHex,text:sameHex,bg:sameHex,disclosure:sameDisclosure});function placeOf(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const bandOf=e=>bandFor(e.palette,e.disclosure,e.drawnAt);function coloursOf(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...decorationFor(n,r,i)};return inSegment(e,placeOf(t,c),e=>{let t=resolveSegmentColors(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function bodyOf(e,t,n,r,i,a){return inSegment(e,placeOf(t,n),e=>(e.bg=i?bandOf(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function affixesOf(e,t,n,r,i,a,o){return inSegment(e,placeOf(t,n),e=>(e.bg=r?bandOf(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const NO_AFFIXES={lead:[],trail:[],drops:[]};function stylesOf(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return stateCell(t,bandOf(e).state,n)},get band(){return stateCell(t,bandOf(e).plane,n)},get close(){return closeCell(t,bandOf(e).state,n)},disclosure:r}}function evaluated(e,t,n){return{styles:stylesOf(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function evaluateOnce(e,t,n,r,i,a,o){let s=coloursOf(e,t,n,r,i,void 0,void 0,o);return evaluated(s,bodyOf(e,t,s,a,!1,o),NO_AFFIXES)}function decoratedStyles(e,t,n,r,i){return stylesOf(coloursOf(e,t,n,r,i,void 0,void 0,{}))}function fixedSource(e,t,n,r){return{session:n,payload:()=>e,run:r,selections:()=>t}}function instantRead(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 FOLDS=new WeakMap;function foldOf(e){let t=FOLDS.get(e);return t===void 0&&(t=foldProjections(e),FOLDS.set(e,t)),t}function projectionsOf(e){return foldOf(e).projections}function foldProjections(e){let t=new Map(declaredVariables(e)),n=new Map,r={reads:valueReadsOf(e),projections:n,clock:CLOCK_FUNCTIONS};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=payloadPathOf(e,r),i=t===void 0?null:drawProjectionAt(t);i&&n.set(e,`reads the draw's "${i}" (${DRAW_PROJECTIONS[i]})`)}let i=rulesOf(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=instantRead(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of EXPRESSION_SLOTS)if(!a.has(t))for(let n of i[t]){let i=instantRead(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=payloadPathOf(r,i);if(t===void 0||n.has(r))continue;let o=slotAt(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 authoredRules(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>EXPRESSION_SLOTS.flatMap(n=>{let r=t[n];return isExpression(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function rulesOf(e){let t=authoredRules(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function instantReadOf(e,t){return instantRead(e,foldOf(t))}function templateInstants(e){return t=>instantRead(t,e)!==null}function toCachePolicy(e){if(`ttl`in e)return{kind:`ttl`,durationMs:parseDuration(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 toSourceParse(e,t){switch(parseArm(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,pattern:e.regex,default:t};case`text`:return{kind:`text`,default:t}}}function declareOne(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:toCachePolicy(n.cache),parse:toSourceParse(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:toCachePolicy(n.cache),parse:toSourceParse(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 compileHelpers(e,t,n,r=Defines.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 registerDslConfig(e,t,n){let{compiled:r,loadWarnings:i}=registerCompiled(e,t,n.cwd,compileAlone(n.signer),EVERY_SCOPE);return{...r,loadWarnings:i}}const compileAlone=e=>(t,n)=>compileDslConfig(n,e);function registerCompiled(e,t,n,r,i=EVERY_SCOPE){let a=compileInputOf(e),o=compileKey(a);return{compiled:r(o,a),compileKey:o,loadWarnings:declareDslVariables(e,t,n,i)}}function compileInputOf(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of SESSION_KEY_TO_EFFECTIVE_VAR)n in t&&r.set(e,n);for(let[t,n]of stateVarDecls(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...projectionsOf(e)].sort(([e],[t])=>e<t?-1:1)}}function compileKey(e){return createHash(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function declareDslVariables(e,t,n,r){let i=variableScopes(e),a=projectionsOf(e),o=[];for(let[s,c]of declaredVariables(e))if(r.has(i.get(s)))try{declareOne(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const EVERY_SCOPE=new Set([`directory`,`view`]);function compileDslConfig({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>renderBinding(i,`drawnAt`).registry.drawnAt(),o=createActiveSegmentRef(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=presetNames(e.presets),u=configOptionDomains(e),d=[e=>swatchesFuncs(i,o,e.now)],f=createCcCandybarEngine({extraFuncs:{...actionFuncs(i),...swatchFuncs(i),...pickerFuncs(i,o),...carouselFuncs(i),...themePreviewFuncs(i,o),...layoutPreviewFuncs(i,o),...menuFuncs(s),...segmentColorFuncs(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=compileHelpers(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=compileActions(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:compileHelpers(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=settingsOf(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>placementSetting(t,e,a,t=>String(renderBinding(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 nodeType(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=presetRoot(e,t);C.set(t,S(n,r,void 0))}let w=new Map(EXPRESSION_SLOTS.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of authoredRules(e)){let e=t.join(`.`),i=w.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:parseExpressionSlot(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let T=new Set(n.map(([e])=>e)),E={reads:valueReads({names:T,helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:engineClockFunctions(d)},D=templateInstants(E),O=[...C.values()].flatMap(layoutGates(y)).some(e=>D(m.get(e))),k=O?new Set([...E.clock,LAYOUT_PREVIEW]):E.clock,A=templateInstants({...E,clock:k}),j=new Set([...m].flatMap(([e,t])=>A(t)?[e]:[]));for(let[t,n]of Object.entries(e.segments)){if(n.partials===void 0)continue;let r=templateInstants({reads:valueReads({names:T,helpers:{...e.helpers,...n.partials},actions:e.actions}),projections:E.projections,clock:k});for(let e of SEGMENT_TEMPLATE_FIELDS){let n=y[t][e];n!==void 0&&r(m.get(n))&&j.add(n)}}return{segments:y,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:w,instant:j,layoutReadsInstant:O,styles:e.styles,runtime:i,views:new WeakMap}}function instantSegments(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 layoutGates=e=>t=>{let n=[];return layoutRows(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 parseExpressionSlot(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 unreachable=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function evalRule(e,t,n,r,i){let a=ruleName(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function ruleName(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??SLOT_FLOORS[e];case`failed`:return r({kind:`rule`,slot:e,message:ruleFloorMessage(t.where,e,`the rule failed — ${n.error}`)}),SLOT_FLOORS[e]}}function placementsUnder(e){return segmentsUnder(e).filter(e=>!e.name.startsWith(EDIT_NS)).map(e=>e.id)}function segmentsUnder(e){return e.kind===`container`?e.children.flatMap(segmentsUnder):[e,...e.opens===void 0?[]:segmentsUnder(e.opens.body)]}function bindPayload(e,t,n,r,i,a,o,s){let c={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return bindView(e,t,n,fixedSource(c,a,o,s)),c}function drawDsl(e,t,n,r,i,a,o,s,c){try{var l=_usingCtx();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new SessionEffects(``),h=m.clockAt(a,ANIMATION_SPEEDS[c.animationSpeed]),g=l.u(bindClock(a,h.timeline)),_=partsOf(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:stripChromeCols(v),padding:v.padding,seamCols:stripSeamCols(v),preset:c.preset},i);let y=_.evaluated,b=l.u(bindRender(t.menuRuntime.action,_.binding)),{preset:x,transitions:S}=c,C={variation:VARIATIONS[c.variation],shade:SHADES[c.shade]},w={config:e,preset:x,revision:r.stateRevision(),width:v.width},T=_.memory.begin(w,returnedBy),E=_.memory.from(w),D=new Set,O={held:e=>E?.rules.get(e),waited:e=>D.add(e),settled:T.rule},k=new Map,A=e=>{let n=_.slot(e);if(k.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&&D.add(n.waited),n.name;let r=decideSlot(t,e,evalRule(e,n.rule,_,p,O),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:j,style:M,effect:N}=_.selections(),F=j.kind===`decided`?j:decideThemeName(A(`palette`),``,unreachable),ee=M.kind===`decided`?M:decideStyleName(A(`style`),e.styles),te=N.kind===`decided`?N:decideEffectName(A(`effect`)),ne=F.value,I=transposedPalette(ne,ee.value);_.publishLook({basePalette:ne,palette:I,decor:C});let re=I.get(`warning`),ie=c.idleSince===void 0?null:{idleSince:c.idleSince,timeoutS:c.menuTimeout,fill:re,text:textOn(I,re,r.drawnAt())},ae=m.motion(te.value,h,{transitions:S,source:w,last:E,returned:returnedBy,hold:heldLine},ie);u?.clear();let oe=t=>e.segments[t],L=(e,n,i)=>{let a=n.kind===`hidden`?n:within(n,_.gate(e)),o=a.kind===`failed`?{...a,report:()=>{let t=`when over ${placementsUnder(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:a.message,message:`${t}: ${a.message} — what it gates is hidden`})}}:a,s={scope:_.scope,palette:I,gate:o,padding:v.padding,region:i,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,a,o)=>evaluateOnce(t.activeSegment,e,a,i,r.drawnAt(),o,n),lookupSegment:oe,renderChild:(e,t,n)=>L(e,t,descend(i,n)),renderBody:(e,t,n)=>L(e,t,bandRoot(n)),closeDisclosure:e=>disclosureCloseFragment(r.session(),e),placed:(e,t)=>T.placed(e,ae.placed(e,t)),lastDrawn:e=>E?.placements.get(e),waited:e=>D.add(e),decorations:(e,n)=>decoratedStyles(t.activeSegment,e,n,i,r.drawnAt())};return nodeType(e.kind).render(e,s)},R=t.roots.get(x);if(R===void 0)throw Error(`Preset "${x}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${PRESET_FLOOR}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let se=rowIdentities(L(R,SHOWN,barRoot(C))).map(({line:e,row:t})=>{let n=fitRow(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...drawStripCells(n.map(e=>e.owner),v,ae.row(t,r,n))}});ae.drawn(),T.commit();let ce=()=>se.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||S||segmentsUnder(R).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`),le=Math.min(g.heard(),...se.map(e=>e.nextChange)),ue=Number.isFinite(le)?`moves`:ce()?`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:se.flatMap(({kind:e,lines:t})=>t.map(t=>({kind:e,runs:t}))),nextChange:le,motion:ue,pending:[...D].sort()},evaluated:_.evaluated-y,cellBreaks:se.reduce((e,t)=>e+t.cellBreaks,0),rules:k}}catch(e){l.e=e}finally{l.d()}}const RESERVED_CHARS=2;function applyClaudeCodeReserve(e){return Math.max(1,e-RESERVED_CHARS)}const LAYOUT_NODE_REF=`#/definitions/LayoutNode`,ROOT_FRAGMENT_REF=`#/definitions/RootFragment`,EMPTY_VERTICAL_NODE={kind:`container`,direction:`vertical`,children:[]};function literalSpec(e){return{required:!0,json:{const:e},parse:()=>e}}function segmentNameSpec(){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 ${describeValue(i)}`,line:findKeyLine(e.source,[`root`])}),``)}}}function directionSpec(){return{required:!0,json:{enum:[...DIRECTIONS]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&DIRECTIONS.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${DIRECTIONS.join(`, `)} (got ${JSON.stringify(i)})`,line:findKeyLine(e.source,[`root`])}),`vertical`)}}}function childrenSpec(e){return{required:!0,json:{type:`array`,items:{$ref:LAYOUT_NODE_REF}},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 ${describeType(a)}`,line:findKeyLine(t.source,[`root`])}),[])}}}const SEGMENT_NODE_SCHEMA={noun:`layout-node key`,fields:{kind:literalSpec(`segment`),name:segmentNameSpec(),when:optionalStringSpec(),id:placementIdSpec(),settings:placementSettingsSpec()}},distributionSpec=()=>optionalEnumSpec(DISTRIBUTION_NAMES),CONTAINER_SCHEMA={noun:`layout-node key`,fields:{kind:literalSpec(`container`),direction:directionSpec(),children:childrenSpec(lazy(()=>validateRoot)),when:optionalStringSpec(),distribution:distributionSpec()}};function segArmSpec(){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 ${describeValue(i)}`,line:findKeyLine(e.source,[...t.split(`.`),n])}),``)}}}const SEG_ARM_SCHEMA={noun:`layout-node key`,fields:{seg:segArmSpec(),when:optionalStringSpec(),id:placementIdSpec(),settings:placementSettingsSpec()}},H_ARM_SCHEMA={noun:`layout-node key`,fields:{h:childrenSpec(lazy(()=>validateRoot)),when:optionalStringSpec(),distribution:distributionSpec()}},V_ARM_SCHEMA={noun:`layout-node key`,fields:{v:childrenSpec(lazy(()=>validateRoot)),when:optionalStringSpec(),distribution:distributionSpec()}},validateRoot=(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:findKeyLine(e.source,[`root`])}),EMPTY_VERTICAL_NODE):{kind:`segment`,name:n};if(!isPlainObject$2(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 ${describeType(n)}`,line:findKeyLine(e.source,[`root`])}),EMPTY_VERTICAL_NODE;if(n.kind===`container`)return record(e,CONTAINER_SCHEMA,t,n)??EMPTY_VERTICAL_NODE;if(n.kind===`segment`)return record(e,SEGMENT_NODE_SCHEMA,t,n)??EMPTY_VERTICAL_NODE;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
218
222
|
Old: { kind: "cells", segments: ["seg1", "seg2"] }
|
|
219
|
-
New: { h: ["seg1", "seg2"] }`,line:findKeyLine(e.source,[`root`])}),EMPTY_VERTICAL_NODE;if(n.kind===`group`){let r=record(e,GROUP_SCHEMA,t,n);return r===null?EMPTY_VERTICAL_NODE:(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}),lowerGroup(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:findKeyLine(e.source,[`root`])}),EMPTY_VERTICAL_NODE}if(a){let r=record(e,SEG_ARM_SCHEMA,t,n);return r===null?EMPTY_VERTICAL_NODE:{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=record(e,H_ARM_SCHEMA,t,n);return r===null?EMPTY_VERTICAL_NODE:{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=record(e,V_ARM_SCHEMA,t,n);return r===null?EMPTY_VERTICAL_NODE:{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:findKeyLine(e.source,[`root`])}),EMPTY_VERTICAL_NODE};function rowsSpec(){return{required:!0,json:{type:`object`,propertyNames:{pattern:ROW_NAME_RE.source},additionalProperties:{$ref:LAYOUT_NODE_REF}},parse:(e,t,n,r)=>{let i=r[n];if(!isPlainObject$2(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${describeType(i)}`,line:findKeyLine(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!ROW_NAME_RE.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:findKeyLine(e.source,[...t.split(`.`),n,r])});continue}a[r]=validateRoot(e,`${t}.${n}.${r}`,o)}return a}}}const ROWS_SCHEMA={noun:`root key`,fields:{rows:rowsSpec(),when:optionalStringSpec(),distribution:distributionSpec()}};function validateRootFragment(e,t,n){return isPlainObject$2(n)&&`rows`in n?record(e,ROWS_SCHEMA,t,n)??{rows:{}}:validateRoot(e,t,n)}const INSERT_SCHEMA={noun:`insert key`,fields:{seg:segArmSpec(),id:placementIdSpec(),before:optionalStringSpec(),after:optionalStringSpec()}};function validateInsert(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=record(e,INSERT_SCHEMA,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:findKeyLine(e.source,i.split(`.`))}),[];if(isReservedName(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:findKeyLine(e.source,[...i.split(`.`),`seg`])}),[];let s=o[0],c=a[s];return isReservedName(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:findKeyLine(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 ${describeType(t)}`,line:findKeyLine(e.source,[`insert`])}),[])}function groupNameSpec(){return{required:!0,json:{type:`string`,pattern:ROW_NAME_RE.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!ROW_NAME_RE.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 "${DISCLOSURE_CLOSED}", got ${describeValue(i)}`,line:findKeyLine(e.source,[`root`])});return}return i}}}function groupKeySpec(){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 ${describeValue(i)}`,line:findKeyLine(e.source,[`root`])});return}return i}}}}function groupLabelSpec(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=requireString(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:findKeyLine(e.source,[...t.split(`.`),n])});return}return i}}}}const GROUP_SCHEMA={noun:`layout-node key`,fields:{kind:literalSpec(`group`),name:groupNameSpec(),label:groupLabelSpec(),open:optionalBooleanSpec(),direction:optionalEnumSpec(DIRECTIONS),key:groupKeySpec(),bg:optionalStringSpec(),fg:optionalStringSpec(),when:optionalStringSpec(),distribution:distributionSpec(),children:childrenSpec(lazy(()=>validateRoot))}};function groupStateKey(e){return e.key??`groups.`+e.name}function lowerGroup(e){let t=GROUP_NS+e.name;return disclosureNode(t,{variable:t,key:groupStateKey(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function groupIssue(e,t,n){e.issues.push({path:t,message:n,line:findKeyLine(e.source,[`root`])})}function synthesizeGroupDecls(e,t){reservedNamespaceCollisions(e,t,GROUP_NS,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&groupIssue(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}.`)&&groupStateKey(t)===groupStateKey(r)&&groupIssue(e,t.path,`group "${t.name}" shares key "${groupStateKey(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=groupStateKey(t);if(i.has(n)||i.set(n,DISCLOSURE_CLOSED),t.open===!0){let r=i.get(n);r!==`closed`&&groupIssue(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=GROUP_NS+e.name,r=groupStateKey(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=disclosureStateVar(r,i.get(r)),o[t]=disclosureCycleAction(r,e.name),s[t]={template:disclosureTrigger(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 MENU_FUNC=`menu`,MIGRATION=`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`,isDictCall=e=>e.kind===`call`&&e.name===`dict`,isNonObjectLiteral=e=>e.kind===`literal`&&typeof e.value!=`object`,legalDisplayCount=e=>cycleDisplayIssue(``,e,2)===void 0;function analyzeMenuCall(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&&isDictCall(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(isDictCall))return t(`whose options (dict …) is not its last argument — ${MIGRATION}`);if(i!==void 0&&a===void 0&&!isNonObjectLiteral(i)&&legalDisplayCount(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=cycleDisplayIssue(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${MIGRATION}`);let c=a===void 0?{}:staticDictEntries(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=parseMenuOptions(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=reservedNamespaceOf(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 "${sharedMenuStateKey(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 parseCalls(e){let t=createEngine({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===MENU_FUNC).map(analyzeMenuCall)}catch{return`parse-failed`}}function hostedMenus(e,t){let n=parseCalls(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:menuStateKey(t,e.apply,e.options.key),member:menuMember(e.apply)}]:[])}function segmentReferencesMenu(e){let t=createEngine({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(MENU_FUNC)}catch{return!1}}function menuIssue(e,t,n){e.issues.push({path:t,message:n,line:findKeyLine(e.source,[`root`])})}function checkMenuDecls(e,t){reservedNamespaceCollisions(e,t,MENU_NS,`{{ menu }} helpers`),reservedNamespaceCollisions(e,t,MENU_PAGE_NS,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))segmentReferencesMenu(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:findKeyLine(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`&&segmentReferencesMenu(i)&&menuIssue(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??{}))segmentReferencesMenu(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:findKeyLine(e.source,[`segments`,t,`partials`,n])})}if(t.root!==void 0)for(let n of walkNodes(fragmentNode(t.root)))typeof n.when==`string`&&segmentReferencesMenu(n.when)&&menuIssue(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||!segmentReferencesMenu(r))continue;let n=parseCalls(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:identityIssue(r.apply);n!==void 0&&menuIssue(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function identityIssue(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(menuMember(e)===`closed`)return`whose apply action is named "${DISCLOSURE_CLOSED}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function synthesizePlacementMenus(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 presetNames(e.presets)){let a=new Map,s=new Map;for(let c of walkNodes(presetRoot(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,parseCalls(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=placementId(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||identityIssue(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=menuMember(i),f=menuStateKey(u,i,l.key),p=menuPageKey(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=menuActionName(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]=disclosureCycleAction(f,d),n[f]=disclosureStateVar(f,DISCLOSURE_CLOSED),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 endcapsNameMessage(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const STYLE_SCHEMA={noun:`style key`,fields:{hueShift:optionalNumberSpec(),chromaScale:optionalNumberSpec({min:0}),lightnessScale:optionalNumberSpec(),lightnessShift:optionalNumberSpec()}};function validateStyles(e,t){if(!isPlainObject$2(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${describeType(t)}`,line:findKeyLine(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:findKeyLine(e.source,[`styles`,r])});continue}if(isStyleEraEndcaps(r)){e.issues.push({path:`styles.${r}`,message:endcapsNameMessage(`styles.${r}`,r,`globals.endcaps`),line:findKeyLine(e.source,[`styles`,r])});continue}let t=record(e,STYLE_SCHEMA,`styles.${r}`,i);t!==null&&(n[r]={...IDENTITY,...t})}return n}const PRESET_SCHEMA={noun:`preset key`,fields:{root:{required:!1,json:{$ref:ROOT_FRAGMENT_REF},parse:(e,t,n,r)=>r[n]===void 0?void 0:validateRootFragment(e,`${t}.${n}`,r[n])},globals:{required:!1,json:presetGlobalsJson(),parse:(e,t,n,r)=>r[n]===void 0?void 0:validatePresetGlobals(e,`${t}.${n}`,r[n])}}};function validatePresets(e,t){if(!isPlainObject$2(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${describeType(t)}`,line:findKeyLine(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:findKeyLine(e.source,[`presets`,r])});continue}let t=record(e,PRESET_SCHEMA,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function presenceOf(e,t){let n=[...t].map(([e,t])=>[ownedBy(e),t]);return t=>{if(isSettingsAnchor(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=scopeOf(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function reportable(e){return e.kind===`plugin`||e.kind===`missing`}function absentPlacement(e,t,n){let r=new Map,i=(e,t)=>{r.set(e,[...r.get(e)??[],t])},a=e=>isRowsFragment(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 walkNodes(e))t.kind===`segment`&&i(placementId(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 withoutUnplaced(e){let t=0,n=presenceOf(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)?[mapOpens(e,i)]:[],o=e=>a(e)[0]??EMPTY_ROW,s=e=>({...e,rows:Object.fromEntries(Object.entries(e.rows).map(([e,t])=>[e,o(t)]))}),c=e=>isRowsFragment(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 EMPTY_ROW={kind:`container`,direction:`horizontal`,children:[]},UNREAD_DISTRIBUTION={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 presetIdentCollisions(e,t){let n=new Map;for(let e of Object.keys(t)){let t=ident(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:findKeyLine(e.source,[`presets`])})}function authoredPlacement(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 fragmentNodePaths(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const unplacedMessage=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${pluginNs(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${pluginDeclares(pluginNs(r.definition),n)}${missingSegmentHint(t,n)}`:`${e} entry "${t}" does not match any declared segment${missingSegmentHint(t,n)}`;function pluginDeclares(e,t){let n=Object.keys(t).filter(ownedBy(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 missingSegmentHint(e,t){return renamedHint(e)+otherScopeHint(e,e=>Object.hasOwn(t,e))}function validateCrossReferences(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||isExpression(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:isStyleEraEndcaps(r)?endcapsNameMessage(i,r,a):`${i} "${r}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:findKeyLine(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:findKeyLine(e.source,[`globals`,`preset`])}),presetIdentCollisions(e,t.presets);let a=templateScopeOf(t);for(let t of a.names)t!==`settings`&&!t.startsWith(SETTINGS_SCOPE_PREFIX)||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:findKeyLine(e.source,[`variables`,t])});let o=(t,n,i)=>{countAnchors(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${SETTINGS_ANCHOR}" ${countAnchors(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}),anchorUnderGate(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${SETTINGS_ANCHOR}" 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:UNREAD_DISTRIBUTION[a](n),line:i});let o=new Map;for(let e of walkNodes(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=placementId(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=freePlacementId(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`||AXIS_OF[e.direction]===`cell`);return AXIS_OF[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:AXIS_OF[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,childPath(t,n)]):e.opens===void 0?[]:[[e.opens.body,bodyPath(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=fragmentNode(n),s=isRowsFragment(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:UNREAD_DISTRIBUTION[t](n),line:findKeyLine(e.source,n.split(`.`))});for(let[o,s]of fragmentNodePaths(n,i)){let n=findKeyLine(e.source,s.split(`.`));if(o.when!==void 0&&(checkTemplateRefs(e,`${s}.when`,o.when,a,{line:n}),checkWhenParses(e,`${s}.when`,o.when,n),checkActionRefs(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if(isSettingsAnchor(o.name)){(o.id!==void 0||o.settings!==void 0)&&e.issues.push({path:s,message:`${i} gives the global settings menu anchor "${SETTINGS_ANCHOR}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${SETTINGS_ANCHOR}"`,line:n});continue}let c=r(o.name);reportable(c)&&(d.add(o.name),e.unplaced.push({path:s,message:unplacedMessage(i,o.name,t.segments,c),line:n})),checkPlacementSettings(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`,rootNode(t.root)]]);for(let e of presetNames(t.presets)){let{node:n,path:r}=presetRoot(t,e);p.set(r,n)}for(let[t,n]of p)o(n,t,findKeyLine(e.source,t.split(`.`)));for(let[n,i]of p)for(let[a]of walkNodePaths(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);reportable(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:unplacedMessage(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:findKeyLine(e.source,n.split(`.`))}))}validateDeclarations(e,t,a,()=>!0)}const TREE_OP_ARMS=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function checkPresetRootTarget(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=findKeyLine(e.source,[`actions`,n,r]);if(!presetNames(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${presetNames(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(`, `)})${renamedHint(i)}`,line:c})},p=new Set(placementIds(presetRoot(t,a).node)),m=(r,i)=>{!RENAMED_SEGMENTS.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${renamedHint(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 SETTINGS_SCOPE_PREFIX=`settings.`;function withSettingsScope(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>SETTINGS_SCOPE_PREFIX+e)])}}function checkSettingOrder(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:findKeyLine(e.source,[`segments`,t,`settings`,n])})},a=floorProblems(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of settingOrderProblems(n,defaultsOf(n)))i(e,`the defaults do not stand together: ${t}`)}function relationsReported(e){return floorProblems(e).length>0||settingOrderProblems(e,defaultsOf(e)).length>0}function defaultsOf(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function floorProblems(e){let t=t=>rangeOf$1(own(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||rangeOf$1(own(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${rangeSettingNames(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 own(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function rangeSettingNames(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&rangeOf$1(n)!==void 0).map(([e])=>e)}function checkPlacementSettings(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=settingsOf(a),s=`${r}: placement "${placementId(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(`, `)})`:inSettingDomain(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?retiredThemeNote(a):``}, but it must be ${describeSettingDomain(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])=>inSettingDomain(o[e],t))||relationsReported(o)))for(let{message:t}of settingOrderProblems(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function checkVarRefs(e,t,n,r,i){for(let[a,o]of variableTemplates(n))checkTemplateRefs(e,`${t}.${a}`,o,r,{segCtx:i})}function checkDependsOn(e,t,n,r,i){if(!(!hasCacheField(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:findKeyLine(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const INSTANT_POLICY=`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 checkPolicyInstant(e,t,n,r){if(!hasCacheField(n))return;let i=n=>findKeyLine(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=instantReadOf(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${INSTANT_POLICY}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=projectionsOf(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}: ${INSTANT_POLICY}`,line:i(`depends_on`)})})}}function checkRuleSlotReads(e,t){let n=new Map(declaredVariables(t)),r=valueReadsOf(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=EXPRESSION_SLOTS.find(e=>SLOT_PATHS[e]===n||SLOT_PATHS[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${SLOT_PATHS[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=payloadPathOf(e,a),s=o===void 0?void 0:slotAt(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 authoredRules(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:findKeyLine(e.source,[...n])})}}function checkWhenParses(e,t,n,r){try{SYNTAX_ENGINE.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function checkActionRefs(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 templateActionRefs(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){checkHelperIssue(e,u,`Template references unknown action "${c}"${r}`,helperKeyPath(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function checkTemplateRefs(e,t,n,r,i){for(let[a,o]of templateReads(n,r.helpers)){if(refResolves(a,r))continue;if(a.startsWith(SETTINGS_SCOPE_PREFIX)){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??findKeyLine(e.source,t.split(`.`))});continue}if(o!==null){checkHelperIssue(e,o,`Template references unknown variable ".${a}"${retiredReadHint(a)}`,helperKeyPath(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&&refResolves(n,r)?` (segment-local vars are namespaced — write ".${n}")`:retiredReadHint(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??findKeyLine(e.source,t.split(`.`))})}}function helperKeyPath(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function checkHelperIssue(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:findKeyLine(e.source,r)})}function checkSettingWrites(e,t,n,r,i){let a=n.set,o=settingControlDomain(SETTINGS[r].configKey),s=`${a} takes ${describeControlDomain(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:findKeyLine(e.source,[`actions`,t,`min`])});return}let c=setWrites(n,i);if(c===ANY_INTEGER){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:findKeyLine(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!controlDomainAdmits(o,e.value,i));if(l.length!==0){if(a===SETTINGS.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>isStyleEraEndcaps(e.value)))){let r=SETTINGS.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:endcapsNameMessage(`actions.${t}.to`,n.to,`set: "${r}", to`),line:findKeyLine(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:findKeyLine(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<=REPORTED_VALUES?r.join(`, `):`${r.slice(0,REPORTED_VALUES).join(`, `)} and ${r.length-REPORTED_VALUES} 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:findKeyLine(e.source,[`actions`,t,n])})}}}const REPORTED_VALUES=3,ANY_INTEGER=Symbol(`any integer`);function setWrites(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?resolveOptionDomain(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)}]:ANY_INTEGER}function subjects(e,t){return Object.entries(e).filter(([e])=>t(e))}function validateDeclarations(e,t,n,r){let i=configOptionDomains(t),a=knownOptionDomainNames(i);for(let[n,o]of subjects(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 ${unknownOptionDomain(r,i)}`,line:findKeyLine(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;CONFIG_ONLY_KEYS.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:findKeyLine(e.source,[`actions`,n,`set`])});let s=SESSION_KEY_TO_SETTING.get(o.set);s!==void 0&&checkSettingWrites(e,n,o,s,i)}for(let[n,i]of subjects(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&&actionBindsTemplateValue(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:findKeyLine(e.source,[`actions`,n,`do`])})});for(let[n,i]of subjects(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:findKeyLine(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of subjects(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=parsePersistTarget(r);if(o===null){let t=removedGlobalPointer(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${listGlobalsFieldNames().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:findKeyLine(e.source,[`actions`,n,a])});continue}let s=TREE_OP_ARMS.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:findKeyLine(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){checkPresetRootTarget(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!presetNames(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: ${presetNames(t.presets).join(`, `)})`,line:findKeyLine(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${retiredThemeNote(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:findKeyLine(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(`, `)})${renamedHint(o.segment)}`,line:findKeyLine(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:findKeyLine(e.source,[`actions`,n,a])})}}for(let[i,a]of subjects(t.variables,r)){checkVarRefs(e,`variables.${i}`,a,n);let t=retiredVariableMessage(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:findKeyLine(e.source,[`variables`,i])})}for(let[i,a]of subjects(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))checkVarRefs(e,`segments.${i}.vars.${t}`,r,n,i);let r=settingsOf(a);if(checkSettingOrder(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:findKeyLine(e.source,[`segments`,i,`partials`,t])});let o=a.partials===void 0?n.helpers:{...n.helpers,...a.partials},s=withSettingsScope({...n,helpers:o},r);for(let n of SEGMENT_TEMPLATE_FIELDS){let c=a[n];typeof c==`string`&&(checkTemplateRefs(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),checkActionRefs(e,t,`segments.${i}.${n}`,c,findKeyLine(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of subjects(t.variables,r))checkDependsOn(e,`variables.${i}`,a,n),checkPolicyInstant(e,`variables.${i}`,a,t);checkRuleSlotReads(e,t);for(let[i,a]of subjects(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))checkDependsOn(e,`segments.${i}.vars.${r}`,o,n,i),checkPolicyInstant(e,`segments.${i}.vars.${r}`,o,t)}function validateNoCycles(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=buildTemplateGraph(t),a=0,o=1,s=2,c=new Map,l=[];for(let e of r.keys())c.set(e,0);for(let e of r.keys())if(!(!n(e)||c.get(e)!==0)&&u(e))return;function u(t){c.set(t,1),l.push(t);for(let a of r.get(t)??[]){if(!n(a))continue;let t=c.get(a);if(t===1){let t=l.indexOf(a),n=[...l.slice(t),a],r=n[0],o=i.get(r);return e.issues.push({path:o?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:findKeyLine(e.source,o?.linePathParts??[`variables`,r])}),!0}if(t===0&&u(a))return!0}return c.set(t,2),l.pop(),!1}}function buildTemplateGraph(e){let t=new Map,n=new Map,r=valueReadsOf(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 validateNoNesting(e,t,n){let r=new Map([...declarationsAt(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, a control the bar builds, or the daemon's payload), 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:findKeyLine(e.source,[...d])})}}}function pluginRoots(e,t){let n=[...[...e.dataDirs].reverse().map(e=>path.join(e,`cc-candybar`,`plugins`)),userPluginRoot(e)];return[...n.filter((e,t)=>n.lastIndexOf(e)===t).map(e=>({dir:e,scope:`plugins`})),...t===null?[]:[{dir:path.join(t,REPO_PLUGIN_DIR),scope:`repo`}]]}function userPluginRoot(e){return path.join(e.dataHome,`cc-candybar`,`plugins`)}const REPO_PLUGIN_DIR=path.join(`.cc-candybar`,`plugins`);function installedPlugins(e,t){let n=pluginRoots(e,t),r=new Map,i=[],a=[];for(let{dir:e,scope:t}of n){let n=listFolders(e);if(`error`in n){i.push(n);continue}for(let i of n.folders){let n=pluginDefinition(path.join(e,i,DEFINITION_FILE),t),a=`${t}\0${i}`;r.delete(a),r.set(a,n)}for(let r of n.files)a.push({path:path.join(e,r),scope:t,name:void 0,reason:`a plugin is a folder holding its ${DEFINITION_FILE}: move this file to ${path.join(e,`<name>`,DEFINITION_FILE)}`})}return{roots:n.map(e=>e.dir),definitions:[...r.values()],unchecked:i,strays:a}}function listFolders(e){try{let t=fs.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()||isDirectoryLink(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 isDirectoryLink(e,t){if(!t.isSymbolicLink())return!1;try{return fs.statSync(path.join(e,t.name)).isDirectory()}catch{return!0}}const CONFIG_EXTENSIONS=[`json5`,`json`];function dslConfigCandidatePaths(e,t,n,r){if(r!==void 0)return[r];let i=n??process.cwd();return[...new Set([...t?CONFIG_EXTENSIONS.map(e=>path.join(t,`${REPO_CONFIG_BASE}.${e}`)):[],...CONFIG_EXTENSIONS.map(e=>path.join(i,`${REPO_CONFIG_BASE}.${e}`)),...CONFIG_EXTENSIONS.map(t=>`${xdgConfigBase(e)}.${t}`)])]}const REPO_CONFIG_BASE=`.cc-candybar`;function xdgConfigBase(e){return path.join(e.configHome,`cc-candybar`,`config`)}function homeLayer(e){return{path:e,scope:`plugins`}}function resolveDslConfig(e,t,n,r,i){let a=[],o=new Map;for(let t of dslConfigCandidatePaths(e,n,r,i)){let n=presence(t);if(n===`absent`)continue;if(n!==`present`){a.push(n);continue}let r=fs.realpathSync.native(path.dirname(t)),s=path.join(r,path.basename(t).replace(/\.(json5|json)$/,``));o.has(s)||o.set(s,{file:t,repo:i!==void 0||isUserFile(e,t)?null:{dir:r,link:worktreeLink(r)}})}let s=[...o.values()],c=gateRepos(t,s.flatMap(e=>e.repo===null?[]:[e.repo]),repoProject(n)),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(i===void 0)return{kind:`chain`,layers:l,home:userHome(e,l),unchecked:a,repos:c};let[u]=a,d=i;return l.length>0?{kind:`chain`,layers:l,home:d,unchecked:a,repos:c}:u===void 0?{kind:`missing`,path:i,home:d,repos:c}:{kind:`unreadable`,...u,home:d,repos:c}}function isUserFile(e,t){return CONFIG_EXTENSIONS.some(n=>t===`${xdgConfigBase(e)}.${n}`)}function repoProject(e){if(e===void 0||presence(e)!==`present`)return null;let t=listFolders(path.join(e,REPO_PLUGIN_DIR)),n=fs.realpathSync.native(e);return{dir:n,link:worktreeLink(n),path:e,ships:!(`error`in t)&&t.folders.length>0}}function userHome(e,t){return t.find(t=>isUserFile(e,t.path))?.path??`${xdgConfigBase(e)}.${CONFIG_EXTENSIONS[0]}`}function durableConfig(e,t,n,r,i){let a=resolveDslConfig(e,t,n,r,i),o=a.kind===`chain`?a.layers:[];return{path:a.home,above:o.filter(e=>e.path!==a.home),repo:a.repos.plugins,cwd:r??null,locs:e}}function configResolutionNotice(e){return noticeLines(e).join(`
|
|
220
|
-
`)||null}function noticeLines(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 detectConfigCollisions(e,t,n){let r=dslConfigCandidatePaths(e,t,n).filter(e=>presence(e)===`present`),i=new Map;for(let e of r){let t=path.dirname(e),n=path.basename(e).replace(/\.(json5|json)$/,``),r=path.join(t,n);i.has(r)||i.set(r,[]),i.get(r).push(e)}let a=[...i.values()].filter(e=>e.length>1);return a.length===0?null:`config-extension collision: ${a.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function noFile(e){return{...NO_FILE,config:mergeWithDefault(NO_FILE.raw,e)}}function loadConfigSource(e,t,n,r,i){let a=parseDslFile(e,t,i,(t,a)=>{let o=applyPlugins(listedPlugins(t,e,r.scope,r.home),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>checkPlugin(t,n,r,e,i)),s=dropsOwning(o,r.beneath.dropped);return{inherited:new Set([...inheritableSegmentNames(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=withDroppedPlacements(mergeWithDefault(a.raw,o.config),s,(a.raw.insert??[]).map(e=>e.seg));return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(droppedPluginNotice)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const installedMemo=new WeakMap;function installedLayer(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e.path,e.scope,statKey(e.path)])]),a=installedMemo.get(n)??new Map;installedMemo.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=applyPlugins(e,t,{config:n,rendering:new Map},(e,t,n)=>checkPlugin(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function definitionProblems(e,t,n,r){return applyPlugins(e,{repo:null,checkout:n,home:r},{config:t,rendering:new Map},(e,t,n)=>checkPlugin(e,t,n,`<plugin install>`,void 0)).dropped}function statKey(e){try{let t=fs.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function loadConfigChain(e,t,n,r,i,a=e=>fs.readFileSync(e,`utf-8`),o){let s={repo:i.repo,checkout:i.cwd===null?null:checkoutOf(i.cwd),home:e.home},c=installedPlugins(e,s.repo),l=installedLayer(c.definitions,s,n,o),u={...l,dropped:[...l.dropped,...c.strays]};r.warned(c.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let d=u.config,f=[];for(let{path:e,scope:n}of t){let t=f.at(-1)?.plugins,i=loadConfigSource(e,a(e),f.at(-1)?.config??d,{...s,scope:n,beneath:{dropped:[...u.dropped,...f.flatMap(e=>e.plugins.dropped)],rendering:t?.rendering??u.rendering}},o);r.warned(i.warnings),f.push({...i,path:e})}let p=new Set(f.flatMap(e=>[...e.plugins.reached])),m=e=>p.has(e.path),h=u.dropped.filter(m),g=u.dropped.filter(e=>!m(e));r.warned(h.map(droppedPluginNotice));let _=f.at(-1)?.plugins.rendering??u.rendering,v={checkout:s.checkout,roots:c.roots,loaded:u.loaded,dropped:h,unreached:g,reached:p,rendering:_},y=f.at(-1),b=({warnings:e,...t})=>(r.warned(e),t);if(y===void 0)return{layers:f,base:d,installed:v,...b(validateRenderable(noFile(d),_,`<default>`,o))};try{return{layers:f,base:d,installed:v,...b(validateRenderable(y,_,y.path,o,f.slice(0,-1).reverse()))}}catch(e){for(let[e,t]of f.slice(0,-1).entries())validateRenderable(t,t.plugins.rendering,t.path,o,f.slice(0,e).reverse());throw e}}function checkPlugin(e,t,n,r,i){if(n){validateRenderable(unauthored(e),new Map,r,i);return}let a=ownedBy(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[],unplaced:[],inherited:[]};if(validateDeclarations(s,e,templateScopeOf(e),a),validateNoCycles(s,e,a),validateNoNesting(s,e,{checked:a,authored:a}),o.length>0)throw new ConfigError(r,o)}function unauthored(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const NO_FILE={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function validateRenderable(e,t,n=`<config>`,r=new Set(listResolvablePaletteNames()),i=[]){let a=presenceOf(e.config.segments,t),o=layerInserts({...e,path:n},i,a),s=(t,s)=>{let c=placeInserts(e.config,t,o.authored);return judgeRenderable(e,n,r,i,c.config,a,o.dropped,[...c.notices,...s])};try{return s(o.cells,[])}catch(e){if(!(e instanceof ConfigError)||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 ConfigError))throw r;let i=r.issues.filter(e=>!n.has(e.message)).map(e=>e.message).join(`; `);return{...e,refused:[...e.refused,insertNotice(t,`${t.relation} "${t.anchor}", but the bar refuses it there: ${i}`)]}}},{taken:[],refused:[]});return s(r,i)}}function judgeRenderable({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 ConfigError(n,[...l,...u.unplaced,...u.inherited],c)};validateCrossReferences(u,a,e,o),validateNoCycles(u,a),d();let f=droppedByFile(n,a.segments,u,o,i,s),p=synthesizePlacementMenus(withoutUnplaced(a),l);d();let m=synthesizeEditChrome(synthesizeSettingsMenu(p)),h=new Set([...declarationsAt({variables:e.variables??{},segments:e.segments??{}})].map(([e])=>e));return validateNoNesting(u,m,{checked:()=>!0,authored:e=>h.has(e)}),d(),{config:m,dropped:f,placed:a,warnings:c}}function layerInserts(e,t,n){let r=[...t].reverse().concat(e),i=absentPlacement(e.config,r.flatMap(e=>e.raw.insert??[]),n),a=e=>!i(e.anchor),o=e=>n(e.seg).kind===`declared`,s=e=>reportable(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=keyLocator(t.source);return(t.raw.insert??[]).filter(s).map(i=>({file:t.path,issue:{path:i.by.entry,message:unplacedMessage(i.by.entry,i.seg,e.config.segments,n(i.seg)),line:r(i.by.entry.split(`.`))}}))})}}function refuseDrops(e){if(e.length>0)throw new DroppedPlacements(e)}function droppedByFile(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=authoredPlacement(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:unplacedMessage(n.layoutKey,a,t,r(a)),line:findKeyLine(n.layer.source,n.path.split(`.`))})}return[...o].map(([e,t])=>new DroppedFileError(e,t))}function parseDslConfig(e,t,n=new Set(listResolvablePaletteNames()),r=NO_INHERITED_SEGMENTS){return parseDslFile(e,t,n,()=>({inherited:r,layer:null})).raw}function parseDslFile(e,t,n,r){let i=parseJson5OrThrow(e,t),a=editabilityNotice(e,t),o=[...a===null?[]:[a],...payloadDeclarationNotices(e,t,isPlainObject$2(i)&&isPlainObject$2(i.variables)?Object.keys(i.variables):[])],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(listResolvablePaletteNames()),groups:[],unplaced:[],inherited:[]};if(!isPlainObject$2(i))throw new ConfigError(e,[{path:``,message:`Config root must be an object, got ${describeType(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:validatePluginRefs({...c,issues:[]},i.plugins)??[],isPlainObject$2(i.segments)?Object.keys(i.segments):[]),d=validateTopLevel(c,i,l,actionHomeOf(e),e);if(s.length>0)throw new ConfigError(e,s,o);return{raw:d,warnings:o,layer:u}}const NO_INHERITED_SEGMENTS=new Set;function parseJson5OrThrow(e,t){try{return import_lib.default.parse(t)}catch(t){let n=t;throw new ConfigError(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function validateTopLevel(e,t,n,r,i){for(let n of Object.keys(t))TOP_LEVEL_KEYS.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...TOP_LEVEL_KEYS].join(`, `)}`,line:findKeyLine(e.source,[n])});let a={};return t.globals!==void 0&&(a.globals=validateGlobals(e,`globals`,t.globals)),t.variables!==void 0&&(a.variables=validateVariables(e,`variables`,t.variables)),t.segments!==void 0&&(a.segments=validateSegments(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.
|
|
223
|
+
New: { h: ["seg1", "seg2"] }`,line:findKeyLine(e.source,[`root`])}),EMPTY_VERTICAL_NODE;if(n.kind===`group`){let r=record(e,GROUP_SCHEMA,t,n);return r===null?EMPTY_VERTICAL_NODE:(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}),lowerGroup(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:findKeyLine(e.source,[`root`])}),EMPTY_VERTICAL_NODE}if(a){let r=record(e,SEG_ARM_SCHEMA,t,n);return r===null?EMPTY_VERTICAL_NODE:{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=record(e,H_ARM_SCHEMA,t,n);return r===null?EMPTY_VERTICAL_NODE:{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=record(e,V_ARM_SCHEMA,t,n);return r===null?EMPTY_VERTICAL_NODE:{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:findKeyLine(e.source,[`root`])}),EMPTY_VERTICAL_NODE};function rowsSpec(){return{required:!0,json:{type:`object`,propertyNames:{pattern:ROW_NAME_RE.source},additionalProperties:{$ref:LAYOUT_NODE_REF}},parse:(e,t,n,r)=>{let i=r[n];if(!isPlainObject$2(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${describeType(i)}`,line:findKeyLine(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!ROW_NAME_RE.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:findKeyLine(e.source,[...t.split(`.`),n,r])});continue}a[r]=validateRoot(e,`${t}.${n}.${r}`,o)}return a}}}const ROWS_SCHEMA={noun:`root key`,fields:{rows:rowsSpec(),when:optionalStringSpec(),distribution:distributionSpec()}};function validateRootFragment(e,t,n){return isPlainObject$2(n)&&`rows`in n?record(e,ROWS_SCHEMA,t,n)??{rows:{}}:validateRoot(e,t,n)}const INSERT_SCHEMA={noun:`insert key`,fields:{seg:segArmSpec(),id:placementIdSpec(),before:optionalStringSpec(),after:optionalStringSpec()}};function validateInsert(e,t,n){return Array.isArray(t)?t.flatMap((t,r)=>{let i=`insert.${r}`,a=record(e,INSERT_SCHEMA,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:findKeyLine(e.source,i.split(`.`))}),[];if(isReservedName(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:findKeyLine(e.source,[...i.split(`.`),`seg`])}),[];let s=o[0],c=a[s];return isReservedName(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:findKeyLine(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 ${describeType(t)}`,line:findKeyLine(e.source,[`insert`])}),[])}function groupNameSpec(){return{required:!0,json:{type:`string`,pattern:ROW_NAME_RE.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!ROW_NAME_RE.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 "${DISCLOSURE_CLOSED}", got ${describeValue(i)}`,line:findKeyLine(e.source,[`root`])});return}return i}}}function groupKeySpec(){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 ${describeValue(i)}`,line:findKeyLine(e.source,[`root`])});return}return i}}}}function groupLabelSpec(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=requireString(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:findKeyLine(e.source,[...t.split(`.`),n])});return}return i}}}}const GROUP_SCHEMA={noun:`layout-node key`,fields:{kind:literalSpec(`group`),name:groupNameSpec(),label:groupLabelSpec(),open:optionalBooleanSpec(),direction:optionalEnumSpec(DIRECTIONS),key:groupKeySpec(),bg:optionalStringSpec(),fg:optionalStringSpec(),when:optionalStringSpec(),distribution:distributionSpec(),children:childrenSpec(lazy(()=>validateRoot))}};function groupStateKey(e){return e.key??`groups.`+e.name}function lowerGroup(e){let t=GROUP_NS+e.name;return disclosureNode(t,{variable:t,key:groupStateKey(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function groupIssue(e,t,n){e.issues.push({path:t,message:n,line:findKeyLine(e.source,[`root`])})}function synthesizeGroupDecls(e,t){reservedNamespaceCollisions(e,t,GROUP_NS,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&groupIssue(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}.`)&&groupStateKey(t)===groupStateKey(r)&&groupIssue(e,t.path,`group "${t.name}" shares key "${groupStateKey(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=groupStateKey(t);if(i.has(n)||i.set(n,DISCLOSURE_CLOSED),t.open===!0){let r=i.get(n);r!==`closed`&&groupIssue(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=GROUP_NS+e.name,r=groupStateKey(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=disclosureStateVar(r,i.get(r)),o[t]=disclosureCycleAction(r,e.name),s[t]={template:disclosureTrigger(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 MENU_FUNC=`menu`,MIGRATION=`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`,isDictCall=e=>e.kind===`call`&&e.name===`dict`,isNonObjectLiteral=e=>e.kind===`literal`&&typeof e.value!=`object`,legalDisplayCount=e=>cycleDisplayIssue(``,e,2)===void 0;function analyzeMenuCall(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&&isDictCall(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(isDictCall))return t(`whose options (dict …) is not its last argument — ${MIGRATION}`);if(i!==void 0&&a===void 0&&!isNonObjectLiteral(i)&&legalDisplayCount(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=cycleDisplayIssue(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${MIGRATION}`);let c=a===void 0?{}:staticDictEntries(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=parseMenuOptions(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=reservedNamespaceOf(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 "${sharedMenuStateKey(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 parseCalls(e){let t=createEngine({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===MENU_FUNC).map(analyzeMenuCall)}catch{return`parse-failed`}}function hostedMenus(e,t){let n=parseCalls(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:menuStateKey(t,e.apply,e.options.key),member:menuMember(e.apply)}]:[])}function segmentReferencesMenu(e){let t=createEngine({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(MENU_FUNC)}catch{return!1}}function menuIssue(e,t,n){e.issues.push({path:t,message:n,line:findKeyLine(e.source,[`root`])})}function checkMenuDecls(e,t){reservedNamespaceCollisions(e,t,MENU_NS,`{{ menu }} helpers`),reservedNamespaceCollisions(e,t,MENU_PAGE_NS,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))segmentReferencesMenu(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:findKeyLine(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`&&segmentReferencesMenu(i)&&menuIssue(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??{}))segmentReferencesMenu(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:findKeyLine(e.source,[`segments`,t,`partials`,n])})}if(t.root!==void 0)for(let n of walkNodes(fragmentNode(t.root)))typeof n.when==`string`&&segmentReferencesMenu(n.when)&&menuIssue(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||!segmentReferencesMenu(r))continue;let n=parseCalls(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:identityIssue(r.apply);n!==void 0&&menuIssue(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function identityIssue(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(menuMember(e)===`closed`)return`whose apply action is named "${DISCLOSURE_CLOSED}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function synthesizePlacementMenus(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 presetNames(e.presets)){let a=new Map,s=new Map;for(let c of walkNodes(presetRoot(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,parseCalls(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=placementId(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||identityIssue(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=menuMember(i),f=menuStateKey(u,i,l.key),p=menuPageKey(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=menuActionName(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]=disclosureCycleAction(f,d),n[f]=disclosureStateVar(f,DISCLOSURE_CLOSED),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 endcapsNameMessage(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const STYLE_SCHEMA={noun:`style key`,fields:{hueShift:optionalNumberSpec(),chromaScale:optionalNumberSpec({min:0}),lightnessScale:optionalNumberSpec(),lightnessShift:optionalNumberSpec()}};function validateStyles(e,t){if(!isPlainObject$2(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${describeType(t)}`,line:findKeyLine(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:findKeyLine(e.source,[`styles`,r])});continue}if(isStyleEraEndcaps(r)){e.issues.push({path:`styles.${r}`,message:endcapsNameMessage(`styles.${r}`,r,`globals.endcaps`),line:findKeyLine(e.source,[`styles`,r])});continue}let t=record(e,STYLE_SCHEMA,`styles.${r}`,i);t!==null&&(n[r]={...IDENTITY,...t})}return n}const PRESET_SCHEMA={noun:`preset key`,fields:{root:{required:!1,json:{$ref:ROOT_FRAGMENT_REF},parse:(e,t,n,r)=>r[n]===void 0?void 0:validateRootFragment(e,`${t}.${n}`,r[n])},globals:{required:!1,json:presetGlobalsJson(),parse:(e,t,n,r)=>r[n]===void 0?void 0:validatePresetGlobals(e,`${t}.${n}`,r[n])}}};function validatePresets(e,t){if(!isPlainObject$2(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${describeType(t)}`,line:findKeyLine(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:findKeyLine(e.source,[`presets`,r])});continue}let t=record(e,PRESET_SCHEMA,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function presenceOf(e,t){let n=[...t].map(([e,t])=>[ownedBy(e),t]);return t=>{if(isSettingsAnchor(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=scopeOf$1(t);return i!==void 0&&i!==t?{kind:`absent`}:{kind:`missing`}}}function reportable(e){return e.kind===`plugin`||e.kind===`missing`}function absentPlacement(e,t,n){let r=new Map,i=(e,t)=>{r.set(e,[...r.get(e)??[],t])},a=e=>isRowsFragment(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 walkNodes(e))t.kind===`segment`&&i(placementId(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 withoutUnplaced(e){let t=0,n=presenceOf(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)?[mapOpens(e,i)]:[],o=e=>a(e)[0]??EMPTY_ROW,s=e=>({...e,rows:Object.fromEntries(Object.entries(e.rows).map(([e,t])=>[e,o(t)]))}),c=e=>isRowsFragment(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 EMPTY_ROW={kind:`container`,direction:`horizontal`,children:[]},UNREAD_DISTRIBUTION={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 presetIdentCollisions(e,t){let n=new Map;for(let e of Object.keys(t)){let t=ident(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:findKeyLine(e.source,[`presets`])})}function authoredPlacement(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 fragmentNodePaths(r,e))if(n.kind===`segment`&&n.name===t)return{layoutKey:e,path:i}}}const unplacedMessage=(e,t,n,r)=>r.kind===`plugin`?`${e} entry "${t}" does not match any segment plugin "${pluginNs(r.definition)}" declares — the plugin loaded from ${r.definition.path} declares: ${pluginDeclares(pluginNs(r.definition),n)}${missingSegmentHint(t,n)}`:`${e} entry "${t}" does not match any declared segment${missingSegmentHint(t,n)}`;function pluginDeclares(e,t){let n=Object.keys(t).filter(ownedBy(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 missingSegmentHint(e,t){return renamedHint(e)+otherScopeHint(e,e=>Object.hasOwn(t,e))}function validateCrossReferences(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||isExpression(r)||Object.prototype.hasOwnProperty.call(t.styles,r))continue;let i=`${n.join(`.`)}.style`;e.issues.push({path:i,message:isStyleEraEndcaps(r)?endcapsNameMessage(i,r,a):`${i} "${r}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:findKeyLine(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:findKeyLine(e.source,[`globals`,`preset`])}),presetIdentCollisions(e,t.presets);let a=templateScopeOf(t);for(let t of a.names)t!==`settings`&&!t.startsWith(SETTINGS_SCOPE_PREFIX)||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:findKeyLine(e.source,[`variables`,t])});let o=(t,n,i)=>{countAnchors(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${SETTINGS_ANCHOR}" ${countAnchors(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}),anchorUnderGate(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${SETTINGS_ANCHOR}" 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:UNREAD_DISTRIBUTION[a](n),line:i});let o=new Map;for(let e of walkNodes(t)){if(e.kind!==`segment`||r(e.name).kind!==`declared`)continue;let t=placementId(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=freePlacementId(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`||AXIS_OF[e.direction]===`cell`);return AXIS_OF[e.direction]===`row`&&!n?t:void 0}let c=(e,t)=>e.kind===`segment`?`band`:AXIS_OF[e.direction]===`cell`?`nested`:t,l=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,childPath(t,n)]):e.opens===void 0?[]:[[e.opens.body,bodyPath(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=fragmentNode(n),s=isRowsFragment(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:UNREAD_DISTRIBUTION[t](n),line:findKeyLine(e.source,n.split(`.`))});for(let[o,s]of fragmentNodePaths(n,i)){let n=findKeyLine(e.source,s.split(`.`));if(o.when!==void 0&&(checkTemplateRefs(e,`${s}.when`,o.when,a,{line:n}),checkWhenParses(e,`${s}.when`,o.when,n),checkActionRefs(e,t,`${s}.when`,o.when,n)),o.kind!==`segment`)continue;if(isSettingsAnchor(o.name)){(o.id!==void 0||o.settings!==void 0)&&e.issues.push({path:s,message:`${i} gives the global settings menu anchor "${SETTINGS_ANCHOR}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${SETTINGS_ANCHOR}"`,line:n});continue}let c=r(o.name);reportable(c)&&(d.add(o.name),e.unplaced.push({path:s,message:unplacedMessage(i,o.name,t.segments,c),line:n})),checkPlacementSettings(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`,rootNode(t.root)]]);for(let e of presetNames(t.presets)){let{node:n,path:r}=presetRoot(t,e);p.set(r,n)}for(let[t,n]of p)o(n,t,findKeyLine(e.source,t.split(`.`)));for(let[n,i]of p)for(let[a]of walkNodePaths(i,n)){if(a.kind!==`segment`||d.has(a.name))continue;let i=r(a.name);reportable(i)&&(d.add(a.name),e.inherited.push({name:a.name,path:n,message:unplacedMessage(`${n} inherits from a config layer below whose`,a.name,t.segments,i),line:findKeyLine(e.source,n.split(`.`))}))}validateDeclarations(e,t,a,()=>!0)}const TREE_OP_ARMS=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function checkPresetRootTarget(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=findKeyLine(e.source,[`actions`,n,r]);if(!presetNames(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${presetNames(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(`, `)})${renamedHint(i)}`,line:c})},p=new Set(placementIds(presetRoot(t,a).node)),m=(r,i)=>{!RENAMED_SEGMENTS.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${renamedHint(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 SETTINGS_SCOPE_PREFIX=`settings.`;function withSettingsScope(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>SETTINGS_SCOPE_PREFIX+e)])}}function checkSettingOrder(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:findKeyLine(e.source,[`segments`,t,`settings`,n])})},a=floorProblems(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of settingOrderProblems(n,defaultsOf(n)))i(e,`the defaults do not stand together: ${t}`)}function relationsReported(e){return floorProblems(e).length>0||settingOrderProblems(e,defaultsOf(e)).length>0}function defaultsOf(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function floorProblems(e){let t=t=>rangeOf$1(own(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||rangeOf$1(own(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${rangeSettingNames(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 own(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function rangeSettingNames(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&rangeOf$1(n)!==void 0).map(([e])=>e)}function checkPlacementSettings(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=settingsOf(a),s=`${r}: placement "${placementId(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(`, `)})`:inSettingDomain(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?retiredThemeNote(a):``}, but it must be ${describeSettingDomain(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])=>inSettingDomain(o[e],t))||relationsReported(o)))for(let{message:t}of settingOrderProblems(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function checkVarRefs(e,t,n,r,i){for(let[a,o]of variableTemplates(n))checkTemplateRefs(e,`${t}.${a}`,o,r,{segCtx:i})}function checkDependsOn(e,t,n,r,i){if(!(!hasCacheField(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:findKeyLine(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const INSTANT_POLICY=`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 checkPolicyInstant(e,t,n,r){if(!hasCacheField(n))return;let i=n=>findKeyLine(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=instantReadOf(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${INSTANT_POLICY}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=projectionsOf(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}: ${INSTANT_POLICY}`,line:i(`depends_on`)})})}}function checkRuleSlotReads(e,t){let n=new Map(declaredVariables(t)),r=valueReadsOf(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=EXPRESSION_SLOTS.find(e=>SLOT_PATHS[e]===n||SLOT_PATHS[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${SLOT_PATHS[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=payloadPathOf(e,a),s=o===void 0?void 0:slotAt(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 authoredRules(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:findKeyLine(e.source,[...n])})}}function checkWhenParses(e,t,n,r){try{SYNTAX_ENGINE.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function checkActionRefs(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 templateActionRefs(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){checkHelperIssue(e,u,`Template references unknown action "${c}"${r}`,helperKeyPath(u,o));continue}e.issues.push({path:n,message:`${s} references unknown action "${c}"${r}`,line:i})}}function checkTemplateRefs(e,t,n,r,i){for(let[a,o]of templateReads(n,r.helpers)){if(refResolves(a,r))continue;if(a.startsWith(SETTINGS_SCOPE_PREFIX)){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??findKeyLine(e.source,t.split(`.`))});continue}if(o!==null){checkHelperIssue(e,o,`Template references unknown variable ".${a}"${retiredReadHint(a)}`,helperKeyPath(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&&refResolves(n,r)?` (segment-local vars are namespaced — write ".${n}")`:retiredReadHint(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??findKeyLine(e.source,t.split(`.`))})}}function helperKeyPath(e,t){return t?.partials!==void 0&&Object.hasOwn(t.partials,e)?[`segments`,t.name,`partials`,e]:[`helpers`,e]}function checkHelperIssue(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:findKeyLine(e.source,r)})}function checkSettingWrites(e,t,n,r,i){let a=n.set,o=settingControlDomain(SETTINGS[r].configKey),s=`${a} takes ${describeControlDomain(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:findKeyLine(e.source,[`actions`,t,`min`])});return}let c=setWrites(n,i);if(c===ANY_INTEGER){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:findKeyLine(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!controlDomainAdmits(o,e.value,i));if(l.length!==0){if(a===SETTINGS.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>isStyleEraEndcaps(e.value)))){let r=SETTINGS.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:endcapsNameMessage(`actions.${t}.to`,n.to,`set: "${r}", to`),line:findKeyLine(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:findKeyLine(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<=REPORTED_VALUES?r.join(`, `):`${r.slice(0,REPORTED_VALUES).join(`, `)} and ${r.length-REPORTED_VALUES} 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:findKeyLine(e.source,[`actions`,t,n])})}}}const REPORTED_VALUES=3,ANY_INTEGER=Symbol(`any integer`);function setWrites(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?resolveOptionDomain(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)}]:ANY_INTEGER}function subjects(e,t){return Object.entries(e).filter(([e])=>t(e))}function validateDeclarations(e,t,n,r){let i=configOptionDomains(t),a=knownOptionDomainNames(i);for(let[n,o]of subjects(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 ${unknownOptionDomain(r,i)}`,line:findKeyLine(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;CONFIG_ONLY_KEYS.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:findKeyLine(e.source,[`actions`,n,`set`])});let s=SESSION_KEY_TO_SETTING.get(o.set);s!==void 0&&checkSettingWrites(e,n,o,s,i)}for(let[n,i]of subjects(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&&actionBindsTemplateValue(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:findKeyLine(e.source,[`actions`,n,`do`])})});for(let[n,i]of subjects(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:findKeyLine(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of subjects(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=parsePersistTarget(r);if(o===null){let t=removedGlobalPointer(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${listGlobalsFieldNames().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:findKeyLine(e.source,[`actions`,n,a])});continue}let s=TREE_OP_ARMS.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:findKeyLine(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){checkPresetRootTarget(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!presetNames(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: ${presetNames(t.presets).join(`, `)})`,line:findKeyLine(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${retiredThemeNote(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:findKeyLine(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(`, `)})${renamedHint(o.segment)}`,line:findKeyLine(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:findKeyLine(e.source,[`actions`,n,a])})}}for(let[i,a]of subjects(t.variables,r)){checkVarRefs(e,`variables.${i}`,a,n);let t=retiredVariableMessage(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:findKeyLine(e.source,[`variables`,i])})}for(let[i,a]of subjects(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))checkVarRefs(e,`segments.${i}.vars.${t}`,r,n,i);let r=settingsOf(a);if(checkSettingOrder(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:findKeyLine(e.source,[`segments`,i,`partials`,t])});let o=a.partials===void 0?n.helpers:{...n.helpers,...a.partials},s=withSettingsScope({...n,helpers:o},r);for(let n of SEGMENT_TEMPLATE_FIELDS){let c=a[n];typeof c==`string`&&(checkTemplateRefs(e,`segments.${i}.${n}`,c,s,{segCtx:i,settings:r,partials:a.partials}),checkActionRefs(e,t,`segments.${i}.${n}`,c,findKeyLine(e.source,[`segments`,i,n]),o,{name:i,partials:a.partials}))}}for(let[i,a]of subjects(t.variables,r))checkDependsOn(e,`variables.${i}`,a,n),checkPolicyInstant(e,`variables.${i}`,a,t);checkRuleSlotReads(e,t);for(let[i,a]of subjects(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))checkDependsOn(e,`segments.${i}.vars.${r}`,o,n,i),checkPolicyInstant(e,`segments.${i}.vars.${r}`,o,t)}function validateNoCycles(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=buildTemplateGraph(t),a=0,o=1,s=2,c=new Map,l=[];for(let e of r.keys())c.set(e,0);for(let e of r.keys())if(!(!n(e)||c.get(e)!==0)&&u(e))return;function u(t){c.set(t,1),l.push(t);for(let a of r.get(t)??[]){if(!n(a))continue;let t=c.get(a);if(t===1){let t=l.indexOf(a),n=[...l.slice(t),a],r=n[0],o=i.get(r);return e.issues.push({path:o?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:findKeyLine(e.source,o?.linePathParts??[`variables`,r])}),!0}if(t===0&&u(a))return!0}return c.set(t,2),l.pop(),!1}}function buildTemplateGraph(e){let t=new Map,n=new Map,r=valueReadsOf(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 validateNoNesting(e,t,n){let r=new Map([...declarationsAt(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, a control the bar builds, or the daemon's payload), 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:findKeyLine(e.source,[...d])})}}}function noFile(e){return{...NO_FILE,config:mergeWithDefault(NO_FILE.raw,e)}}function loadConfigSource(e,t,n,r,i){let a=parseDslFile(e,t,i,(t,a)=>{let o=applyPlugins(listedPlugins(t,e,r.scope,r.home),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>checkPlugin(t,n,r,e,i)),s=dropsOwning(o,r.beneath.dropped);return{inherited:new Set([...inheritableSegmentNames(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=withDroppedPlacements(mergeWithDefault(a.raw,o.config),s,(a.raw.insert??[]).map(e=>e.seg));return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(droppedPluginNotice)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const installedMemo=new WeakMap;function installedLayer(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e.path,e.scope,statKey(e.path)])]),a=installedMemo.get(n)??new Map;installedMemo.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=applyPlugins(e,t,{config:n,rendering:new Map},(e,t,n)=>checkPlugin(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function definitionProblems(e,t,n,r){return applyPlugins(e,{repo:null,checkout:n,home:r},{config:t,rendering:new Map},(e,t,n)=>checkPlugin(e,t,n,`<plugin install>`,void 0)).dropped}function statKey(e){try{let t=fs.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function loadConfigChain(e,t,n,r,i,a=e=>fs.readFileSync(e,`utf-8`),o){let{ctx:s,found:c,plugins:l,base:u,layers:d}=mergeChain(e,t,n,r,i,a,o);return validateChain(s,c,l,u,d,r,o)}function inheritedConfig(e,t,n,r,i){let{base:a,layers:o}=mergeChain(e,t,n,{warned:()=>{}},r,i);return o.at(-1)?.config??a}function mergeChain(e,t,n,r,i,a,o){let s={repo:i.repo,checkout:i.cwd===null?null:checkoutOf(i.cwd),home:e.home},c=installedPlugins(e,s.repo),l=installedLayer(c.definitions,s,n,o),u={...l,dropped:[...l.dropped,...c.strays]};r.warned(c.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let d=u.config,f=[];for(let{path:e,role:n}of t){let t=scopeOf(n),i=f.at(-1)?.plugins,c=loadConfigSource(e,a(e),f.at(-1)?.config??d,{...s,scope:t,beneath:{dropped:[...u.dropped,...f.flatMap(e=>e.plugins.dropped)],rendering:i?.rendering??u.rendering}},o);r.warned(c.warnings),f.push({...c,path:e})}return{ctx:s,found:c,plugins:u,base:d,layers:f}}function validateChain(e,t,n,r,i,a,o){let s=new Set(i.flatMap(e=>[...e.plugins.reached])),c=e=>s.has(e.path),l=n.dropped.filter(c),u=n.dropped.filter(e=>!c(e));a.warned(l.map(droppedPluginNotice));let d=i.at(-1)?.plugins.rendering??n.rendering,f={checkout:e.checkout,roots:t.roots,loaded:n.loaded,dropped:l,unreached:u,reached:s,rendering:d},p=i.at(-1),m=({warnings:e,...t})=>(a.warned(e),t);if(p===void 0)return{layers:i,base:r,installed:f,...m(validateRenderable(noFile(r),d,`<default>`,o))};try{return{layers:i,base:r,installed:f,...m(validateRenderable(p,d,p.path,o,i.slice(0,-1).reverse()))}}catch(e){for(let[e,t]of i.slice(0,-1).entries())validateRenderable(t,t.plugins.rendering,t.path,o,i.slice(0,e).reverse());throw e}}function checkPlugin(e,t,n,r,i){if(n){validateRenderable(unauthored(e),new Map,r,i);return}let a=ownedBy(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[],unplaced:[],inherited:[]};if(validateDeclarations(s,e,templateScopeOf(e),a),validateNoCycles(s,e,a),validateNoNesting(s,e,{checked:a,authored:a}),o.length>0)throw new ConfigError(r,o)}function unauthored(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const NO_FILE={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function validateRenderable(e,t,n=`<config>`,r=new Set(listResolvablePaletteNames()),i=[]){let a=presenceOf(e.config.segments,t),o=layerInserts({...e,path:n},i,a),s=(t,s)=>{let c=placeInserts(e.config,t,o.authored);return judgeRenderable(e,n,r,i,c.config,a,o.dropped,[...c.notices,...s])};try{return s(o.cells,[])}catch(e){if(!(e instanceof ConfigError)||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 ConfigError))throw r;let i=r.issues.filter(e=>!n.has(e.message)).map(e=>e.message).join(`; `);return{...e,refused:[...e.refused,insertNotice(t,`${t.relation} "${t.anchor}", but the bar refuses it there: ${i}`)]}}},{taken:[],refused:[]});return s(r,i)}}function judgeRenderable({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 ConfigError(n,[...l,...u.unplaced,...u.inherited],c)};validateCrossReferences(u,a,e,o),validateNoCycles(u,a),d();let f=droppedByFile(n,a.segments,u,o,i,s),p=synthesizePlacementMenus(withoutUnplaced(a),l);d();let m=synthesizeEditChrome(synthesizeSettingsMenu(p)),h=new Set([...declarationsAt({variables:e.variables??{},segments:e.segments??{}})].map(([e])=>e));return validateNoNesting(u,m,{checked:()=>!0,authored:e=>h.has(e)}),d(),{config:m,dropped:f,placed:a,warnings:c}}function layerInserts(e,t,n){let r=[...t].reverse().concat(e),i=absentPlacement(e.config,r.flatMap(e=>e.raw.insert??[]),n),a=e=>!i(e.anchor),o=e=>n(e.seg).kind===`declared`,s=e=>reportable(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=keyLocator(t.source);return(t.raw.insert??[]).filter(s).map(i=>({file:t.path,issue:{path:i.by.entry,message:unplacedMessage(i.by.entry,i.seg,e.config.segments,n(i.seg)),line:r(i.by.entry.split(`.`))}}))})}}function refuseDrops(e){if(e.length>0)throw new DroppedPlacements(e)}function droppedByFile(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=authoredPlacement(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:unplacedMessage(n.layoutKey,a,t,r(a)),line:findKeyLine(n.layer.source,n.path.split(`.`))})}return[...o].map(([e,t])=>new DroppedFileError(e,t))}function parseDslConfig(e,t,n=new Set(listResolvablePaletteNames()),r=NO_INHERITED_SEGMENTS){return parseDslFile(e,t,n,()=>({inherited:r,layer:null})).raw}function parseDslFile(e,t,n,r){let i=parseJson5OrThrow(e,t),a=editabilityNotice(e,t),o=[...a===null?[]:[a],...payloadDeclarationNotices(e,t,isPlainObject$2(i)&&isPlainObject$2(i.variables)?Object.keys(i.variables):[])],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(listResolvablePaletteNames()),groups:[],unplaced:[],inherited:[]};if(!isPlainObject$2(i))throw new ConfigError(e,[{path:``,message:`Config root must be an object, got ${describeType(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:validatePluginRefs({...c,issues:[]},i.plugins)??[],isPlainObject$2(i.segments)?Object.keys(i.segments):[]),d=validateTopLevel(c,i,l,actionHomeOf(e),e);if(s.length>0)throw new ConfigError(e,s,o);return{raw:d,warnings:o,layer:u}}const NO_INHERITED_SEGMENTS=new Set;function parseJson5OrThrow(e,t){try{return import_lib.default.parse(t)}catch(t){let n=t;throw new ConfigError(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function validateTopLevel(e,t,n,r,i){for(let n of Object.keys(t))TOP_LEVEL_KEYS.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...TOP_LEVEL_KEYS].join(`, `)}`,line:findKeyLine(e.source,[n])});let a={};return t.globals!==void 0&&(a.globals=validateGlobals(e,`globals`,t.globals)),t.variables!==void 0&&(a.variables=validateVariables(e,`variables`,t.variables)),t.segments!==void 0&&(a.segments=validateSegments(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.
|
|
221
224
|
Replace: layout: [["seg1", "seg2"], ["seg3"]]
|
|
222
225
|
With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
|
|
223
|
-
Single-row example: root: { h: ["seg1", "seg2"] }`,line:findKeyLine(e.source,[`layout`])}),t.root!==void 0&&(a.root=validateRootFragment(e,`root`,t.root)),t.insert!==void 0&&(a.insert=validateInsert(e,t.insert,i)),t.actions!==void 0&&(a.actions=validateActions(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:findKeyLine(e.source,[`looks`])}),t.styles!==void 0&&(a.styles=validateStyles(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=validateThemeDefaults(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=validatePresets(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=validateEditGlobals(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=validateHelpers(e,t.helpers)),t.plugins!==void 0&&(a.plugins=validatePluginRefs(e,t.plugins)),synthesizeGroupDecls(e,a),checkMenuDecls(e,a),synthesizeEditModeToggle(e,a),reservedNamespaceCollisions(e,a,SETTINGS_NS,`the global settings menu`),pluginScopeCollisions(e,a,n),a}const TOP_LEVEL_KEYS=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function validatePluginRefs(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 ${describeType(t)}`,line:findKeyLine(e.source,[`plugins`])})}const BUNDLED_THEME_DEFAULTS={},COMMAND_TRAY=commandTray(`commands.`),AUTOCOMPACT=autocompactControl(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),GIT_INIT=confirmStep(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),DIR_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 }}`,GIT_QUIET_FG=`{{ ${QUIET_TEXT} }}`,EFFORT_BUBBLE_CONTRAST=1.08,PERCENT={min:0,max:100,step:5},QUOTA_SETTINGS={warnAt:{label:`warning at %`,domain:PERCENT,default:50},errorAt:{label:`error at %`,domain:{...PERCENT,atLeast:`warnAt`},default:80}};function budgetSettings(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:PERCENT,default:80}}}const RAW_DEFAULT_DSL_CONFIG={globals:{palette:`tokyo-night`},variables:{...COMMAND_TRAY.variables,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:`⊫`},...GIT_INIT.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_TEMPLATE,fg:GIT_QUIET_FG},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 ${GIT_INIT.armed} }}{{ if ne .git.branch "" }} {{ end }}${GIT_INIT.template}{{ end }}`,fg:GIT_QUIET_FG,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:quickActions(``).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:COMMAND_TRAY.template,when:COMMAND_TRAY.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:budgetSettings(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:budgetSettings(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:QUOTA_SETTINGS,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:QUOTA_SETTINGS,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) ${TEXT_MIN_CONTRAST} }}`,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:AUTOCOMPACT.template,bg:AUTOCOMPACT.bg,when:AUTOCOMPACT.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:{...quickActions(``).actions,...COMMAND_TRAY.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...GIT_INIT.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...AUTOCOMPACT.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:BUNDLED_THEME_DEFAULTS,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) ${EFFORT_BUBBLE_CONTRAST} }}{{ if eq \$ord 5 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${TEXT_MIN_CONTRAST} }}{{ \$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 (${QUIET_TEXT}) 2 (readableOn (color "accent") (bgOf) ${TEXT_MIN_CONTRAST})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${TEXT_MIN_CONTRAST}) .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:formatTokenCount(`.`),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 .)) }}`}},AUTHORED_PALETTE_NAMES=new Set([RAW_DEFAULT_DSL_CONFIG.globals.palette,...Object.keys(RAW_DEFAULT_DSL_CONFIG.themeDefaults),...Object.values(RAW_DEFAULT_DSL_CONFIG.segments).map(e=>e.palette)].filter(e=>e!==void 0)),DEFAULT_DSL_CONFIG=mergeWithDefault(parseDslConfig(`<default>`,JSON.stringify(RAW_DEFAULT_DSL_CONFIG),AUTHORED_PALETTE_NAMES),RAW_DEFAULT_DSL_CONFIG),BUNDLED_PRESETS=presetNames(DEFAULT_DSL_CONFIG.presets);function isBundledPreset(e){return BUNDLED_PRESETS.includes(e)}function usageOver(e,t){return e.kind===`ok`?ok$1({cost:t.cost?.total_cost_usd??e.value.calculatedCost,tokens:e.value.tokens}):e}function resumeCommand(e,t,n){return claudeCommandLine({dir:e.project_dir,env:n===void 0?[]:[[CLAUDE_CONFIG_DIR_ENV,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function renderOptionsOf(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function effectiveInputs(e){return{...Object.fromEntries(VALUED_FIELDS.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:isBundledPreset(e.preset)}}}function prFactOf(e){if(isPending(e))return`pending`;let{prState:t,prError:n,prEarlier:r}=e??{};return isPending(t)?`pending`:t===void 0?n===void 0?r===void 0?`-`:`earlier-${String(r)}`:`failed`:t}const MIN_BURN_SECONDS=60,MIN_SPEED_SAMPLE_MS=50;function projectCostPerHour(e,t){if(!(t<MIN_BURN_SECONDS))return e*3600/t}function projectTokensPerSecond(e,t,n,r){let i=r-t;if(i<MIN_SPEED_SAMPLE_MS)return;let a=n-e;if(!(a<=0))return a*1e3/i}function turnIntervals(e){return e.slice(1).map((t,n)=>[e[n],t]).filter(([e,t])=>e.turnOpen&&t.atMs-e.atMs>=MIN_SPEED_SAMPLE_MS)}function openTurn(e){let t=e.length;for(;t>0&&e[t-1].turnOpen;)t--;return e.slice(t)}function projectSpeed(e){let t=turnIntervals(openTurn(e.samples));for(let e=t.length-1;e>=0;e--){let n=intervalRates(t[e]);if(n!==void 0)return n}}function intervalRates([e,t]){let n=projectTokensPerSecond(e.input,e.atMs,t.input,t.atMs),r=projectTokensPerSecond(e.output,e.atMs,t.output,t.atMs),i=projectTokensPerSecond(e.total,e.atMs,t.total,t.atMs);if(!(n===void 0&&r===void 0&&i===void 0))return{...n!==void 0&&{input:n},...r!==void 0&&{output:r},...i!==void 0&&{total:i}}}function projectSpeedHistory(e){let t=turnIntervals(e.samples).map(([e,t])=>projectTokensPerSecond(e.total,e.atMs,t.total,t.atMs)??0);if(t.length!==0)return t.join(`,`)}function renderWidth(e){return applyClaudeCodeReserve(e.termCols??120)}function awaitsReading({builtins:e,sources:t,runs:n},r){return[...AWAITED_BUILTINS.map(t=>e[t]),...Object.values(t),...[...r].map(e=>(n[e.digest]??UNREAD_RUN).reading)].some(awaitedReading)}const AWAITED={session:!0,today:!1,speed:!0,context:!0,metrics:!0,activity:!0,cache:!0,autocompact:!0,git:!0,pr:!1,tmux:!0,hostName:!0,hostUser:!0},AWAITED_BUILTINS=Object.keys(AWAITED).filter(e=>AWAITED[e]),awaitedReading=e=>e.kind===`pending`&&e.why===`unread`;async function settleWorld(e,t,n){try{await(0,import_dist$1.when)(()=>!awaitsReading(e(),t()),{signal:n})}catch(e){if(!n.aborted)throw e}}function firstPending(...e){let t=e.find(e=>e.kind===`pending`);return t?.kind===`pending`?pendingOf(t.why):void 0}const unstamped=e=>{switch(e.kind){case`pending`:return e;case`absent`:return ABSENT$2;case`ok`:return ok$1(e.value);case`failed`:return failed$2(e.reason,e.failedAt)}};function composePayload(e,t,n){let{hookData:r,hints:i}=t,a=r.session_id,{effective:o,configFacts:s}=n,{configPath:c,...l}=s,u=e.builtins,d={usage:usageOver(unstamped(u.session),r),context:contextOver(unstamped(u.context),r),metrics:metricsOver(unstamped(u.metrics),r),activity:unstamped(u.activity),cache:unstamped(u.cache),speed:unstamped(u.speed),autoCompact:unstamped(u.autocompact),git:unstamped(u.git),pr:unstamped(u.pr),tmux:unstamped(u.tmux),hostName:unstamped(u.hostName),hostUser:unstamped(u.hostUser)},f=(e,t)=>{switch(e.kind){case`pending`:return pendingOf(e.why);case`failed`:case`absent`:return;case`ok`:return t(e.value)}},p=e=>e.kind===`ok`?e.value:void 0,m=i.tmux??null,h=d.git.kind===`pending`?pendingOf(d.git.why):d.git.kind===`ok`?projectGitInfo(d.git.value,d.pr,pendingOf):void 0,g=d.tmux.kind===`pending`?pendingOf(d.tmux.why):p(d.tmux)?.session,_=d.hostName.kind===`pending`?pendingOf(d.hostName.why):p(d.hostName),v=d.hostUser.kind===`pending`?pendingOf(d.hostUser.why):p(d.hostUser),y=firstPending(d.context)??projectAutoCompact(d.autoCompact,p(d.context)?.maxTokens),b=r.rate_limits?.five_hour,x=r.rate_limits?.seven_day,S=firstPending(d.usage,d.metrics)??burnOf(p(d.usage)?.cost,p(d.metrics)?.sessionDuration),C=f(d.speed,speedPayloadOf),w=f(d.usage,e=>pickNonNull({cost:e.cost,tokens:e.tokens})),T=f(d.metrics,e=>pickNonNull({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),E=f(d.activity,projectActivity),D=f(d.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),O=f(d.cache,e=>({expiresAt:e})),k=posixify(t.home),A=r.workspace?{...r.workspace,current_dir:posixify(r.workspace.current_dir)??``,project_dir:posixify(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>posixify(e)??e)}:r.workspace;return{...r,...A!==void 0&&{workspace:A},...k!==void 0&&{home:k},...h!==void 0&&{git:h},...r.location!==void 0&&{location:{...r.location,main:posixify(r.location.main)??``}},...m!==null&&{tmux:{pane:m.pane,...g!==void 0&&{session:g}}},host:{..._!==void 0&&{name:_},...v!==void 0&&{user:v},...i.ssh!==void 0&&{ssh:i.ssh}},...effectiveInputs(o),history:n.history,navigation:{back:n.back},term:{cols:renderWidth(i)},...l,...c!==null&&{configPath:c},resumeCommand:resumeCommand(A,a,i.claudeConfigDir),...w!==void 0&&{session:w},...S!==void 0&&{burn:S},...C!==void 0&&{speed:C},...b!==void 0&&{block:{nativeUtilization:b.used_percentage,resetsAt:b.resets_at}},...x!==void 0&&{weekly:{percentage:x.used_percentage,resetsAt:x.resets_at}},...O!==void 0&&{cache:O},...D!==void 0&&{context:D},...T!==void 0&&{metrics:T},...E!==void 0&&{activity:E},...y!==void 0&&{autocompact:y},...projectSources(n.sources,t=>{let n=unstamped(sourceFactOf(e,t));return n.kind===`pending`?pendingOf(n.why):n})}}const sourceFactOf=(e,t)=>e.sources[t]??pendingOf(`unread`);function sourcesFactOf(e,t,n){let r=[...e.map(e=>[e,sourceFactOf(n,e)]),...[...t].map(([e,t])=>[e,t.kind===`ok`?(n.runs[t.value.digest]??UNREAD_RUN).reading:t])];return{sources:String(r.length),sourcesPending:r.flatMap(([e,t])=>t.kind===`pending`?[`${e}:${t.why}`]:[]).join(`,`)||`-`,sourcesFailed:r.flatMap(([e,t])=>t.kind===`failed`?[e]:[]).join(`,`)||`-`}}function projectSources(e,t){let n=Object.fromEntries(PLUGIN_SCOPES.map(e=>[e,{}]));for(let r of e){let e=r.split(`.`),i=e.pop(),a=e.reduce((e,t)=>e[t]??={},n);a[i]=t(r)}return n}function burnOf(e,t){let n=e!=null&&t!=null?projectCostPerHour(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function speedPayloadOf(e){let t=projectSpeed(e),n=projectSpeedHistory(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function instantFacts(e,t){return{today:todayOf(e.today,t)}}function todayOf(e,t){if(e.kind===`pending`)return pendingOf(e.why);if(e.kind!==`ok`)return;let n=projectToday(e.value,t);return n.kind===`ok`?{cost:n.value.cost,tokens:n.value.tokens}:void 0}function projectAutoCompact(e,t){switch(e.kind){case`pending`:return pendingOf(e.why);case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return autoCompactControls(e.value,t)}}function projectActivity(e){let t=e.todos.findIndex(e=>e.active),n=e.todos.length===0?void 0:{total:e.todos.length,completed:e.todos.filter(e=>e.done).length,...t>=0&&{position:t+1,active:e.todos[t].text}},r=encodeTally(e.running),i=encodeTally(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}};if(!(e.command===null&&n===void 0&&a===void 0))return{...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function encodeTally(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function pickNonNull(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function posixify(e){return e===void 0||e.length===0||path.sep!==`\\`?e:e.replace(/\\/g,`/`)}function projectGitInfo(e,t,n){let r=e=>e.kind===`ok`?e.value:void 0,i=r(e.aheadBehind),a=r(e.sha),o=r(e.operation),s=r(e.committedAt),c=r(e.stashCount),l=r(e.upstream),u=r(trackingOf(e.upstream,e.aheadBehind)),d=r(e.repoName),f=r(e.repoUrl),p=t.kind===`pending`?t:prOfHead(t,e.head),m={};switch(p.kind){case`pending`:{let e=n(p.why);m={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:m={prNumber:p.value.number,prState:p.value.state,prUrl:p.value.url};break;case`failed`:m={prError:p.reason};break;case`earlier`:m={prEarlier:p.value.state};break;case`absent`:break}return{branch:e.branch,status:e.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},staged:e.workingTree.staged,unstaged:e.workingTree.unstaged,untracked:e.workingTree.untracked,conflicts:e.workingTree.conflicts,...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{committedAt:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{tracking:u},...d!==void 0&&{repoName:d},...f!==void 0&&{repoUrl:f},...m}}const KEY=`click.error`,CLICK_ERROR_HOLD_S=5;function holdClickError(e,t,n,r){let i=joinedEvent(lastClickError(e,t),n,r);e.set(t,KEY,JSON.stringify(i))}function answeredClickError(e,t,n){let r=lastClickError(e,t);r===null||!answeredBy(r,n)||e.set(t,KEY,JSON.stringify({...r,answered:!0}))}function lastClickError(e,t){let n=e.get(t,KEY);return n===null?null:recordOf(n)}function clickErrorAt(e,t,n,r){let i=lastClickError(e,t);if(i===null)return{kind:`none`};let a=eventHoldAt(i,5,n,r);return a===`over`?{kind:a}:{kind:a,error:i}}function recordOf(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let{text:n,at:r,answered:i}=t;return typeof n==`string`&&typeof r==`number`&&(i===void 0||typeof i==`boolean`)?{text:n,at:r,answered:i===!0}:null}function handedOffTo(e,t){return LANE_NAMES.filter(n=>e[n]&&LANES[n].handsOff&&t.has(n))}const HANDOFF_BUTTON=`[⟲ claude]`;function laneHandoff(e,t){return{severity:HANDOFF_SEVERITY,lines:[[diagnosticSpan(HANDOFF_BUTTON,effectsUrl([{verb:VERB_RESET_CONFIG,args:[e,...t.map(e=>LANES[e].switch.setting)]}]))]]}}function renderFrame(e,t,n,r,i){let{clock:a}=e,o=a.monotonic(),s=[];try{try{var c=_usingCtx();let a=c.u(setUpFrame(e,t,r,s));if(a===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=drawRender(e,a,{by:`feed`,fps:n},i.feeds,i.idleSince),p=signingFrames(e.linkSigner),m=p(o.body),h=RENDER_ANSWERS.ansi(m),g=statuslineOf(t,o,handedOffTo(f,i.following));return d(),{bar:m,resp:h,statusline:g===o.body?h:RENDER_ANSWERS.ansi(p(g)),evaluated:l,cellBreaks:u,lanes:f,failure:null}}catch(e){c.e=e}finally{c.d()}}catch(n){let r=renderFailure(failureOf(n)),{level:i,line:c}=requestEvent(`render`,s,r,elapsedMs(a,o)),l=failedWith(r.message);return{bar:renderFailedFrame(l.error),resp:l,statusline:l,evaluated:0,cellBreaks:0,lanes:viewLanes(e,t),failure:{level:i,line:`frame ${c}`}}}}function sessionGlobals$1(e,t,n){let{sessionState:r}=e;return resolveEffectiveGlobals(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function viewLanes(e,t){try{var n=_usingCtx();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:laneSwitches(i.view.source.effective(),inTmux(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function lanesAt(e,t,n,r){try{var i=_usingCtx();let{renderCache:a}=e;return laneSwitches(sessionGlobals$1(e,n,i.u(a.hold(t.projectDir,t.cwd,t.target.path)).state),r===null||inTmux(r.hints.tmux))}catch(e){i.e=e}finally{i.d()}}function contextFacts(e,t,n){noteFacts(n,{sid:e.hookData.session_id,at:t.toFixed(3)});let{hints:r}=e;noteFacts(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:refusedHints(e,r).map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits})}const hintsErrorOf=e=>refusedHintsError(refusedHints(e,e.hints));function configureSession(e,t,n,r,i){contextFacts(t,r,i),noteFacts(i,{encoding:t.encoding}),(0,import_dist$1.runInAction)(()=>{recordRequest(e,t),e.worldStates.take(n),holdSessionAt(e,t)[Symbol.dispose]()})}function retireSession(e,t){(0,import_dist$1.runInAction)(()=>{e.worldStates.drop(t),e.renderCache.retireSession(t)})}function holdSessionAt(e,t){let{projectDir:n,cwd:r,target:i}=t.requested;return e.renderCache.holdSession(n,r,i.path,t)}function setUpRender(e,t,n,r){let i=hintsErrorOf(t);return setUpDraw(e,holdSessionAt(e,t),t,i,n,r)}function setUpFrame(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{contextFacts(o,n,r),s=hintsErrorOf(o)}catch(e){throw a[Symbol.dispose](),e}return setUpDraw(e,a,o,s,n,r)}function setUpDraw(e,t,n,r,i,a){try{let{entry:e,state:o,view:s}=t;return{req:n,at:i,facts:a,sessionId:n.hookData.session_id,entry:e,state:o,view:s,hintsError:r,[Symbol.dispose]:()=>t[Symbol.dispose]()}}catch(e){throw t[Symbol.dispose](),e}}function drawRender(e,t,n,r,i){let{sessionState:a,renderCache:o,linkSigner:s,renderWarnings:c,effectSessions:l,menuIdle:u}=e,{req:d,at:f,facts:p,sessionId:m,entry:h,state:g,view:_,hintsError:v}=t,y=_.source.payload(),b=_.source.effective(),x=_.source.failure(),S=_.source.facts(),C=laneSwitches(b,y.tmux!==void 0);noteFacts(p,{lanes:LANE_NAMES.filter(e=>C[e]).join(`,`)||`-`});let w=_.source.hints(),T=y.term.cols;noteFacts(p,{width:String(T)});let E=clickErrorAt(a,m,f,n.by),D=E.kind===`held`||E.kind===`owed`?E.error:null,{update:O}=S.daemon,k=updateNotice(O.newer.kind===`ok`?O.newer.value:null,O.act,{sessionId:m,dismissed:a.get(m,UPDATE_DISMISSED_KEY),enabled:b.updateNotice}),A=repoQuestions(h.repos,m,s),j=(e,t)=>({about:e,text:t,copy:t}),M=e=>j(e??``,e),N=[M(refusedArgsError(d.refusedArgs)),M(v),j(`load`,h.lastError),j(`update-act`,O.actsError),...g.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),M(D?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),F=h.watch===null?null:watchFault(`config watch`,h.watch,null),{daemon:ee}=S,te=launcherWarningsAt(ee.launcher,f,n.by),ne=te.find(e=>e.kind===`launch-pipes`),I=[daemonEventAt(`renderer-ended`,ee.rendererEnded,f,n.by),daemonEventAt(`act-failed`,ee.actFailed,f,n.by)].flatMap(e=>e===void 0?[]:[e]),re=[ne?.event,...I.map(e=>e.event)].flatMap(e=>e===void 0?[]:[e]),ie=[...ee.fileEvents,...te,...I,...F===null?[]:[{kind:`config-watch`,message:F}],...h.lastWarning===null?[]:[{kind:`load`,message:h.lastWarning}],...x===null?[]:[{kind:`facts`,message:`the bar is drawn from the last facts that were read; the next could not be stamped: ${x}`}]],ae={config:g.config},oe=collectDiagnostics(m,n.by,N,[...k.offer,...A],[...k.failure,...ie.map(e=>({about:e.kind,text:e.message,copy:e.message})),...c.ofSession(m,n.by,ae).map(e=>({about:`${e.kind}\0${e.message}`,text:e.message,copy:e.message}))]),L={diagnostics:diagnosticsProjection(oe),drawing:n,feeds:r,...instantFacts(S.builtins,f)},R=isPending(y.metrics)?void 0:y.metrics;noteFacts(p,sourcesFactOf([..._.state.sources.keys()],_.registry.runSources(),S)),noteFacts(p,{prompts:String(R?.messageCount??`-`),nonPrompts:String(R?.nonPrompts??`-`),pr:prFactOf(y.git),feeds:feedsFact(L.feeds)});let se=[],ce=renderOptionsOf(b,T),le=l.of(m),{frame:ue,evaluated:z,cellBreaks:de,rules:fe}=drawDsl(g.config,g.compiled,_.store,_.registry,L,f,ce,{perSegmentSink:_.lastRenderCellsBySegment,onRenderWarning:e=>se.push(e)},{...b,effects:le,idleSince:i??void 0}),B=copyKeys(oe),V=new Map(oe.map((e,t)=>[B[t],e.copy])),H=()=>o.delivered(m,n.by,V);u.observe(m,f,ue.rows.some(e=>e.kind===`menu`),b.menuTimeout),noteFacts(p,{menuIdle:i===null?`-`:`${(f-i).toFixed(1)}s/${b.menuTimeout}s`});let pe=c.drawn(m,n.by,ae,se),me={width:T,rows:viewerRowCap(w.termRows,n.by===`feed`?LANE_NAMES.flatMap(e=>{let t=LANES[e].rows;return C[e]&&t!==null?[t]:[]}):[]),colorCompatibility:ue.depth},U=viewedIndex(a.get(m,DIAGNOSTICS_VIEWING),oe),he=U===null?ue:standIn$1(ue,viewerRows(oe,U,m,n.by,me)),W=le.lastFrame(),ge=W.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,G=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,K=e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`file-events`:return`${e.kind}:${e.state}`;case`load`:case`facts`:case`config-watch`:case`lifeline`:case`launch-pipes`:case`renderer-ended`:case`act-failed`:case`when`:return e.kind}},q=[...k.failure.map(()=>`update-failed`),...[...ie,...se].map(K)].join(`,`)||`-`;return noteFacts(p,{effect:W.effect,effectT:W.t.toFixed(3),speed:`${W.speed}x`,effectRows:`${W.made}made/${W.reused}reused`,effectOwn:ge,fadeBasis:W.basis,stateRev:String(W.revision),fades:G(W.fades),leaves:G(W.leaves),motion:he.motion,evaluated:String(z),cellBreaks:String(de),pending:he.pending.join(`,`)||`-`,rules:[...fe].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:N.length>0?`Y`:`N`,clickError:E.kind===`none`?`-`:E.kind,pipeEvent:ne?.hold??`-`,upd:String(k.offer.length),ask:String(A.length),warn:q,diag:String(oe.length),warnRecord:pe?`new`:`kept`,viewer:U===null?`-`:`${U.index}/${oe.length}p${U.page+1}`}),{drawn:{body:he,viewerOpen:U!==null,diagnostics:oe,geometry:me},evaluated:z,cellBreaks:de,clickShown:D,eventsShown:re,delivered:H,lanes:C}}function daemonEventAt(e,t,n,r){return t===null||eventHoldAt(t,60,n,r)===`over`?void 0:{kind:e,message:t.text,event:t}}function recordRequest(e,t){let{sessionState:n}=e,r=t.hookData.session_id,{client:i,...a}=t.hints,o=JSON.stringify(a);n.get(r,`client-hints`)!==o&&n.set(r,SESSION_CLIENT_HINTS_KEY,o);let s=encodeRenderOrigin(t.requested);n.get(r,`render-origin`)!==s&&n.set(r,SESSION_RENDER_ORIGIN_KEY,s)}async function answerRequest(e,t,n,r,i,a,o){try{var s=_usingCtx();let{clock:c,log:l}=e,u=c.monotonic(),d=s.u(setUpRender(e,t,n,a));e.laneActs.noted(t,laneSwitches(d.view.source.effective(),inTmux(t.hints.tmux)),o);let f=c.monotonic(),p=r-(f-u);noteFacts(a,{deadline:`${t.deadline.kind}:${Math.round(p)}ms`});let m=await waitWithin(t=>settleWorld(()=>e.worldStates.of(d.sessionId),()=>d.view.registry.namedRuns().values(),t),p,(e,t)=>l(`error`,`render wait failed after it ended ended=${t} sid=${JSON.stringify(d.sessionId)}: ${inspect(e)}`),c.after,e.renderCache.closing),h=c.monotonic();noteFacts(a,{waited:`${Math.round(h-f)}ms`,ended:m});let g=t.hookData.session_id,{drawn:_,clickShown:v,eventsShown:y,delivered:b,lanes:x}=drawRender(e,d,ANSWERING,i.feeds,i.idleSince),S=handedOffTo(x,i.following),C=roleOf(t.hints.client??null)===`statusline`,w=signingFrames(e.linkSigner)(C?statuslineOf(g,_,S):_.body);return noteFacts(a,{handoff:(C?S:[]).join(`,`)||`-`,drew:`${elapsedMs(c,h)}ms`}),{frame:w,delivered:answerDelivered(e,g,b,v,y)}}catch(e){s.e=e}finally{s.d()}}function answerDelivered(e,t,n,r,i){return()=>{n(),r!==null&&answeredClickError(e.sessionState,t,r);for(let t of i)e.eventAnswered(t)}}function statuslineOf(e,t,n){let[r,...i]=n;return r===void 0||t.viewerOpen?t.body:standIn$1(t.body,handoffRows(laneHandoff(e,[r,...i]),t.diagnostics,e,t.geometry))}async function clickTurn({verbs:e,menuIdle:t},{verb:n,value:r,session:i,arrival:a,id:o,latest:s},c,l){let u=e.handler(n);if(u===void 0)throw new BadVerbArgs(`unknown click verb: ${n}`);let d=i?.ok?i.id:null;d!==null&&t.clickArrived(d);try{await u(r,{arrival:a,placeWaited:e=>noteFacts(c,{placeWait:`${e}ms`}),gatherTook:e=>noteFacts(c,{gather:`${e}ms`}),turnWaited:e=>noteFacts(c,{turnWait:`${e}ms`}),click:o,latest:s,effects:l})}finally{d!==null&&t.clickSettled(d)}}function spelled(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?BOOLEAN_TRUE:BOOLEAN_FALSE;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const SETTING_ROWS=Object.entries(SETTINGS),SETTING_KEYS=new Set(SETTING_PROJECTIONS.map(e=>e.sessionKey)),NOT_CUSTOMIZED=()=>!1;function sessionGlobals(e,t){return resolveEffectiveGlobals(e,e=>SETTING_KEYS.has(e)?t(e):null,NOT_CUSTOMIZED)}const SELECTORS=[`preset`,`theme`];function fileThrough(e,t,n){let r=new Set(SELECTORS.slice(0,n).map(e=>SETTINGS[e].sessionKey));return resolveEffectiveGlobals(e,e=>r.has(e)?t(e):null,NOT_CUSTOMIZED)}function baseOf(e,t){let n=Array.from({length:SELECTORS.length+1},(n,r)=>fileThrough(e,t,r));return e=>{let t=SELECTORS.indexOf(e);return n[t===-1?SELECTORS.length:t]}}function differing(e,t,n,r){return e.flatMap(([e,i])=>{let a=spelled(t,e);return a===null||a===spelled(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function sessionSettingValue(e,t,n){return spelled(sessionGlobals(e,t),n)}function settingDrafts(e,t){let n=sessionGlobals(e,t);return differing(SETTING_ROWS,n,baseOf(e,t),t=>landingKey(e,n.preset,t.configKey))}function landingKey(e,t,n){return n in(presetByName(e.presets,t).globals??{})?presetGlobalsKey(t,n):n}function durableLanding(e,t,n){let r=effectivePresetName(t(SETTINGS.preset.sessionKey),e.globals.preset,e.presets),i=parsePersistTarget(n);return{key:i?.scope===`globals`?landingKey(e,r,i.field):n,globals:presetGlobals(e,r)}}function placementDrafts(e,t){let{preset:n}=sessionGlobals(e,t);return slotsOf(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:parseSettingSpelling(a,s);return c===void 0||settingSpelling(c)===settingSpelling(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function placementPickProblems(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return presetNames(e.presets).flatMap(n=>{let i=slotsOf(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 settingOrderProblems(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:parseSettingSpelling(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const SLOTS=new WeakMap;function slotsOf(e,t){let n=SLOTS.get(e)??new Map;SLOTS.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...walkNodes(presetRoot(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=settingsOf(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 presetSnapshot(e,t){let n=sessionGlobals(e,t);return{from:n.preset,globals:presetByName(e.presets,n.preset).globals??{},picks:differing(SETTING_ROWS.filter(([e])=>e!==`preset`),n,baseOf(e,t),e=>e.configKey),placements:placementDrafts(e,t)}}function themeOwnLook(e,t){return resolveEffectiveGlobals({...e,globals:{palette:t},presets:{}},()=>null,NOT_CUSTOMIZED)}function themeDefaultSave(e,t){let n=sessionGlobals(e,t),r=spelled(n,`theme`);if(r===null)return{kind:`rule`};let i=themeOwnLook(e,r),a=presetGlobals(e,n.preset),o=Object.fromEntries(THEME_DEFAULT_FIELDS.map(e=>[e,spelled(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:THEME_DEFAULT_FIELDS.some(e=>o[e]!==spelled(i,e))}}function resetLayers(e){return{sessionKeys:SETTING_PROJECTIONS.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...isPresetGlobalsField(e)?BUNDLED_PRESETS.map(t=>presetGlobalsKey(t,e)):[],...isThemeDefaultField(e)?listResolvablePaletteNames().map(t=>themeDefaultKey(t,e)):[]]}}function fileHeldSettings(e){return new Set(SETTING_PROJECTIONS.map(e=>e.configKey).filter(t=>resetLayers(t).fileKeys.some(t=>holds(e,filePath(t)))))}function settingCounts(e,t,n){let r=settingDrafts(e,n),i=new Set(r.map(e=>e.configKey)),a=perSetting(e=>i.has(SETTINGS[e].configKey)||t.has(SETTINGS[e].configKey)),o=themeDefaultSave(e,n);return{unsaved:r.length+placementDrafts(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function filePath(e){let t=parsePersistTarget(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return persistPath(t)}function holds(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&holds(e[n],r)}function stateKeySeed(e,t,n){let r=SESSION_KEY_TO_SETTING.get(n);if(r!==void 0)return sessionSettingValue(e,t,r);for(let[,t]of stateVarDecls(e))if(t.key===n)return t.default??null;return null}function configKeySeed(e,t){let n=numericGlobalsSeeds(e).get(t);return n===void 0?null:String(n)}const NO_NEST={inside:()=>[],defaultOf:()=>DISCLOSURE_CLOSED,menus:[]},idOf=e=>`${e.key}\0${e.member}`;function buildDisclosureNest(e){let t=new Map,n=n=>{let r=`${n.name}\0${placementId(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:hostedMenus(a,placementId(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(idOf(e))??new Map;n.set(idOf(t),t),o.set(idOf(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(idOf(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 presetNames(e.presets))d(presetRoot(e,t).node,[]);for(let t of Object.values(e.actions)){let e=disclosureOfAction(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(idOf(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(idOf(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(idOf(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const NESTS=new WeakMap;function disclosureNest(e){let t=NESTS.get(e);if(t!==void 0)return t;let n=buildDisclosureNest(e);return NESTS.set(e,n),n}function closeNested(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 openRoots(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 closingView(e,t,n){let r=(r,i,a)=>{let o=closeNested(t(r),t=>e.get(r,t),i);(0,import_dist$1.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 BOOLEAN_TRUTHY=new Set([`1`,`true`]),BOOLEAN_FALSY=new Set([`0`,`false`,``]);function persistValueText(e,t){let n=requireValueTarget(e),r=n.scope===`segment-palette`?`string`:wireKindOf(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(BOOLEAN_TRUTHY.has(t))return`true`;if(BOOLEAN_FALSY.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function docOf(e){return/^\s*$/.test(e)?null:parseDocument(e)}function has(e,t){return e!==null&&nodeAt(e,t)!==void 0}function authoredLayout(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(authoredLayout),...i}}return e}function authoredFragment(e){if(!isRowsFragment(e))return authoredLayout(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,authoredLayout(t)])),...n}}const RAW=RAW_DEFAULT_DSL_CONFIG,RAW_SEGMENTS=RAW.segments,RAW_PRESETS=RAW.presets,RAW_ROOT=RAW.root;function requireDeclared(e,t,n,r){if(!has(e,t)&&n===void 0)throw new BadVerbArgs(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function valuePathOf(e,t){let n=persistPath(t);return t.scope===`segment-palette`&&requireDeclared(e,[`segments`,t.segment],RAW_SEGMENTS[t.segment],n.join(`.`)),n}function bundledDoc(e){return parseDocument(json5Text(e))}function bundledRowLayers(){return Object.entries(RAW_ROOT.rows).map(([e,t])=>{let n=authoredLayout(t);return{path:[`root`],fragment:bundledDoc({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function fileLayer(e,t){let n=e===null?void 0:nodeAt(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function bundledRootLayer(e,t){if(t===void 0)return null;let n=authoredFragment(t);return{path:e,fragment:bundledDoc(n),unit:{path:e,value:n}}}function presetLayer(e,t){let n=[`presets`,t],r=[...n,`root`],i=RAW_PRESETS[t];requireDeclared(e,n,i,r.join(`.`));let a=fileLayer(e,r)??bundledRootLayer(r,i?.root);return a!==null&&restagesFragment(a.fragment)?a:null}const TREE_BLOCK=`#`;function applyLayer(e,t){let n=rowEntriesOf(t.fragment);return n===null?new Map([[TREE_BLOCK,{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 cascadeOf(e,t){return[...bundledRowLayers(),fileLayer(e,[`root`]),presetLayer(e,t)].filter(e=>e!==null).reduce(applyLayer,new Map)}function layoutPlacementOf(e,t,n){for(let{node:r,...i}of cascadeOf(e,t).values())if(hasSegmentRef(r,n))return i;throw new BadVerbArgs(`${stagedPathOf(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 stagedPathOf(e,t){return presetLayer(e,t)?.path??[`root`]}function resetPathOf(e,t){return t.scope===`preset-root`?stagedPathOf(e,t.preset):persistPath(t)}function ensureAuthored(e,{unit:t}){return t===null?e:setValue(e,t.path,json5Text(t.value),JSON5_DIALECT)}function requireTarget(e){let t=parsePersistTarget(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function requireValueTarget(e){let t=requireTarget(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function commit(e,t,n,r,i){let a=loadOrRefuse(t,r),o,s=()=>(o??={chain:loadedOrNull(t,n)}).chain;return refuseNewDrops(t,s,a),i(t,s,a),e.record(t.path,n,r),a.config}function refuseHidden(e,t,n){let r=hiddenBy(e,t(),n);if(r.length>0)throw new BadVerbArgs(`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 releases=()=>{};function homeOnly(e,t){try{return t()}catch(t){throw!(t instanceof BadVerbArgs)||e.above.length===0?t:new BadVerbArgs(`${t.message} — or it is declared by ${e.above.map(e=>e.path).join(`, `)}, which the bar does not edit`)}}function hiddenBy(e,t,n){if(t===null)return[];let r=new Set(changedPaths(topConfig(t),topConfig(n)));return changedPaths(homeConfig(e,t),homeConfig(e,n)).filter(e=>!r.has(e))}function loadedOrNull(e,t){try{return chainOver(e,t)}catch(e){if(e instanceof ConfigError)return null;throw e}}function chainOver(e,t){return loadConfigChain(e.locs,t===null?e.above:[homeLayer(e.path),...e.above],DEFAULT_DSL_CONFIG,{warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:fs.readFileSync(n,`utf8`))}function homeConfig(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function topConfig(e){return e.layers.at(-1)?.config??e.base}function changedPaths(e,t,n=``){return!isPlainObject(e)||!isPlainObject(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>changedPaths(e[r],t[r],n===``?r:`${n}.${r}`))}function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function proveLoads(e,t){loadOrRefuse(e,t)}function loadOrRefuse(e,t){try{return chainOver(e,t)}catch(e){throw e instanceof ConfigError?new BadVerbArgs(`refused: the config file would not load after this click — ${e.message}`):e}}function refuseNewDrops(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 BadVerbArgs(`refused: this click would leave a placement of a segment nothing declares — ${o.map(({file:e,issue:t})=>new ConfigError(e,[t]).message).join(`
|
|
224
|
-
`)}`)}function readValue(e,t){let n=requireValueTarget(t),r=docOf(e??``),i=r===null?void 0:nodeAt(r,persistPath(n));return i!==void 0&&`value`in i?i.value:void 0}function writeValues(e,t,n){writeDrafts(e,t,n,[])}function writeDrafts(e,t,n,r){let i=e.read(t.path),a=n.reduce((e,[t,n])=>setValue(e,valuePathOf(docOf(e),requireValueTarget(t)),persistValueText(t,n),JSON5_DIALECT),i??``);commit(e,t,i,homeOnly(t,()=>withPlacements(a,t.path,r,e=>e)),refuseHidden)}function withPlacements(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=layoutPlacementOf(docOf(s),n,i),l=setPlacementSetting(ensureAuthored(s,c),c.path,i,a,json5Text(o));if(l===null)throw new BadVerbArgs(`${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 ownRow(e,t,n){let r=docOf(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of cascadeOf(r,t)){if(!hasSegmentRef(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?movableTextOf(e,c):json5Text(s.value);if(a!==TREE_BLOCK)return setValue(e,[...i,`rows`,a],l,JSON5_DIALECT);if(presetLayer(r,t)!==null)throw new BadVerbArgs(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return setValue(e,i,l,JSON5_DIALECT)}return e}function deleteAtPath(e,t){return deleteValue(e,t,t[0]===`presets`&&t.length>2&&!isBundledPreset(t[1])?2:0)}function deleteValues(e,t,n){let r=n.map(requireTarget),i=e.read(t.path);if(i===null)return;let a=r.reduce((e,t)=>deleteAtPath(e,resetPathOf(docOf(e),t)),i);a!==i&&commit(e,t,i,a,releases)}const SAVED_PRESET_PREFIX=`custom-`;function presetKeys(e){let t=e===null?void 0:nodeAt(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function freePresetName(e,t){let n=new Set([...BUNDLED_PRESETS,...presetKeys(e),...t.above.flatMap(e=>Object.keys(import_lib.default.parse(fs.readFileSync(e.path,`utf8`)).presets??{}))].map(ident));return Array.from({length:n.size+1},(e,t)=>`${SAVED_PRESET_PREFIX}${t+1}`).find(e=>!n.has(ident(e)))}function writePreset(e,t,n,r,i,a){let o=e.read(t.path),s=docOf(o??``),c=freePresetName(s,t),l=[`presets`,c],u=homeOnly(t,()=>presetLayer(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?movableTextOf(o??``,u.fragment):json5Text(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],json5Text(r)]]],f=i.map(([e,t])=>{let n=presetGlobalsKey(c,e);return[valuePathOf(s,requireValueTarget(n)),persistValueText(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>setValue(e,t,n,JSON5_DIALECT),setValue(o??``,l,`{}`,JSON5_DIALECT));return commit(e,t,o,homeOnly(t,()=>withPlacements(p,t.path,a.map(e=>({...e,preset:c})),ownRow)),refuseHidden),c}function writeThemeDefault(e,t,n,r){let i=e.read(t.path);return commit(e,t,i,setValue(i??``,[`themeDefaults`,n],json5Text(r),JSON5_DIALECT),refuseHidden)}function deletePreset$1(e,t,n){if(isBundledPreset(n))throw new BadVerbArgs(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=e.read(t.path),a=docOf(i??``);if(i===null||a===null||nodeAt(a,r)===void 0)throw new BadVerbArgs(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=nodeAt(a,[`globals`,`preset`]);commit(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>deleteAtPath(e,t),i),releases)}function applyLayoutOp$1(e,t,n,r){let i=requireTarget(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=e.read(t.path),o=r.op===`remove`?r.target:r.anchor,s=homeOnly(t,()=>layoutPlacementOf(docOf(a??``),i.preset,o)),c=ensureAuthored(a??``,s),{after:l,placed:u}=spliceOp(c,s.path,r,()=>{let e=loadOrRefuse(t,c).config;return presetNames(e.presets).map(t=>presetRoot(e,t).node)});if(l===null)throw new BadVerbArgs(`${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{placed:u,config:commit(e,t,a,l,refuseHidden)}}function spliceOp(e,t,n,r){switch(n.op){case`remove`:return{after:removeSegmentRef(e,t,n.target),placed:null};case`insert`:{let i=mintPlacement(n.segment,n.anchor,r());return{after:insertSegmentRef(e,t,i,n.anchor,n.relation),placed:i}}}}function recordingView(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 EPHEMERAL_SESSION_STORAGE={load:()=>new Map,save:()=>{},flush:()=>{}},DEFAULT_MAX_SESSIONS=256;var SessionState=class{sessions;storage;head=0;atom=(0,import_dist$1.createAtom)(`SessionState`);constructor(e=EPHEMERAL_SESSION_STORAGE,t=DEFAULT_MAX_SESSIONS){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Array.from(this.storage.load(),([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,import_dist$1.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,import_dist$1.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,import_dist$1.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=EPHEMERAL_SESSION_STORAGE}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 SETTING_SESSION_KEYS=new Set(SETTING_PROJECTIONS.map(e=>e.sessionKey)),isSettingKey=e=>SETTING_SESSION_KEYS.has(e)||e.startsWith(PLACEMENT_DRAFT_NS),EPHEMERAL_HISTORY_STORAGE={load:()=>new Map,save:()=>{}},MAX_STEPS$1=50,MAX_SESSIONS$2=32,MAX_BYTES=8*1024*1024,EMPTY={past:[],future:[]},identity=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var SettingsHistory=class{held=import_dist$1.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,import_dist$1.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=EPHEMERAL_HISTORY_STORAGE,r=n.load()){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(r)}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??EMPTY;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??EMPTY}begin(e){let t=heldWrites(this.sessionState),n=new Map,r={held:t,files:e,historyOf:e=>n.get(e)??this.history(e),move:(e,t)=>n.set(e,t)},i=new Map,a=!1,o=(e,t)=>{a=!0;let n=i.get(e)??new Map,r=n.get(identity(t));n.set(identity(t),r===void 0?t:{...t,before:r.before}),i.set(e,n)},s=new Map,c=recordingView(t,()=>!0,(e,t,n,r)=>{if(a=!0,!(!isSettingKey(t)&&t!==`edit.mode`)){if(t===`edit.mode`){let t=s.get(e);s.set(e,{before:t===void 0?n:t.before,after:r});return}o(e,{kind:`session`,key:t,before:n,after:r})}}),l=()=>{let e=new Map(i),t=new Map(s);i.clear(),s.clear();for(let n of new Set([...e.keys(),...t.keys()])){let i=[...e.get(n)?.values()??[]].filter(e=>e.before!==e.after),a=r.historyOf(n),o=i.length===0?a:afterAppend(a,i),s=t.get(n),c=s===void 0?o:withToggle(o,s);c!==a&&r.move(n,c)}};return{sessionState:c,file:(t,n,r,i)=>{o(t,{kind:`file`,file:n,before:r,after:i}),e.land(n,r,i)},wrote:()=>{a=!0},written:()=>a,undo:e=>(l(),this.undo(r,e)),redo:e=>(l(),this.redo(r,e)),rewind:e=>(l(),this.rewind(r,e)),commit:()=>{l();let e=new Map(n);n.clear();for(let[t,n]of e)this.put(t,n);t.flush()}}}undo(e,t){let n=e.historyOf(t),r=n.past.at(-1);if(r===void 0)throw new BadVerbArgs(`undo: nothing to undo`);return this.apply(e,t,r,`before`,`undo`,afterUndo(n,r)),r}rewind(e,t){let n=e.historyOf(t),{savepoint:r}=n;if(r===void 0)throw new BadVerbArgs(`rewind: edit mode has no savepoint — nothing to cancel`);let i=r.net.flatMap(n=>{let r=stepOf(e,t,n,`before`);return r.kind===`moved`?[r]:[]}),a=new Set(i.map(e=>e.target)),o=r.net.filter(e=>!a.has(identity(e))),s=capped(without(pastAt(n,r),a));if(this.apply(e,t,o,`before`,`rewind`,{past:s,future:[],savepoint:{at:s.length,net:[],below:[]}}),i.length>0)throw new BadVerbArgs(`rewind: ${i.map(e=>e.what).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return o}redo(e,t){let n=e.historyOf(t),{past:r,future:i}=n,a=i.at(-1);if(a===void 0)throw new BadVerbArgs(`redo: nothing to redo`);let o=[...r,a],s=capped(o);return this.apply(e,t,a,`after`,`redo`,{past:s,future:i.slice(0,-1),...savepointAfter(n.savepoint,o.length-s.length,a)}),a}apply(e,t,n,r,i,a){let o=n.map(n=>stepOf(e,t,n,r)),s=o.flatMap(e=>e.kind===`moved`?[e]:[]);if(s.length>0)throw e.move(t,forgotten(e.historyOf(t),new Set(s.map(e=>e.target)))),new BadVerbArgs(`${i}: ${s.map(e=>e.what).join(`, `)} changed since that edit — refusing to overwrite it; this session's undo history no longer steps it`);let c=o.flatMap(e=>e.kind===`file`?[e]:[]);for(let{file:t,text:n}of c)e.files.prove(t,n);for(let{file:t,text:n}of c)e.files.land(t,e.files.read(t),n);for(let n of o)n.kind===`session`&&(n.value===null?e.held.clear(t,n.key):e.held.set(t,n.key,n.value));e.move(t,a)}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>MAX_SESSIONS$2||weight(n)>MAX_BYTES;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,withoutOldestStep(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${MAX_BYTES} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function weight(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 withoutOldestStep({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...savepointAfter(n,1,[])}:{past:e,future:t.slice(1),...savepointAfter(n,0,[])}}function capped(e){return e.slice(-MAX_STEPS$1)}const isOpen=e=>e===EDIT_MODE_REF.member;function savepointAfter(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:withNet(e.net,n),below:e.below}}}function withNet(e,t){let n=new Map(e.map(e=>[identity(e),e]));for(let e of t){let t=n.get(identity(e));n.set(identity(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const reversed=e=>e.map(e=>({...e,before:e.after,after:e.before}));function afterAppend(e,t){let n=[...e.past,t],r=capped(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...savepointAfter(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...redone(e.future,a),...i.below]},n.length-r.length,t)}}function redone(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function afterUndo(e,t){return{past:e.past.slice(0,-1),future:capped([...e.future,t]),...savepointAfter(e.savepoint,0,reversed(t))}}function pastAt(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...redone(r,t.at-i.length),...t.below]}function withToggle(e,t){if(isOpen(t.after)&&!isOpen(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!isOpen(t.after)&&isOpen(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function without(e,t){return e.map(e=>e.filter(e=>!t.has(identity(e)))).filter(e=>e.length>0)}function describeStep(e){return e.map(describe).join(`, `)}function describe(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function stepOf(e,t,n,r){let i=r===`before`?`after`:`before`;if(n.kind===`session`)return e.held.get(t,n.key)===n[i]?{kind:`session`,key:n.key,value:n[r]}:{kind:`moved`,target:identity(n),what:`session setting "${n.key}"`};let a=applyChanges(e.files.read(n.file),diffChanges(n[i],n[r]));return a.kind===`applied`?{kind:`file`,file:n.file,text:a.text}:{kind:`moved`,target:identity(n),what:`${addressText(a.at)} in ${n.file}`}}function forgotten({past:e,future:t,savepoint:n},r){return{past:without(e,r),future:without(t,r),...n!==void 0&&{savepoint:{at:without([...e,...[...t].reverse()].slice(0,n.at),r).length,net:n.net.filter(e=>!r.has(identity(e))),below:without(n.below,r)}}}}function heldWrites(e){let t=new Map,n=(e,n,r)=>{let i=t.get(e)??new Map;i.set(n,r),t.set(e,i)};return{get:(n,r)=>{let i=t.get(n);return i?.has(r)?i.get(r):e.get(n,r)},revision:t=>e.revision(t),set:(e,t,r)=>n(e,t,r),setBatch:(e,t)=>{for(let{key:r,value:i}of t)n(e,r,i)},clear:(e,t)=>n(e,t,null),flush:()=>(0,import_dist$1.runInAction)(()=>{for(let[n,r]of t){let t=[...r].flatMap(([e,t])=>t===null?[]:[{key:e,value:t}]);t.length>0&&e.setBatch(n,t);for(let[t,i]of r)i===null&&e.clear(n,t)}t.clear()})}}const SESSION_FACT_VARIABLES=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function sessionEnv(e){return{...Object.fromEntries(SESSION_FACT_VARIABLES.map(e=>[e,null])),CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir,...e.claudeConfigDir!==void 0&&{CLAUDE_CONFIG_DIR:e.claudeConfigDir}}}const isRecord=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function parseMarkBook(e){let t=e=>({kind:`failed`,reason:e});if(!isRecord(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!isRecord(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!GLYPH_MARKS.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${GLYPH_MARKS.join(` or `)}`)}return{kind:`ok`,value:e}}function withMark(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const fileMarkBook=e=>stateFile(e,`doctor-marks.json`,{},parseMarkBook),parseClickedTerminals=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},withClicked=(e,t)=>e.includes(t)?e:[...e,t],fileClickedTerminals=e=>stateFile(e,`doctor-clicked-terminals.json`,[],parseClickedTerminals),inTurn=e=>({gathers:!1,prepare:async t=>n=>e(t,n)});function requireSessionId(e){let t=parseSessionId(e);if(!t.ok)throw new BadVerbArgs(`session id ${t.problem}`);return t.id}function oneArg(e){return decodeWire(()=>decodeURIComponent(e))}function ask(e,t){e.acts.ask(e.effects,t)}const copy=async(e,t)=>ask(t,{kind:`copy`,session:t.session,text:oneArg(e)}),DRAWERS=new Set([`request`,`feed`]);function requireDrawer(e){if(!DRAWERS.has(e))throw new BadVerbArgs(`unknown renderer ${JSON.stringify(e)}`);return e}const copyDiagnostic=async(e,t)=>{let[n=``,r=``,i=``]=decodeWire(()=>decodeSegments(e)),a=requireSessionId(n),o=t.diagnosticCopy(a,requireDrawer(r),i);if(o===void 0)throw new BadVerbArgs(`that message is no longer listed in session ${a}'s diagnostics — open the indicator beside the settings door again and copy from there`);ask(t,{kind:`copy`,session:a,text:o})},openVscode=async(e,t)=>ask(t,{kind:`open`,session:t.session,target:oneArg(e)}),setState=async(e,t)=>{let[n=``,...r]=decodeWire(()=>decodeSegments(e)),i=requireSessionId(n),a=t.gates.state.gateFor(sessionConfig(t,i));if(r.length===0)throw new BadVerbArgs(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new BadVerbArgs(`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 BadVerbArgs(`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 BadVerbArgs(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}refuseDisorderedPicks(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})`)},STEP_INT_RE=/^-?\d+$/;function stepWithin(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const stepState=async(e,t)=>{let[n=``,r=``,i=``]=decodeWire(()=>decodeSegments(e)),a=requireSessionId(n);if(!r)throw new BadVerbArgs(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!STEP_INT_RE.test(i))throw new BadVerbArgs(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=sessionConfig(t,a),c=t.gates.state.gateFor(s),l=c.rangeParamsFor(r);if(!l)throw new BadVerbArgs(`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&&STEP_INT_RE.test(u)?clampTo(l,parseInt(u,10)):stepFrom(`step-state`,r,l,stateKeySeed(s,e=>t.sessionState.get(a,e),r)),f=stepWithin(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new BadVerbArgs(`step-state: ${p.reason}`);refuseDisorderedPicks(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 refuseDisorderedPicks(e,t,n,r){let i=r.filter(e=>e.key.startsWith(PLACEMENT_DRAFT_NS));if(i.length===0)return;let a=placementPickProblems(sessionConfig(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new BadVerbArgs(`${n}: refused — ${a.join(`; `)}`)}function clampTo(e,t){return Math.max(e.min,Math.min(e.max,t))}function stepFrom(e,t,n,r){if(r===null)return n.min;if(!STEP_INT_RE.test(r))throw new BadVerbArgs(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return clampTo(n,parseInt(r,10))}function recordedTarget(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function parseRenderOrigin(e){let t;try{t=JSON.parse(e)}catch{throw new BadVerbArgs(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new BadVerbArgs(`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 BadVerbArgs(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,target:recordedTarget(a,i)}}function sessionOrigin(e,t){let n=recordedOrigin(e,t);if(n===null)throw new BadVerbArgs(`session ${t} has not rendered yet — no config to act on`);return n}function recordedOrigin(e,t){let n=e.sessionState.get(t,SESSION_RENDER_ORIGIN_KEY);return n===null?null:parseRenderOrigin(n)}function changeDone(e,t,n,r){let i=e.configWrites.settled(t,n);return i===void 0?!1:(i!==`owed`&&changeLanded(e,i,r),!0)}function changeLanded(e,{session:t,files:n,answered:r,consequence:i,outcome:a},o){let s=[],c=e=>{try{e()}catch(e){s.push(failureOf(e).message)}};if(a.kind===`ok`)c(()=>{let i=recordedOrigin(e,t);i!==null&&(r||n.includes(originHome(e,i).path))&&e.reloadConfig(i)}),c(()=>i(o));else if(a.kind===`closing`)return;else s.push(a.reason);if(s.length===0)return;let l=s.join(`
|
|
225
|
-
`);e.log(`warn`,`config change: ${l} (session=${t})`),holdClickError(e.sessionState,t,l,e.now())}function proveLoadsAsHome(e,t,n,r){let i=t===null?null:recordedOrigin(e,t),a=i===null?null:originHome(e,i);if(a?.path!==n)throw new BadVerbArgs(`${n} is not the config file this session renders from — its step is not taken`);proveLoads(a,r)}function sessionConfig(e,t){return e.configFor(sessionOrigin(e,t))}function laneMeter(e,t,n){let r=recordedOrigin(e,t);if(r===null)return null;let i=()=>e.lanes.of(r,t,n);return{sessionId:t,latest:n,before:i(),read:i}}function nestOf(e,t){let n=recordedOrigin(e,t);return n===null?NO_NEST:disclosureNest(e.configFor(n))}function originHome(e,t){return durableConfig(e.locations,repoConfigs(e.stateDir).read(),t.projectDir,t.cwd,t.target.path)}function editStore(e,t){return{read:t=>e.configWrites.read(t),record:(n,r,i)=>e.journal.file(t,n,r,i)}}const setConfig=async(e,t)=>{let[n=``,r=``,i=``]=decodeWire(()=>decodeSegments(e)),a=requireSessionId(n),o=sessionOrigin(t,a),s=t.configFor(o),c=t.gates.config.gateFor(s);if(!r)throw new BadVerbArgs(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new BadVerbArgs(`set-config: ${l.reason}`);let u=originHome(t,o),d=durableLanding(s,e=>t.sessionState.get(a,e),r);writeValues(editStore(t,a),u,[[d.key,l.value]]),t.log(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},stepConfig=async(e,t)=>{let[n=``,r=``,i=``]=decodeWire(()=>decodeSegments(e)),a=requireSessionId(n);if(!r)throw new BadVerbArgs(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!STEP_INT_RE.test(i))throw new BadVerbArgs(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=sessionOrigin(t,a),c=t.configFor(s),l=t.gates.config.gateFor(c),u=l.rangeParamsFor(r);if(!u)throw new BadVerbArgs(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=originHome(t,s),f=durableLanding(c,e=>t.sessionState.get(a,e),r),p=readValue(editStore(t,a).read(d.path),f.key),m=typeof p==`number`?clampTo(u,p):stepFrom(`step-config`,r,u,configKeySeed(f.globals,r)),h=stepWithin(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new BadVerbArgs(`step-config: ${g.reason}`);writeValues(editStore(t,a),d,[[f.key,g.value]]),t.log(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},save=async(e,t)=>{let[n=``]=decodeWire(()=>decodeSegments(e)),r=requireSessionId(n),i=sessionOrigin(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=settingDrafts(a,o),c=placementDrafts(a,o);if(s.length+c.length===0){t.log(`info`,`save: nothing unsaved (session=${r})`);return}let l=t.gates.state.gateFor(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new BadVerbArgs(`save: ${t.reason}`);return[e.target,t.value]});gatePlacements(`save`,l,c);let d=originHome(t,i);writeDrafts(editStore(t,r),d,u,c);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(placementLog)].join(` `)} → ${d.path} (session=${r})`)},placementLog=e=>`${e.preset}/${e.id}.settings.${e.setting}=${settingSpelling(e.value)}`;function gatePlacements(e,t,n){for(let r of n){let n=t.validate(r.key,settingSpelling(r.value));if(!n.ok)throw new BadVerbArgs(`${e}: ${n.reason}`)}}const savePreset=async(e,t)=>{let[n=``]=decodeWire(()=>decodeSegments(e)),r=requireSessionId(n),i=sessionOrigin(t,r),a=t.configFor(i),o=presetSnapshot(a,e=>t.sessionState.get(r,e)),s=t.gates.state.gateFor(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new BadVerbArgs(`save-preset: ${t.reason}`);return[e.configKey,t.value]});gatePlacements(`save-preset`,s,o.placements);let l=originHome(t,i),u=writePreset(editStore(t,r),l,o.from,o.globals,c,o.placements);for(let e of[...SETTING_PROJECTIONS.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,SETTINGS.preset.sessionKey,u),t.log(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(placementLog)].join(` `)} → ${l.path} (session=${r})`)},saveThemeDefault=async(e,t)=>{let[n=``]=decodeWire(()=>decodeSegments(e)),r=requireSessionId(n),i=sessionOrigin(t,r),a=themeDefaultSave(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new BadVerbArgs(`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=originHome(t,i),s=writeThemeDefault(editStore(t,r),o,a.theme,a.look),c=new Set(settingDrafts(s,e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),l=THEME_DEFAULT_FIELDS.map(e=>SETTINGS[e].sessionKey).filter(e=>!c.has(e));for(let e of l)t.sessionState.clear(r,e);t.log(`info`,`save-theme-default: ${a.theme} ${THEME_DEFAULT_FIELDS.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},deletePreset=async(e,t)=>{let[n=``,r=``]=decodeWire(()=>decodeSegments(e)),i=requireSessionId(n);if(!r)throw new BadVerbArgs(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=originHome(t,sessionOrigin(t,i));deletePreset$1(editStore(t,i),a,r);let o=SETTINGS.preset.sessionKey;t.sessionState.get(i,o)===r&&t.sessionState.clear(i,o),t.log(`info`,`delete-preset: ${r} ← ${a.path} (session=${i})`)},resetConfig=async(e,t)=>{let[n=``,...r]=decodeWire(()=>decodeSegments(e)),i=requireSessionId(n),a=sessionOrigin(t,i),o=t.gates.config.gateFor(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new BadVerbArgs(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=originHome(t,a),l=r.map(resetLayers),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);deleteValues(editStore(t,i),c,u);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 endedPlacements(e,t){let n=(e,t)=>[...walkNodes(presetRoot(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(presetNames(t.presets).flatMap(e=>n(t,e).map(t=>configureMember(ident(e),placementId(t)))));return presetNames(e.presets).flatMap(t=>n(e,t).map(e=>({member:configureMember(ident(t),placementId(e)),node:e})).filter(({member:e})=>!r.has(e)))}function endedSessionKeys(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[EDIT_CONFIGURE_KEY]:[]])}const applyLayoutOp=async(e,t)=>{let[n=``,r=``,i=``]=decodeWire(()=>decodeSegments(e)),a=requireSessionId(n),o=sessionOrigin(t,a),s=t.configFor(o),c=t.gates.config.gateFor(s);if(!r)throw new BadVerbArgs(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new BadVerbArgs(`apply-layout-op: ${l.reason}`);let u=decodeLayoutOp(l.value);if(u===null)throw new BadVerbArgs(`apply-layout-op: "${l.value}" is not a layout op token`);let d=originHome(t,o),{placed:f,config:p}=applyLayoutOp$1(editStore(t,a),d,r,u),m=endedSessionKeys(endedPlacements(s,p),t.sessionState.get(a,EDIT_CONFIGURE_KEY)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of m)t.sessionState.clear(a,e);t.log(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(m)} (session=${a})`)},undo=async(e,t)=>{let[n=``]=decodeWire(()=>decodeSegments(e)),r=requireSessionId(n),i=t.journal.undo(r);t.journal.wrote(),t.log(`info`,`undo: restored ${describeStep(i)} (session=${r})`)},back=async(e,t)=>{let n=requireSessionId(oneArg(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,t.gates.state.gateFor(sessionConfig(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.log(`info`,`back: ${a} discarded=${i} (session=${n})`)},rewind=async(e,t)=>{let n=requireSessionId(oneArg(e));t.journal.wrote();let r=t.journal.rewind(n);t.log(`info`,`rewind: put back ${describeStep(r)||`nothing`} as edit mode found it (session=${n})`)},redo=async(e,t)=>{let[n=``]=decodeWire(()=>decodeSegments(e)),r=requireSessionId(n),i=t.journal.redo(r);t.journal.wrote(),t.log(`info`,`redo: re-applied ${describeStep(i)} (session=${r})`)},applyUpdate=async(e,t)=>ask(t,{kind:`apply-update`,session:requireSessionId(oneArg(e))});function sessionHints(e,t){let n=e.sessionState.get(t,SESSION_CLIENT_HINTS_KEY);if(n===null)throw new BadVerbArgs(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new BadVerbArgs(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new BadVerbArgs(`client hints record is not an object: ${n}`);return parseClientHints(r)}function writeReport(e,t,n){let r=runDoctor(n);e.sessionState.setBatch(t,doctorReportPairs(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${configFields(n.config)} ${nerdFontFields(n.nerdFont,n.marks)} ${linkFields(n.terminal,n.clicked)} ${terminalFeatureFields(n.terminal,n.width)} ${installFields(n.install)} ${daemonFields(n.daemon)} ${dataFields(n.data)} ${transcriptFields(n.transcripts)} ${frameFields(n.frames,n.claudeSettings)} ${truecolorEnvFields(n.claudeSettings.origin.sources)} (session=${t})`)}async function clickGather(e,t,n,r){let i={kind:`clicked`,sessionId:t,via:e.arrival.via},[a,o]=await Promise.all([e.clients.ofSession(t,e.now()),e.serving()]),s,c;try{[s,c]=await Promise.all([gatherFacts({...n,loadConfig:()=>r},sessionHints(e,t),sessionOrigin(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:o},{kind:`ok`,value:a.map(e=>e.rateLimits)},{kind:`ok`,value:a.map(e=>e.transcript)},i,{kind:`ok`,value:barsOf(i,a)},sessionWidth(t,a),readStores(e.doctorStores)),e.installFacts(e.bundle,a.map(e=>e.client))])}catch(e){throw e instanceof DoctorBusy?new BadVerbArgs(e.message):e}let l={facts:s,install:c,current:async e=>{let i=n.loadConfig(sessionOrigin(e,t));return i.config===r.config&&i.error===r.error&&i.warning===r.warning?l:clickGather(e,t,n,i)}};return l}const gatherClick=(e,t)=>{let n=oneAskPerClick(e.doctor);return clickGather(e,t,n,n.loadConfig(sessionOrigin(e,t)))};async function clickFacts(e,t,n){let{facts:r,install:i}=await e.gather(n.current),a=readStores(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:clickArrived(e.arrival),install:i,clicked:clickedFrom(e,o)}}function clickedFrom(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?sightingOf(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>withClicked(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 doctorRun={gathers:!0,prepare:async(e,t)=>{let n=requireSessionId(oneArg(e)),r=await gatherClick(t,n);return async e=>writeReport(e,n,await clickFacts(e,n,r))}},doctorFix={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``]=decodeWire(()=>decodeSegments(e)),i=requireSessionId(n),a=checkByName(r);if(a===void 0)throw new BadVerbArgs(`doctor-fix: unknown check "${r}"`);let o=await gatherClick(t,i);return async e=>{let t=await clickFacts(e,i,o),n=a.probe(t);if(n.ok||n.fix===void 0)throw new BadVerbArgs(`doctor-fix: ${a.label} — ${n.ok?`nothing to fix`:n.reason}`);let r=applyFix(e.doctorStores,n.fix,t);if(r.kind===`failed`)throw new BadVerbArgs(`doctor-fix: ${a.label} — ${r.reason}`);e.log(`info`,`doctor-fix: ${a.name} → ${describeFix(n.fix)} (session=${i})`),writeReport(e,i,r.value)}}},doctorMark={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``,i=``]=decodeWire(()=>decodeSegments(e)),a=requireSessionId(n),o=checkByName(r);if(o===void 0)throw new BadVerbArgs(`doctor-mark: unknown check "${r}"`);if(!GLYPH_MARKS.includes(i))throw new BadVerbArgs(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${GLYPH_MARKS.join(` or `)}`);let s=await gatherClick(t,a);return async e=>{let t=await clickFacts(e,a,s),n=o.probe(t);if(n.ok||n.sighting===void 0)throw new BadVerbArgs(`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=>withMark(e,...r));if(c.kind===`failed`)throw new BadVerbArgs(`doctor-mark: ${c.reason}`);e.log(`info`,`doctor-mark: ${o.name} ${i} on ${n.sighting.id} (session=${a})`),writeReport(e,a,{...t,marks:c})}}},slash=async(e,t)=>{let[n=``,r=``]=decodeWire(()=>decodeSegments(e)),i=requireSessionId(n),a=Object.values(t.configFor(sessionOrigin(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new BadVerbArgs(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=tmuxPaneOf(sessionHints(t,i).tmux);if(s.kind===`refused`)throw new BadVerbArgs(`${r} was not typed: ${s.reason}`);ask(t,{kind:`type-slash`,session:i,pane:s.hint,line:o.slash})};function runOf([e=``,t=``,n=``,r=``],i){let a=requireSessionId(e),o=sessionOrigin(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 BadVerbArgs(`"${t}" is not a run action this session's config declares`);let l=runDeclaration(c);if(!i.links.verify({sessionId:a,action:t,declaration:l,evaluated:n},r))throw new BadVerbArgs(`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 BadVerbArgs(`run ${t}: what the link carries is not JSON`)}let[d,...f]=u.run;if(d===void 0||d===``)throw new BadVerbArgs(`run ${t}: the program evaluated to nothing`);let p=i.sourcesFor(o);return{kind:`run`,session:a,action:t,program:d,args:f,env:{...sessionEnv({sessionId:a,projectDir:o.projectDir,claudeConfigDir:sessionHints(i,a).claudeConfigDir}),...u.env},cwd:c.cwd??i.locations.home,refreshes:c.refreshes.map(e=>({name:e,folder:p.get(e)}))}}const run=async(e,t)=>ask(t,runOf(decodeWire(()=>decodeSegments(e)),t)),repoConfig=async(e,t)=>{let[n=``,r=``,i=``,a=``]=decodeWire(()=>decodeSegments(e)),o=requireSessionId(n),s=REPO_ANSWERS.find(e=>e===i);if(s===void 0||!t.links.verify(repoAnswerFields(o,r,s),a))throw new BadVerbArgs(`the answer's signature does not match what it carries: it was not drawn by this daemon`);t.configWrites.answer(r,s),t.journal.wrote()},LEAF_VERBS=new Map([[VERB_COPY,inTurn(copy)],[VERB_OPEN_VSCODE,inTurn(openVscode)],[VERB_SET_STATE,inTurn(setState)],[VERB_STEP_STATE,inTurn(stepState)],[VERB_SET_CONFIG,inTurn(setConfig)],[VERB_STEP_CONFIG,inTurn(stepConfig)],[VERB_RESET_CONFIG,inTurn(resetConfig)],[VERB_SAVE,inTurn(save)],[VERB_SAVE_PRESET,inTurn(savePreset)],[VERB_SAVE_THEME_DEFAULT,inTurn(saveThemeDefault)],[VERB_DELETE_PRESET,inTurn(deletePreset)],[VERB_APPLY_LAYOUT_OP,inTurn(applyLayoutOp)],[VERB_UNDO,inTurn(undo)],[VERB_REDO,inTurn(redo)],[VERB_BACK,inTurn(back)],[VERB_REWIND,inTurn(rewind)],[VERB_APPLY_UPDATE,inTurn(applyUpdate)],[VERB_DOCTOR_RUN,doctorRun],[VERB_DOCTOR_FIX,doctorFix],[VERB_DOCTOR_MARK,doctorMark],[VERB_SLASH,inTurn(slash)],[`run`,inTurn(run)],[VERB_REPO_CONFIG,inTurn(repoConfig)],[VERB_COPY_DIAGNOSTIC,inTurn(copyDiagnostic)]]),hoisted=(e,t,n)=>n.journalTurns.gathering(()=>e.prepare(t,n)).catch(e=>()=>Promise.reject(e));async function perform(e,t,n,r){await(r??await n.gather(n=>e.prepare(t,n)))(n)}async function headGather(e,t){let[n]=e,r=n===void 0?void 0:LEAF_VERBS.get(n.verb);return r?.gathers?hoisted(r,n.value,t):void 0}function stepsOf(e,t){return batchAdjacentWrites(e===`dispatch`?parseEffects(t):[{verb:e,value:t}])}async function foldEffects(e,t,n,r){let i=[],a=!1;for(let[t,{verb:o,value:s}]of e.entries()){let e=LEAF_VERBS.get(o);if(!e){i.push(`unknown effect verb "${o}"`);continue}try{await perform(e,s,n,t===0?r:void 0)}catch(e){let t=failureOf(e);if(t.kind!==`bad-request`&&t.kind!==`threw`)throw i.length>0&&n.log(`warn`,`click: ${i.join(`; `)}`),e;t.kind===`threw`&&(a=!0),i.push(`${o}: ${t.message}`)}}if(i.length>0){t!==null&&holdClickError(n.sessionState,t,i.join(`
|
|
226
|
-
`),n.now());let e=i.join(`; `);throw a?Error(e):new BadVerbArgs(e)}}function throwAll(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}async function journaled(e,t,n,r,i,a){let o=e===null?null:laneMeter(n,e,t),s=n.history.begin({read:e=>n.configWrites.read(e),land:(e,t,r)=>n.configWrites.land(e,t,r),prove:(t,r)=>proveLoadsAsHome(n,e,t,r)}),c=n.navigation.begin(s.sessionState),l=[],u=e=>closingView(e,e=>nestOf(n,e),e=>n.log(`info`,e)),d={...n,session:e,sessionState:u(s.sessionState),journal:s,navigating:u(c.sessionState)};try{await a({...d,gather:e=>i.landed(e(d))})}catch(e){l.push(e)}let f=e=>{let t=[];for(let e of[c,s])try{e.commit()}catch(e){t.push(e)}if(o!==null)try{let t=o.read();n.lanes.clicked(o.sessionId,o.latest,s.written()?o.before:t,t,e)}catch(e){t.push(e)}throwAll(t)};try{n.configWrites.seal(r,e,f)}catch(e){l.push(e)}throwAll(l)}function click(e){return async(t,n)=>{let r=clickSessionOf(e,t),i=r?.ok?r.id:null,a=stepsOf(e,t);return n.journalTurns.click(e,i,{placed:n.placeWaited,waited:n.turnWaited,gone:n.clientGone,gathered:n.gatherTook},()=>headGather(a,n),(e,t)=>journaled(i,n.latest,n,n.effects,t,async t=>{try{await foldEffects(a,i,t,e)}finally{i!==null&&n.clickLanded(i)}}))}}const VERBS=new Map([...LEAF_VERBS.keys(),VERB_DISPATCH].map(e=>[e,click(e)])),VERB_NAMES=Object.freeze([...VERBS.keys()]);function closeIdleMenus(e,t,n,r,i){return r.journalTurns.take(`menu-idle`,{waited:t=>r.log(`info`,`menu-idle: waited=${t}ms (session=${e})`),gone:async()=>!1},a=>journaled(e,t,r,i,a,async t=>{if(!await a.landed(n.confirm())){t.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}let r=openRoots(nestOf(t,e),n=>t.navigating.get(e,n));t.navigating.setBatch(e,r.map(({key:e})=>({key:e,value:DISCLOSURE_CLOSED}))),t.log(`info`,`menu-idle: closed=${r.map(({key:e})=>e).join(`,`)||`-`} idle=${n.idleS.toFixed(1)}s timeout=${n.timeoutS}s (session=${e})`)}))}function verbsOver(e,t){return{handler:n=>{let r=VERBS.get(n);return r&&((n,{click:i,...a})=>r(n,{...e,...a,clientGone:()=>t.gone(i)}))},closeIdle:(t,n,r,i)=>closeIdleMenus(t,n,r,e,i),changeDone:(t,n,r)=>changeDone(e,t,n,r)}}const MAX_STEPS=20,MAX_SESSIONS$1=32,isNavigationKey=e=>!isSettingKey(e)&&!isConfirmKey(e)&&e!==`update.dismissed`&&e!==DIAGNOSTICS_VIEWING;var NavigationHistory=class{past=import_dist$1.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:recordingView(e,isNavigationKey,(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 BadVerbArgs(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,import_dist$1.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(-MAX_STEPS))}put(e,t){(0,import_dist$1.runInAction)(()=>{for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>MAX_SESSIONS$1;)this.past.delete(this.past.keys().next().value)})}};const MAX_RECORDS=512,RENDERERS=[`request`,`feed`],generations=new WeakMap;let nextGeneration=0;const generationOf=e=>{let t=generations.get(e);if(t!==void 0)return t;let n=nextGeneration++;return generations.set(e,n),n};var RenderWarningRecords=class{records=new Map;constructor(e=MAX_RECORDS){this.maxRecords=e}of(e,t){return this.records.get(keyOf(e,t))?.warnings??[]}ofSession(e,t,n){let r=generationOf(n.config),i=[];for(let n of RENDERERS){let a=this.records.get(keyOf(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=keyOf(e,t);this.records.delete(a),this.records.set(a,{generation:generationOf(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 keyOf=(e,t)=>`${t}\0${e}`;var ActsOnTheirWay=class{owed=new Set;constructor(e,t){this.mint=e,this.failed=t}ask(e,t){let n=this.mint();this.owed.add(n),e.push({...t,id:n})}done(e,t,n){return this.owed.delete(e)?(t!==null&&(n.kind===`failed`||n.kind===`refused`)&&this.failed(t,n.reason),!0):!1}};const MAX_SESSIONS_OWED=1024,atOf=e=>({sessionId:e.hookData.session_id,tmux:e.hints.tmux,session:{projectDir:e.requested.projectDir,claudeConfigDir:e.hints.claudeConfigDir??null,transcript:e.hookData.transcript_path,answered:answeredOf(e.hookData)}});function inPane(e,t){let n=tmuxPaneOf(e.tmux);return n.kind===`refused`?n:t(n.hint)}const act=e=>({kind:`act`,act:e}),nothing=e=>({kind:`nothing`,said:e}),LANE_SETUP={band:{on:e=>act({kind:`surface`,surface:`band`,on:!0,session:e.sessionId,pane:tmuxPaneOf(e.tmux),at:e.session}),off:()=>nothing(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:e=>inPane(e,t=>act({kind:`restart-claude`,session:e.sessionId,pane:t,at:e.session})),off:()=>nothing(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:e=>inPane(e,t=>act({kind:`surface`,surface:`pane`,on:!0,session:e.sessionId,pane:t})),off:e=>{let t=tmuxPaneOf(e.tmux);return t.kind===`refused`?nothing(`no bar pane to close: ${t.reason}`):act({kind:`surface`,surface:`pane`,on:!1,session:e.sessionId,pane:t.hint})}},tmuxStatus:{on:e=>inPane(e,e=>nothing(`the daemon draws ${e.pane}'s bar in its status line`)),off:()=>nothing(`nothing to stop: the daemon puts the status line back once the lane is off`)}};var LaneActs=class{owed=new Map;constructor(e){this.deps=e}clicked(e,t,n,r,i){let a=LANE_NAMES.filter(e=>n[e]!==r[e]),o=this.take(e);for(let e of a)o.has(e)||o.set(e,n[e]);let s=e=>a.includes(e)?`click`:`owed`;if(t!==null){this.settle(atOf(t),o,r,s,i);return}for(let[e,t]of o)t===r[e]&&o.delete(e);if(a.length>0){let t=[...o.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}o.size>0&&this.owed.set(e,o);for(let[e,t]of this.owed){if(this.owed.size<=MAX_SESSIONS_OWED)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t,n){let r=this.owed.get(e.hookData.session_id);r!==void 0&&(this.owed.delete(e.hookData.session_id),this.settle(atOf(e),r,t,()=>`owed`,n))}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r,i){for(let[a,o]of t){let t=n[a],s=`lane: ${a} ${t?`on`:`off`}`,c=`by=${r(a)} (session=${e.sessionId})`;if(t===o){this.deps.log(`info`,`${s} — nothing owed: its switch is back where the lane is ${c}`);continue}let l=LANE_SETUP[a][t?`on`:`off`](e);switch(l.kind){case`act`:this.deps.log(`info`,`${s} — asked ${c}`),this.deps.ask(i,l.act);break;case`nothing`:this.deps.log(`info`,`${s} — ${l.said} ${c}`);break;case`refused`:this.deps.log(`warn`,`${s}: ${l.reason} ${c}`),this.deps.refused(e.sessionId,`${s}: ${l.reason}`)}}}},WorldStates=class{constructor(e){this.took=e}documents=import_dist$1.observable.map(void 0,{deep:!1});take(e){let t=this.documents.get(e.session);if(t!==void 0&&e.seq<=t.seq){if(e.seq===t.seq&&(0,import_dist$1.compareStructural)(e,t))return;throw Error(`world state seq ${e.seq} for session ${JSON.stringify(e.session)} does not follow the held seq ${t.seq}`)}(0,import_dist$1.runInAction)(()=>this.documents.set(e.session,e)),this.took(e)}of(e){let t=this.documents.get(e);if(t===void 0)throw Error(`no world state for session ${JSON.stringify(e)}: the host hands one in with the config ahead of every request`);return t}drop(e){(0,import_dist$1.runInAction)(()=>this.documents.delete(e))}},UpdateGate=class{newest=null;gate=null;constructor(e){this.gates=e}took(e){if(e.kind===`pending`||this.newest!==null&&e.at<this.newest)return;this.newest=e.at;let t=e.kind===`ok`?updateIdentity(e.value):null;(this.gate?.identity??null)!==t&&(this.gate?.dispose(),this.gate=t===null?null:{identity:t,dispose:this.gates.state.register(UPDATE_DISMISSED_KEY,[t])})}},Watches=class{minted=0;held=new Map;constructor(e){this.host=e}acquire(e,t,n){let r=++this.minted,i={deaf:[],heard:n};return this.held.set(r,i),this.host.watch(r,e,t),{release:()=>{this.held.delete(r)&&this.host.unwatch(r)},get deaf(){return i.deaf}}}follow(e,t,n){return followWatch(e,t,(e,t)=>this.acquire(e,t,n))}pushed(e,t,n){let r=this.held.get(e);if(r===void 0)return;let i=!(0,import_dist$1.compareStructural)(r.deaf,n);r.deaf=n;let a=t??(i?{kind:`unknown`}:null);a!==null&&r.heard(a)}};function sessionSource(e){return({sessionId:t,state:n,store:r,requested:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>resolveEffectiveGlobals(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.compose`,`computed`,()=>{let{hookData:t,hints:n}=i();return{hookData:t,hints:n,home:e.home}}),c=r.derive(`session.draw`,`computed`,()=>({sources:[...n.sources.keys()],effective:o.read(),configFacts:{...settingCounts(n.config,n.fileHeldSettings,a),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})),l=()=>e.worldStates.of(t),u=r.derive(`session.payload`,`computed`,()=>composePayload(l(),s.read(),c.read()));return{session:t,payload:()=>u.read(),effective:()=>c.read().effective,facts:l,run:e=>l().runs[e]??UNREAD_RUN,hints:()=>s.read().hints,failure:()=>stampFailureOf(l()),selections:()=>c.read().effective}}}function*variablesOf(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*templatesOf(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 presetNames(e.presets)){for(let n of walkNodes(presetRoot(e,t).node))n.when!==void 0&&(yield n.when);let n=presetGlobals(e,t);for(let e of EXPRESSION_SLOTS){let t=n[e];isExpression(t)&&(yield t)}}for(let[,t]of variablesOf(e))for(let[,e]of variableTemplates(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of actionTemplates(t))yield e}function unusedDeclarations(e,t,n){let r=valueReadsOf(t),i=new Set,a=new Set,o=new Set;for(let e of templatesOf(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of templateActionRefs(e,t.helpers))a.add(n);for(let n of templateHelperRefs(e,t.helpers))o.add(n)}for(let[,e]of variablesOf(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 presetNames(t.presets))for(let n of walkNodes(presetRoot(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=>!isReservedName(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(variablesOf(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))]}const ENTRY_BYTES=3*1024*1024,COMPILE_BYTES=10*1024*1024,VIEW_BYTES=2.5*1024*1024,RENDER_CACHE_RESERVE_BYTES=96*1024*1024;function renderCacheBudget(e){return Math.floor(Math.max(e/4,e*NEAR_LIMIT-RENDER_CACHE_RESERVE_BYTES))}const MAX_ENTRIES=256;function pluginLoadLine(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[pluginDataVar(pluginNs(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[pluginNs(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>ownedBy(e)(t)&&t!==pluginDataVar(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${chainName(e,`<default>`)}: projections=${[...projectionsOf(n).keys()].join(`,`)||`-`} instantSegments=${instantSegments(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 heardField=e=>{switch(e.kind){case`changed`:return e.paths.join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},causeField=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${heardField(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function configLoadedLine(e,t,n){let r=e=>valueOf$1(e.join(`,`)||`-`);return`config loaded projectDir=${valueOf$1(e.projectDir)} cwd=${valueOf$1(e.cwd)} cause=${valueOf$1(causeField(t))} state=${n} files=${valueOf$1(chainName(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 configDisposeLine(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function cacheKey(e,t,n){return e+`\0`+t+`\0`+(n??``)}function authoredRoots(e,t){return new Set(presetNames(e.presets).filter(n=>presetRoot(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function watchTargetsFor(e,t){let{loaded:n,dropped:r,unreached:i}=e.state.plugins,a=[...new Set([...e.state.plugins.roots,path.join(e.projectDir,REPO_PLUGIN_DIR)])];return watchTargetsOf({named:[...dslConfigCandidatePaths(t,e.projectDir,e.cwd,e.configFile),...a,...n.map(e=>e.path),...[...r,...i].map(e=>e.path),...new Set(e.state.sources.values())],whole:a})}function joinWarnings(e){return e.filter(Boolean).join(`
|
|
227
|
-
`)||null}const thrown=e=>e instanceof Error?e.message:String(e);function plugins(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function loadKey(e){let{loaded:t,chain:n}=e;return digestOf({cwd:e.cwd,chain:{layers:n.layers,home:n.home,repo:n.repo,locs:n.locs},loaded:{layers:t.layers.map(e=>({path:e.path,raw:e.raw,config:e.config,plugins:plugins(e.plugins),source:null,warnings:null})),base:t.base,installed:{...plugins(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])})}function declaredSources(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))r.kind===`source`&&t.set(n,r.storage);return t}function resolveLoad(e,t){let n=[];try{let r=loadConfigChain(t.locs,t.layers,DEFAULT_DSL_CONFIG,{warned:e=>n.push(...e)},{repo:t.repo,cwd:e}),i={cwd:e,chain:t,loaded:r,sources:declaredSources(r.config)};return{kind:`resolved`,...i,key:loadKey(i),warnings:n}}catch(e){return e instanceof ConfigError&&n.push(...e.warnings),{kind:`failed`,cause:e,warnings:n}}}function buildRenderState(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??DEFAULT_DSL_CONFIG,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new VariableStore(t.clock),m=new SourceRegistry(p,o.globals.default_empty_value??``,t.sessionState,null,t.env),h;try{h=registerCompiled(o,m,n,t.compile??compileAlone(t.signer),DIRECTORY_SCOPE),f.push(...h.loadWarnings);let e=m.view();f.push(...declareDslVariables(o,e,n,VIEW_SCOPE)),e.dispose(),t.gates.state.gateFor(o),t.gates.config.gateFor(o)}catch(e){return m.dispose(),e instanceof ConfigError&&f.push(...e.warnings),{kind:`failed`,cause:e,warnings:f}}return{kind:`built`,state:{config:o,dropped:c,compileKey:h.compileKey,loadKey:e.key,buildWarnings:f,store:p,registry:m,compiled:h.compiled,authoredRoots:authoredRoots(l,u),fileHeldSettings:fileHeldSettings(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>unusedDeclarations(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 settle(e,t,n,r,i){let a={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:elapsedMs(i,e.started)},o=t=>joinWarnings([...e.advisories,...n,...t]);switch(r.kind){case`built`:case`kept`:return{...a,kind:r.kind,warning:o(r.state.buildWarnings),state:r.state,error:null};case`failed`:return{...a,kind:`failed`,warning:o(r.warnings),state:null,error:thrown(r.cause),cause:r.cause}}}function loadChain(e,t,n,r,i=null){let a=resolveLoad(t,n);if(a.kind===`failed`)return settle(e,n,[],a,r.clock);let o=i?.loadKey===a.key?{kind:`kept`,state:i}:buildRenderState(a,r);return settle(e,n,a.warnings,o,r.clock)}function loadFromDisk(e,t,n,r,i=null){let a=r.clock.monotonic(),o=resolveDslConfig(r.locations,repoConfigs(r.stateDir).read(),e,t,n),{repos:s}=o,c={layers:o.kind===`chain`?o.layers:[],home:o.home,repo:s.plugins,locs:r.locations};return loadChain({repos:s,advisories:[detectConfigCollisions(r.locations,e,t),configResolutionNotice(o),repoUnreadNotice(s)],started:a},t,c,r,i)}function fallbackState(e,t,n){let r=resolveLoad(e,{layers:[],home:``,repo:t,locs:n.locations}),i=r.kind===`failed`?r:buildRenderState(r,n);if(i.kind===`failed`)throw Error(`bundled default failed to load: ${thrown(i.cause)}`,{cause:i.cause});return i.state}const DIRECTORY_SCOPE=new Set([`directory`]),VIEW_SCOPE=new Set([`view`]);function openView(e,t,n,{source:r,changed:i,log:a}){let o=n.hookData.session_id,s=e.registry.view();declareDslVariables(e.config,s,t,VIEW_SCOPE);let c=import_dist$1.observable.box(n,{deep:!1}),l;try{l=r({sessionId:o,state:e,store:s.variableStore,requested:()=>c.get()})}catch(e){throw s.dispose(),e}bindView(e.compiled,s.variableStore,s,l);let u=(0,import_dist$1.reaction)(()=>[l.payload(),l.selections(),s.published(),e.registry.published()],()=>i(o),{equals:import_dist$1.compareShallow,fireImmediately:!0,onError:e=>a(`error`,`session view change threw sid=${JSON.stringify(o)}: ${String(e)}`)});return{sessionId:o,state:e,store:s.variableStore,registry:s,source:l,requested:e=>{e!==c.get()&&(0,import_dist$1.runInAction)(()=>c.set(e))},facts:()=>c.get(),lastRenderCellsBySegment:new Map,retire:u,dispose:()=>(u(),s.dispose())}}const subscriptionsOf=({state:e,registry:t})=>[...[...e.sources].map(([e,t])=>({kind:`plugin`,source:e,folder:t})),...t.subscriptions().map(e=>({kind:`run`,run:e}))];var RenderCache=class{entries=new Map;answersWatch;lifetime=new AbortController;closing=this.lifetime.signal;get closed(){return this.closing.aborted}due=new Map;walk=null;holds=new Map;storageHolds=0;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??quietLogger,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},fs.mkdirSync(repoConfigsDir(e.stateDir),{recursive:!0});let{dir:n,name:r}=nearestWatchTarget(repoConfigsPath(e.stateDir));this.answersWatch=e.watchers.acquire(`repo-configs:${n}/${r}`,{dirs:[{path:n,filenames:[r]}]},e=>this.reloadEvery({kind:`answers-watch`,heard:e}))}compileOf(e,t){return this.compiles.get(e)??compileDslConfig(t,this.deps.signer)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*ENTRY_BYTES+e.size*COMPILE_BYTES+this.views.size*VIEW_BYTES}getOrCreate(e,t,n){let r=cacheKey(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`,pluginLoadLine(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??fallbackState(t,a.repos.plugins,this.deps),watch:null};return this.serve(o.state),this.entries.set(r,o),this.holdFolders(o.state),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=${mb(this.accountedBytes())}/${mb(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++;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 this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}pin(e){this.pins.set(e,(this.pins.get(e)??0)+1);let t=!1;return()=>{if(t)throw Error(`render-cache pin released twice`);t=!0;let n=(this.pins.get(e)??0)-1;n>0?this.pins.set(e,n):this.pins.delete(e)}}viewOf(e,t,n,r){let i=n.hookData.session_id,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;try{o=this.opened(e,t,n,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),o}opened(e,t,n,r){let i=n.hookData.session_id,a;try{a=openView(t,e.cwd,n,{source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(i,{error:e}),e}return this.openFailures.delete(i),this.views.set(i,a),this.viewHolds.set(a,{entry:e,holders:0,retired:null}),this.log(`info`,`session view opened sid=${JSON.stringify(i)} by=${r} cwd=${e.cwd} views=${this.views.size}`),a}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}`))}retireSession(e){this.openFailures.delete(e);let t=this.views.get(e);t!==void 0&&this.retireView(t,`idle`)}subscriptions(){return{sources:Object.fromEntries([...this.views].map(([e,t])=>[e,subscriptionsOf(t)]))}}close(){if(this.closed)return;this.lifetime.abort(Error(`the render cache closed`)),this.walk?.(),this.walk=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 loadFromDisk(e,t,n,this.deps,r)}drop(e,t,n){t.watch?.held.handle.release(),this.entries.delete(e),this.due.delete(t),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,due:this.due.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=${mb(this.accountedBytes())}/${mb(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,{id:++this.storageHolds,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}`)}holdFolders(e){this.deps.storage.hold(this.holdOf(e).id,[...e.sources.values()])}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(),`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.deps.storage.release(t.id),this.log(`info`,configDisposeLine(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){this.due.delete(e);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`,pluginLoadLine(i.layers,i.state,i.ms)),i.kind===`built`&&(e.state=i.state,this.serve(i.state)),this.holdFolders(e.state),i.kind===`built`&&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.due.set(t,e);this.armWalk()}armWalk(){this.walk!==null||this.due.size===0||(this.walk=this.deps.clock.defer(()=>this.walkOne()))}walkOne(){this.walk=null;let e=null;for(let t of this.entries.values()){let n=this.due.get(t);n!==void 0&&(e=[t,n])}if(e===null)return;let[t,n]=e;try{this.reloadInto(t,n)}catch(e){this.log(`error`,`every-entry reload threw projectDir=${valueOf$1(t.projectDir)} cwd=${valueOf$1(t.cwd)} configFile=${valueOf$1(t.configFile??`-`)} cause=${valueOf$1(causeField(n))}: ${inspect(e)}`)}finally{this.armWalk()}}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.repos=t.repos;let n=watchTargetsFor(e,this.deps.locations),{targets:r,unresolved:i}=n,a=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${n.key}`,{watch:o,move:s}=this.deps.watchers.follow(e.watch?.held??null,{...n,key:a},t=>this.reloadInto(e,{kind:`config-watch`,heard:t}));if(e.watch={derived:{...n,key:a},held:o},s!==`kept`){this.log(`info`,`config watch bound projectDir=${e.projectDir} cwd=${e.cwd} dirs=${r.dirs.map(e=>e.path).join(`,`)}`);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)}};function buildDebugSnapshot(e,t){switch(e){case`vars`:return{what:e,vars:introspectVars(t)};case`segments`:return{what:e,segments:introspectSegments(t)};case`config`:return{what:e,config:introspectConfig(t)}}}function introspectVars(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=buildSourceKindIndex(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=valueOf(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:ageFromNode(r.lastUpdatedMs(),t.clock)})}return o}function valueOf(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 ageFromNode(e,t){return e===null?null:Math.max(0,t.now()-e)}function buildSourceKindIndex(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,sourceKindOf(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}`,sourceKindOf(i));return t}function sourceKindOf(e){return e.kind}function introspectSegments(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=orderedSegmentNames(n),o=placementsBySegment(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:extractReferencedVars(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function placementsBySegment(e){let t=new Map;for(let n of presetNames(e.presets))for(let r of walkNodes(presetRoot(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=placementId(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function orderedSegmentNames(e){let t=[],n=new Set;for(let r of walkNodes(rootNode(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 extractReferencedVars(e,t,n){let r=new Set([...templateReads(e,t).keys()].flatMap(e=>variableRead(e,n)));return Array.from(r).sort()}function introspectConfig(e){return e===null?null:e.config}const DEBUG_RENDER_OPTS={endcaps:floorOf(`endcaps`),colorCompatibility:floorOf(`colorCompatibility`),wrap:floorOf(`autoWrap`),padding:floorOf(`padding`),width:1/0},EMPTY_RENDER_MAP=new Map;function serializeSegmentCells(e,t){let n=new Map;for(let[r,i]of e)n.set(r,renderStripCells(i,{...DEBUG_RENDER_OPTS,colorCompatibility:t}));return n}function rendererOf(e){function t(t){return t.kind===`event`?e.event(t):e.adapter(t)}return{answer:t}}const DAEMON_WIDE=`journals`,GATHERS=`gathers`;var JournalTurns=class{queue=new KeyedSerialQueue;sessions=new KeyedSerialQueue;gathers=new KeyedSerialQueue;open=!0;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(DAEMON_WIDE,async()=>{await this.deps.changesLanded(),this.queued--;let a=this.deps.monotonic();t(spanMs(i,a)),this.holder={verb:e,since:a};try{if(this.refuseClosed(e),await n())throw new ClickAbandoned(e);return this.refuseClosed(e),await r({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(elapsedMs(this.deps,c)),this.refuseClosed(e),await i())throw new ClickAbandoned(e);this.refuseClosed(e);let t=this.deps.monotonic(),l=await o();a(elapsedMs(this.deps,t));let u=await i();return this.take(e,{waited:r,gone:async()=>!u&&await 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:elapsedMs(this.deps,e.since),queued:t,gathers:this.gathersInFlight}}close(){this.open=!1}refuseClosed(e){if(!this.open)throw new DaemonClosing(e)}},ConfigWrites=class{open=new Map;landing=null;waiting=[];closed=!1;answers=[];constructor(e,t){this.mint=e,this.disk=t}read(e){let t=this.open.get(e);return t===void 0?this.disk(e):t.after}land(e,t,n){let r=this.open.get(e);this.open.set(e,{before:r===void 0?t:r.before,after:n})}answer(e,t){this.answers.push({dir:e,answer:t})}seal(e,t,n){let r=this.answers;if(this.answers=[],this.closed)return this.open.clear();let i=[...this.open].flatMap(([e,{before:t,after:n}])=>{let r=diffChanges(t,n);return r.length===0?[]:[{path:e,list:r}]}),a=i.map(({path:e})=>e);if(this.open.clear(),i.length===0&&r.length===0)return n(e);if(t===null)throw Error(`a click with no session wrote ${[...a,...r.map(e=>`the answer for ${e.dir}`)].join(`, `)}`);let o=[...i.map(({path:e,list:n})=>({kind:`change`,id:this.mint(),session:t,target:{kind:`layer`,path:e},changes:n})),...r.map(({dir:e,answer:n})=>({kind:`approve-repo`,id:this.mint(),session:t,dir:e,answer:n}))];this.landing={of:{session:t,files:a,answered:r.length>0,consequence:n},owed:new Set(o.map(e=>e.id)),missed:null},e.push(...o)}settled(e,t){let n=this.landing;if(!(n===null||!n.owed.delete(e))){if(t.kind!==`ok`&&(n.missed??=t),n.owed.size>0)return`owed`;this.landing=null;for(let e of this.waiting.splice(0))e();return{...n.of,outcome:n.missed??{kind:`ok`}}}}close(){this.closed=!0}landed(){return this.landing===null?Promise.resolve():new Promise(e=>this.waiting.push(e))}};function mainRenderer(e,t){let n=new Map,r={sources:{},tmuxStatus:[]},i=async(t,r,i,a)=>{switch(t.kind){case`start`:for(let{context:n,worldState:a}of t.sessions)configureSession(e,n,a,r,i);return;case`config`:configureSession(e,t.context,t.worldState,r,i);return;case`request`:{let{frame:o,delivered:s}=await answerRequest(e,t.context,r,t.waitMs,{following:new Set(t.following),feeds:t.feeds,idleSince:t.idleSince},i,a),c=e.mint();n.set(c,s),a.push({kind:`present`,id:c,session:t.context.hookData.session_id,surface:`statusline`,request:t.id,frame:o});return}case`world-state`:e.worldStates.take(t.worldState);return;case`retire`:retireSession(e,t.session);return;case`effect-done`:{if(e.verbs.changeDone(t.of,t.outcome,a)||e.acts.done(t.of,t.session,t.outcome))return;let r=n.get(t.of);if(r===void 0)throw Error(`effect-done for effect ${t.of}, which is no present, change or act on its way`);n.delete(t.of),t.outcome.kind===`ok`&&r();return}case`click`:await clickTurn(e,t,i,a);return;case`menu-idle`:await e.verbs.closeIdle(t.session,t.latest,{...t.idle,confirm:()=>e.menuIdle.confirmClose(t.session,t.idle.firedAt)},a);return}};return rendererOf({adapter:async e=>{try{return{kind:`replied`,reply:t(e.push,e.at)}}catch(e){return{kind:`threw`,failure:failureOf(e)}}},event:async t=>{let n=[],a=e.clock.monotonic(),o=[];return{...await i(t.event,t.at,n,o).finally(()=>{let{sources:t}=e.renderCache.subscriptions();r={sources:t,tmuxStatus:Object.keys(t).filter(t=>viewLanes(e,t)?.tmuxStatus===!0)}}).then(()=>({kind:`answered`}),e=>({kind:`threw`,failure:failureOf(e)})),effects:o,record:n,subscriptions:r,turnMs:elapsedMs(e.clock,a)}}})}function loadMainRenderer(e){let t=new SessionState(e.storage.session),n=e.storage.history.load();return{start:r=>startOver(e,t,n,r)}}function startOver(e,t,n,r){let{clock:i,now:a,gates:o,linkSigner:s}=e,{log:c}=r,l=new SettingsHistory(t,c,e.storage.history,n),u=0,d=()=>++u,f=new ConfigWrites(d,readConfigText),p=(e,n)=>holdClickError(t,e,n,a()),m=new ActsOnTheirWay(d,p),h=new LaneActs({ask:(e,t)=>m.ask(e,t),refused:p,log:c}),g=new JournalTurns({monotonic:()=>i.monotonic(),changesLanded:()=>f.landed()}),_=new NavigationHistory,v=new EffectSessions,y=new RenderWarningRecords,b=new UpdateGate(o),x=new WorldStates(e=>b.took(e.daemon.update.newer)),S=new Watches(r.watches),C=new RenderCache({clock:i,stateDir:e.stateDir,locations:e.locations,env:e.env,sessionState:t,watchers:S,log:c,storage:r.storage,signer:s,gates:o,source:sessionSource({sessionState:t,worldStates:x,home:e.home,history:e=>l.depth(e),navigation:(e,n)=>_.depth(e,t,o.state.gateFor(n))})},{budgetBytes:()=>renderCacheBudget(e.memoryLimitBytes),observers:{onReload:(e,t,n,i)=>{c(`info`,configLoadedLine(e,n,i));for(let e of t)r.wake(e,`reload`)},onViewChanged:e=>r.wake(e,`data`)}}),w={...r,clock:i,linkSigner:s,sessionState:t,renderCache:C,worldStates:x,renderWarnings:y,effectSessions:v,laneActs:h},T=e=>C.reload(e.projectDir,e.cwd,e.target.path,{kind:`write`}),{install:E,...D}=r.doctor,O={gates:o,sessionState:t,stateDir:e.stateDir,locations:e.locations,journalTurns:g,configWrites:f,clickLanded:e=>r.menuIdle.clicked(e,a()),log:c,acts:m,now:a,doctor:{...D,loadConfig:e=>{let t=[e.projectDir,e.cwd,e.target.path];C.reload(...t,{kind:`doctor`});let n=C.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}},home:e.home,managedSettingsDir:claudeManagedSettingsDirIn(e.env)},installFacts:E,doctorStores:e.storage.doctor,clients:r.renderSightings,bundle:e.bundle,serving:r.serving,history:l,navigation:_,configFor:e=>C.getOrCreate(e.projectDir,e.cwd,e.target.path).state.config,reloadConfig:T,sourcesFor:e=>C.getOrCreate(e.projectDir,e.cwd,e.target.path).state.sources,links:s,lanes:{of:(e,t,n)=>lanesAt(w,e,t,n),clicked:(e,t,n,r,i)=>h.clicked(e,t,n,r,i)},diagnosticCopy:(e,t,n)=>C.drawnCopy(e,t,n)},k=new Map,A=e=>{if(k.has(e))throw Error(`pin of session ${e}, whose feed is pinned`);let n=C.pin(e),i=(0,import_dist$1.reaction)(()=>t.revision(e),()=>r.wake(e,`state`));k.set(e,()=>{i(),C.stopDrawing(e,`feed`),n()})},j=e=>{let t=k.get(e);if(t===void 0)throw Error(`unpin of session ${e}, whose feed is not pinned`);k.delete(e),t()},M=(e,n)=>{switch(e.kind){case`frame`:return{kind:`frame`,frame:renderFrame(w,e.session,e.fps,n,{following:new Set(e.following),feeds:e.feeds,idleSince:e.idleSince})};case`lanes`:return{kind:`lanes`,lanes:viewLanes(w,e.session)};case`pin`:return A(e.session),{kind:`pin`};case`unpin`:return j(e.session),{kind:`unpin`};case`stats`:return{kind:`stats`,stats:{renderCache:C.stats,effectCache:v.getStats(),sessionState:{sessions:t.size(),observers:t.observers(),revision:t.latestRevision()},journalTurns:g.getStats()}};case`debug`:return{kind:`debug`,snapshot:debugOf(C.latestView(),e.what)};case`watch`:return S.pushed(e.id,e.heard,e.deaf),{kind:`watch`};case`reload-every`:return C.reloadEvery({kind:`events-resumed`,since:e.since}),{kind:`reload-every`};case`reload-config`:return T(e.origin),{kind:`reload-config`};case`close-journal`:return g.close(),f.close(),{kind:`close-journal`};case`close-views`:return C.close(),{kind:`close-views`};case`close-session-state`:return t.close(),{kind:`close-session-state`}}};return mainRenderer({...w,verbs:verbsOver(O,r.clicks),mint:d,acts:m},M)}function debugOf(e,t){return buildDebugSnapshot(t,e===null?null:{store:e.store,registry:e.registry,config:e.state.config,compiled:e.state.compiled,lastRenderBySegment:t===`segments`?serializeSegmentCells(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??floorOf(`colorCompatibility`)):EMPTY_RENDER_MAP})}function bootEnv(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>t===void 0?[]:[[e,t]]))}const REACH_KINDS={wake:`notice`,log:`notice`,doctor:{probeTmux:`call`,remoteLogin:`call`,fontInUse:`call`,daemons:`call`,forge:`call`,transcript:`call`,install:`call`},menuIdle:{clicked:`notice`,clickArrived:`notice`,clickSettled:`notice`,observe:`notice`,confirmClose:`call`},clicks:{gone:`call`},serving:`call`,renderSightings:{ofSession:`call`},eventAnswered:`notice`,watches:{watch:`notice`,unwatch:`notice`},storage:{hold:`notice`,release:`notice`}};function reachesOf(e,t=``){return Object.entries(e).flatMap(([e,n])=>typeof n==`string`?[[`${t}${e}`,n]]:reachesOf(n,`${t}${e}.`))}const REACHES=reachesOf(REACH_KINDS);function reachAt(e,t){let n=t.split(`.`).reduce((e,t)=>e?.[t],e);if(typeof n!=`function`)throw Error(`the renderer reached ${t}, which the host has not`);return n}function lineSplitter(e){let t=``;return{push:n=>{let r=0,i=n.indexOf(`
|
|
226
|
+
Single-row example: root: { h: ["seg1", "seg2"] }`,line:findKeyLine(e.source,[`layout`])}),t.root!==void 0&&(a.root=validateRootFragment(e,`root`,t.root)),t.insert!==void 0&&(a.insert=validateInsert(e,t.insert,i)),t.actions!==void 0&&(a.actions=validateActions(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:findKeyLine(e.source,[`looks`])}),t.styles!==void 0&&(a.styles=validateStyles(e,t.styles)),t.themeDefaults!==void 0&&(a.themeDefaults=validateThemeDefaults(e,t.themeDefaults)),t.presets!==void 0&&(a.presets=validatePresets(e,t.presets)),t.editGlobals!==void 0&&(a.editGlobals=validateEditGlobals(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(a.helpers=validateHelpers(e,t.helpers)),t.plugins!==void 0&&(a.plugins=validatePluginRefs(e,t.plugins)),synthesizeGroupDecls(e,a),checkMenuDecls(e,a),synthesizeEditModeToggle(e,a),reservedNamespaceCollisions(e,a,SETTINGS_NS,`the global settings menu`),pluginScopeCollisions(e,a,n),a}const TOP_LEVEL_KEYS=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`insert`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function validatePluginRefs(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 ${describeType(t)}`,line:findKeyLine(e.source,[`plugins`])})}const BUNDLED_THEME_DEFAULTS={},COMMAND_TRAY=commandTray(`commands.`),AUTOCOMPACT=autocompactControl(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),GIT_INIT=confirmStep(`gitInit`,{arm:`init`,confirm:`init ✓ confirm`},[{action:`gitInit.run`,when:`true`}]),DIR_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 }}`,GIT_QUIET_FG=`{{ ${QUIET_TEXT} }}`,EFFORT_BUBBLE_CONTRAST=1.08,PERCENT={min:0,max:100,step:5},QUOTA_SETTINGS={warnAt:{label:`warning at %`,domain:PERCENT,default:50},errorAt:{label:`error at %`,domain:{...PERCENT,atLeast:`warnAt`},default:80}};function budgetSettings(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:PERCENT,default:80}}}const RAW_DEFAULT_DSL_CONFIG={globals:{palette:`tokyo-night`},variables:{...COMMAND_TRAY.variables,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:`⊫`},...GIT_INIT.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_TEMPLATE,fg:GIT_QUIET_FG},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 ${GIT_INIT.armed} }}{{ if ne .git.branch "" }} {{ end }}${GIT_INIT.template}{{ end }}`,fg:GIT_QUIET_FG,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:quickActions(``).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:COMMAND_TRAY.template,when:COMMAND_TRAY.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:budgetSettings(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:budgetSettings(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:QUOTA_SETTINGS,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:QUOTA_SETTINGS,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) ${TEXT_MIN_CONTRAST} }}`,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:AUTOCOMPACT.template,bg:AUTOCOMPACT.bg,when:AUTOCOMPACT.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:{...quickActions(``).actions,...COMMAND_TRAY.actions,copyDir:{copy:`{{ .current_dir }}`},"gitInit.run":{run:[`git`,`-C`,`{{ .current_dir }}`,`init`]},...GIT_INIT.actions,gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...AUTOCOMPACT.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:BUNDLED_THEME_DEFAULTS,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) ${EFFORT_BUBBLE_CONTRAST} }}{{ if eq \$ord 5 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${TEXT_MIN_CONTRAST} }}{{ \$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 (${QUIET_TEXT}) 2 (readableOn (color "accent") (bgOf) ${TEXT_MIN_CONTRAST})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${TEXT_MIN_CONTRAST}) .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:formatTokenCount(`.`),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 .)) }}`}},AUTHORED_PALETTE_NAMES=new Set([RAW_DEFAULT_DSL_CONFIG.globals.palette,...Object.keys(RAW_DEFAULT_DSL_CONFIG.themeDefaults),...Object.values(RAW_DEFAULT_DSL_CONFIG.segments).map(e=>e.palette)].filter(e=>e!==void 0)),DEFAULT_DSL_CONFIG=mergeWithDefault(parseDslConfig(`<default>`,JSON.stringify(RAW_DEFAULT_DSL_CONFIG),AUTHORED_PALETTE_NAMES),RAW_DEFAULT_DSL_CONFIG),BUNDLED_PRESETS=presetNames(DEFAULT_DSL_CONFIG.presets);function isBundledPreset(e){return BUNDLED_PRESETS.includes(e)}function usageOver(e,t){return e.kind===`ok`?ok$1({cost:t.cost?.total_cost_usd??e.value.calculatedCost,tokens:e.value.tokens}):e}function resumeCommand(e,t,n){return claudeCommandLine({dir:e.project_dir,env:n===void 0?[]:[[CLAUDE_CONFIG_DIR_ENV,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function renderOptionsOf(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function effectiveInputs(e){return{...Object.fromEntries(VALUED_FIELDS.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:isBundledPreset(e.preset)}}}function prFactOf(e){if(isPending(e))return`pending`;let{prState:t,prError:n,prEarlier:r}=e??{};return isPending(t)?`pending`:t===void 0?n===void 0?r===void 0?`-`:`earlier-${String(r)}`:`failed`:t}const MIN_BURN_SECONDS=60,MIN_SPEED_SAMPLE_MS=50;function projectCostPerHour(e,t){if(!(t<MIN_BURN_SECONDS))return e*3600/t}function projectTokensPerSecond(e,t,n,r){let i=r-t;if(i<MIN_SPEED_SAMPLE_MS)return;let a=n-e;if(!(a<=0))return a*1e3/i}function turnIntervals(e){return e.slice(1).map((t,n)=>[e[n],t]).filter(([e,t])=>e.turnOpen&&t.atMs-e.atMs>=MIN_SPEED_SAMPLE_MS)}function openTurn(e){let t=e.length;for(;t>0&&e[t-1].turnOpen;)t--;return e.slice(t)}function projectSpeed(e){let t=turnIntervals(openTurn(e.samples));for(let e=t.length-1;e>=0;e--){let n=intervalRates(t[e]);if(n!==void 0)return n}}function intervalRates([e,t]){let n=projectTokensPerSecond(e.input,e.atMs,t.input,t.atMs),r=projectTokensPerSecond(e.output,e.atMs,t.output,t.atMs),i=projectTokensPerSecond(e.total,e.atMs,t.total,t.atMs);if(!(n===void 0&&r===void 0&&i===void 0))return{...n!==void 0&&{input:n},...r!==void 0&&{output:r},...i!==void 0&&{total:i}}}function projectSpeedHistory(e){let t=turnIntervals(e.samples).map(([e,t])=>projectTokensPerSecond(e.total,e.atMs,t.total,t.atMs)??0);if(t.length!==0)return t.join(`,`)}function renderWidth(e){return applyClaudeCodeReserve(e.termCols??120)}function awaitsReading({builtins:e,sources:t,runs:n},r){return[...AWAITED_BUILTINS.map(t=>e[t]),...Object.values(t),...[...r].map(e=>(n[e.digest]??UNREAD_RUN).reading)].some(awaitedReading)}const AWAITED={session:!0,today:!1,speed:!0,context:!0,metrics:!0,activity:!0,cache:!0,autocompact:!0,git:!0,pr:!1,tmux:!0,hostName:!0,hostUser:!0},AWAITED_BUILTINS=Object.keys(AWAITED).filter(e=>AWAITED[e]),awaitedReading=e=>e.kind===`pending`&&e.why===`unread`;async function settleWorld(e,t,n){try{await(0,import_dist$1.when)(()=>!awaitsReading(e(),t()),{signal:n})}catch(e){if(!n.aborted)throw e}}function firstPending(...e){let t=e.find(e=>e.kind===`pending`);return t?.kind===`pending`?pendingOf(t.why):void 0}const unstamped=e=>{switch(e.kind){case`pending`:return e;case`absent`:return ABSENT$2;case`ok`:return ok$1(e.value);case`failed`:return failed$2(e.reason,e.failedAt)}};function composePayload(e,t,n){let{hookData:r,hints:i}=t,a=r.session_id,{effective:o,configFacts:s}=n,{configPath:c,...l}=s,u=e.builtins,d={usage:usageOver(unstamped(u.session),r),context:contextOver(unstamped(u.context),r),metrics:metricsOver(unstamped(u.metrics),r),activity:unstamped(u.activity),cache:unstamped(u.cache),speed:unstamped(u.speed),autoCompact:unstamped(u.autocompact),git:unstamped(u.git),pr:unstamped(u.pr),tmux:unstamped(u.tmux),hostName:unstamped(u.hostName),hostUser:unstamped(u.hostUser)},f=(e,t)=>{switch(e.kind){case`pending`:return pendingOf(e.why);case`failed`:case`absent`:return;case`ok`:return t(e.value)}},p=e=>e.kind===`ok`?e.value:void 0,m=i.tmux??null,h=d.git.kind===`pending`?pendingOf(d.git.why):d.git.kind===`ok`?projectGitInfo(d.git.value,d.pr,pendingOf):void 0,g=d.tmux.kind===`pending`?pendingOf(d.tmux.why):p(d.tmux)?.session,_=d.hostName.kind===`pending`?pendingOf(d.hostName.why):p(d.hostName),v=d.hostUser.kind===`pending`?pendingOf(d.hostUser.why):p(d.hostUser),y=firstPending(d.context)??projectAutoCompact(d.autoCompact,p(d.context)?.maxTokens),b=r.rate_limits?.five_hour,x=r.rate_limits?.seven_day,S=firstPending(d.usage,d.metrics)??burnOf(p(d.usage)?.cost,p(d.metrics)?.sessionDuration),C=f(d.speed,speedPayloadOf),w=f(d.usage,e=>pickNonNull({cost:e.cost,tokens:e.tokens})),T=f(d.metrics,e=>pickNonNull({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),E=f(d.activity,projectActivity),D=f(d.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),O=f(d.cache,e=>({expiresAt:e})),k=posixify(t.home),A=r.workspace?{...r.workspace,current_dir:posixify(r.workspace.current_dir)??``,project_dir:posixify(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>posixify(e)??e)}:r.workspace;return{...r,...A!==void 0&&{workspace:A},...k!==void 0&&{home:k},...h!==void 0&&{git:h},...r.location!==void 0&&{location:{...r.location,main:posixify(r.location.main)??``}},...m!==null&&{tmux:{pane:m.pane,...g!==void 0&&{session:g}}},host:{..._!==void 0&&{name:_},...v!==void 0&&{user:v},...i.ssh!==void 0&&{ssh:i.ssh}},...effectiveInputs(o),history:n.history,navigation:{back:n.back},term:{cols:renderWidth(i)},...l,...c!==null&&{configPath:c},resumeCommand:resumeCommand(A,a,i.claudeConfigDir),...w!==void 0&&{session:w},...S!==void 0&&{burn:S},...C!==void 0&&{speed:C},...b!==void 0&&{block:{nativeUtilization:b.used_percentage,resetsAt:b.resets_at}},...x!==void 0&&{weekly:{percentage:x.used_percentage,resetsAt:x.resets_at}},...O!==void 0&&{cache:O},...D!==void 0&&{context:D},...T!==void 0&&{metrics:T},...E!==void 0&&{activity:E},...y!==void 0&&{autocompact:y},...projectSources(n.sources,t=>{let n=unstamped(sourceFactOf(e,t));return n.kind===`pending`?pendingOf(n.why):n})}}const sourceFactOf=(e,t)=>e.sources[t]??pendingOf(`unread`);function sourcesFactOf(e,t,n){let r=[...e.map(e=>[e,sourceFactOf(n,e)]),...[...t].map(([e,t])=>[e,t.kind===`ok`?(n.runs[t.value.digest]??UNREAD_RUN).reading:t])];return{sources:String(r.length),sourcesPending:r.flatMap(([e,t])=>t.kind===`pending`?[`${e}:${t.why}`]:[]).join(`,`)||`-`,sourcesFailed:r.flatMap(([e,t])=>t.kind===`failed`?[e]:[]).join(`,`)||`-`}}function projectSources(e,t){let n=Object.fromEntries(PLUGIN_SCOPES.map(e=>[e,{}]));for(let r of e){let e=r.split(`.`),i=e.pop(),a=e.reduce((e,t)=>e[t]??={},n);a[i]=t(r)}return n}function burnOf(e,t){let n=e!=null&&t!=null?projectCostPerHour(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function speedPayloadOf(e){let t=projectSpeed(e),n=projectSpeedHistory(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function instantFacts(e,t){return{today:todayOf(e.today,t)}}function todayOf(e,t){if(e.kind===`pending`)return pendingOf(e.why);if(e.kind!==`ok`)return;let n=projectToday(e.value,t);return n.kind===`ok`?{cost:n.value.cost,tokens:n.value.tokens}:void 0}function projectAutoCompact(e,t){switch(e.kind){case`pending`:return pendingOf(e.why);case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return autoCompactControls(e.value,t)}}function projectActivity(e){let t=e.todos.findIndex(e=>e.active),n=e.todos.length===0?void 0:{total:e.todos.length,completed:e.todos.filter(e=>e.done).length,...t>=0&&{position:t+1,active:e.todos[t].text}},r=encodeTally(e.running),i=encodeTally(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}};if(!(e.command===null&&n===void 0&&a===void 0))return{...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function encodeTally(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function pickNonNull(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function posixify(e){return e===void 0||e.length===0||path.sep!==`\\`?e:e.replace(/\\/g,`/`)}function projectGitInfo(e,t,n){let r=e=>e.kind===`ok`?e.value:void 0,i=r(e.aheadBehind),a=r(e.sha),o=r(e.operation),s=r(e.committedAt),c=r(e.stashCount),l=r(e.upstream),u=r(trackingOf(e.upstream,e.aheadBehind)),d=r(e.repoName),f=r(e.repoUrl),p=t.kind===`pending`?t:prOfHead(t,e.head),m={};switch(p.kind){case`pending`:{let e=n(p.why);m={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:m={prNumber:p.value.number,prState:p.value.state,prUrl:p.value.url};break;case`failed`:m={prError:p.reason};break;case`earlier`:m={prEarlier:p.value.state};break;case`absent`:break}return{branch:e.branch,status:e.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},staged:e.workingTree.staged,unstaged:e.workingTree.unstaged,untracked:e.workingTree.untracked,conflicts:e.workingTree.conflicts,...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{committedAt:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{tracking:u},...d!==void 0&&{repoName:d},...f!==void 0&&{repoUrl:f},...m}}const KEY=`click.error`,CLICK_ERROR_HOLD_S=5;function holdClickError(e,t,n,r){let i=joinedEvent(lastClickError(e,t),n,r);e.set(t,KEY,JSON.stringify(i))}function answeredClickError(e,t,n){let r=lastClickError(e,t);r===null||!answeredBy(r,n)||e.set(t,KEY,JSON.stringify({...r,answered:!0}))}function lastClickError(e,t){let n=e.get(t,KEY);return n===null?null:recordOf(n)}function clickErrorAt(e,t,n,r){let i=lastClickError(e,t);if(i===null)return{kind:`none`};let a=eventHoldAt(i,5,n,r);return a===`over`?{kind:a}:{kind:a,error:i}}function recordOf(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let{text:n,at:r,answered:i}=t;return typeof n==`string`&&typeof r==`number`&&(i===void 0||typeof i==`boolean`)?{text:n,at:r,answered:i===!0}:null}function handedOffTo(e,t){return LANE_NAMES.filter(n=>e[n]&&LANES[n].handsOff&&t.has(n))}const HANDOFF_BUTTON=`[⟲ claude]`;function laneHandoff(e,t,n){return{severity:HANDOFF_SEVERITY,lines:[[diagnosticSpan(HANDOFF_BUTTON,effectsUrl(t.filter(e=>e!==`project`).map(t=>({verb:VERB_RESET_CONFIG,args:[e,t,...n.map(e=>LANES[e].switch.setting)]}))))]]}}function renderFrame(e,t,n,r,i){let{clock:a}=e,o=a.monotonic(),s=[];try{try{var c=_usingCtx();let a=c.u(setUpFrame(e,t,r,s));if(a===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=drawRender(e,a,{by:`feed`,fps:n},i.feeds,i.idleSince),p=signingFrames(e.linkSigner),m=p(o.body),h=RENDER_ANSWERS.ansi(m),g=statuslineOf(t,a.state.writable,o,handedOffTo(f,i.following));return d(),{bar:m,resp:h,statusline:g===o.body?h:RENDER_ANSWERS.ansi(p(g)),evaluated:l,cellBreaks:u,lanes:f,failure:null}}catch(e){c.e=e}finally{c.d()}}catch(n){let r=renderFailure(failureOf(n)),{level:i,line:c}=requestEvent(`render`,s,r,elapsedMs(a,o)),l=failedWith(r.message);return{bar:renderFailedFrame(l.error),resp:l,statusline:l,evaluated:0,cellBreaks:0,lanes:viewLanes(e,t),failure:{level:i,line:`frame ${c}`}}}}function sessionGlobals$1(e,t,n){let{sessionState:r}=e;return resolveEffectiveGlobals(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function viewLanes(e,t){try{var n=_usingCtx();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:laneSwitches(i.view.source.effective(),inTmux(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function lanesAt(e,t,n,r){try{var i=_usingCtx();let{renderCache:a}=e;return laneSwitches(sessionGlobals$1(e,n,i.u(a.hold(t.projectDir,t.cwd,t.target.path)).state),r===null||inTmux(r.hints.tmux))}catch(e){i.e=e}finally{i.d()}}function contextFacts(e,t,n){noteFacts(n,{sid:e.hookData.session_id,at:t.toFixed(3)});let{hints:r}=e;noteFacts(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:refusedHints(e,r).map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits})}const hintsErrorOf=e=>refusedHintsError(refusedHints(e,e.hints));function configureSession(e,t,n,r,i){contextFacts(t,r,i),noteFacts(i,{encoding:t.encoding}),(0,import_dist$1.runInAction)(()=>{recordRequest(e,t),e.worldStates.take(n),holdSessionAt(e,t)[Symbol.dispose]()})}function retireSession(e,t){(0,import_dist$1.runInAction)(()=>{e.worldStates.drop(t),e.renderCache.retireSession(t)})}function holdSessionAt(e,t){let{projectDir:n,cwd:r,target:i}=t.requested;return e.renderCache.holdSession(n,r,i.path,t)}function setUpRender(e,t,n,r){let i=hintsErrorOf(t);return setUpDraw(e,holdSessionAt(e,t),t,i,n,r)}function setUpFrame(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{contextFacts(o,n,r),s=hintsErrorOf(o)}catch(e){throw a[Symbol.dispose](),e}return setUpDraw(e,a,o,s,n,r)}function setUpDraw(e,t,n,r,i,a){try{let{entry:e,state:o,view:s}=t;return{req:n,at:i,facts:a,sessionId:n.hookData.session_id,entry:e,state:o,view:s,hintsError:r,[Symbol.dispose]:()=>t[Symbol.dispose]()}}catch(e){throw t[Symbol.dispose](),e}}function drawRender(e,t,n,r,i){let{sessionState:a,renderCache:o,linkSigner:s,renderWarnings:c,effectSessions:l,menuIdle:u}=e,{req:d,at:f,facts:p,sessionId:m,entry:h,state:g,view:_,hintsError:v}=t,y=_.source.payload(),b=_.source.effective(),x=_.source.failure(),S=_.source.facts(),C=laneSwitches(b,y.tmux!==void 0);noteFacts(p,{lanes:LANE_NAMES.filter(e=>C[e]).join(`,`)||`-`});let w=_.source.hints(),T=y.term.cols;noteFacts(p,{width:String(T)});let E=clickErrorAt(a,m,f,n.by),D=E.kind===`held`||E.kind===`owed`?E.error:null,{update:O}=S.daemon,k=updateNotice(O.newer.kind===`ok`?O.newer.value:null,O.act,{sessionId:m,dismissed:a.get(m,UPDATE_DISMISSED_KEY),enabled:b.updateNotice}),A=repoQuestions(h.repos,m,s),j=(e,t)=>({about:e,text:t,copy:t}),M=e=>j(e??``,e),N=[M(refusedArgsError(d.refusedArgs)),M(v),j(`load`,h.lastError),j(`update-act`,O.actsError),...g.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),M(D?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),F=h.watch===null?null:watchFault(`config watch`,h.watch,null),{daemon:ee}=S,te=launcherWarningsAt(ee.launcher,f,n.by),ne=te.find(e=>e.kind===`launch-pipes`),I=[daemonEventAt(`renderer-ended`,ee.rendererEnded,f,n.by),daemonEventAt(`act-failed`,ee.actFailed,f,n.by)].flatMap(e=>e===void 0?[]:[e]),re=[ne?.event,...I.map(e=>e.event)].flatMap(e=>e===void 0?[]:[e]),ie=[...ee.fileEvents,...te,...I,...F===null?[]:[{kind:`config-watch`,message:F}],...h.lastWarning===null?[]:[{kind:`load`,message:h.lastWarning}],...x===null?[]:[{kind:`facts`,message:`the bar is drawn from the last facts that were read; the next could not be stamped: ${x}`}]],ae={config:g.config},oe=collectDiagnostics(m,n.by,N,[...k.offer,...A],[...k.failure,...ie.map(e=>({about:e.kind,text:e.message,copy:e.message})),...c.ofSession(m,n.by,ae).map(e=>({about:`${e.kind}\0${e.message}`,text:e.message,copy:e.message}))]),L={diagnostics:diagnosticsProjection(oe),drawing:n,feeds:r,...instantFacts(S.builtins,f)},R=isPending(y.metrics)?void 0:y.metrics;noteFacts(p,sourcesFactOf([..._.state.sources.keys()],_.registry.runSources(),S)),noteFacts(p,{prompts:String(R?.messageCount??`-`),nonPrompts:String(R?.nonPrompts??`-`),pr:prFactOf(y.git),feeds:feedsFact(L.feeds)});let se=[],ce=renderOptionsOf(b,T),le=l.of(m),{frame:ue,evaluated:z,cellBreaks:de,rules:fe}=drawDsl(g.config,g.compiled,_.store,_.registry,L,f,ce,{perSegmentSink:_.lastRenderCellsBySegment,onRenderWarning:e=>se.push(e)},{...b,effects:le,idleSince:i??void 0}),B=copyKeys(oe),V=new Map(oe.map((e,t)=>[B[t],e.copy])),H=()=>o.delivered(m,n.by,V);u.observe(m,f,ue.rows.some(e=>e.kind===`menu`),b.menuTimeout),noteFacts(p,{menuIdle:i===null?`-`:`${(f-i).toFixed(1)}s/${b.menuTimeout}s`});let pe=c.drawn(m,n.by,ae,se),me={width:T,rows:viewerRowCap(w.termRows,n.by===`feed`?LANE_NAMES.flatMap(e=>{let t=LANES[e].rows;return C[e]&&t!==null?[t]:[]}):[]),colorCompatibility:ue.depth},U=viewedIndex(a.get(m,DIAGNOSTICS_VIEWING),oe),he=U===null?ue:standIn$1(ue,viewerRows(oe,U,m,n.by,me)),W=le.lastFrame(),ge=W.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,G=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,K=e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`file-events`:return`${e.kind}:${e.state}`;case`load`:case`facts`:case`config-watch`:case`lifeline`:case`launch-pipes`:case`renderer-ended`:case`act-failed`:case`when`:return e.kind}},q=[...k.failure.map(()=>`update-failed`),...[...ie,...se].map(K)].join(`,`)||`-`;return noteFacts(p,{effect:W.effect,effectT:W.t.toFixed(3),speed:`${W.speed}x`,effectRows:`${W.made}made/${W.reused}reused`,effectOwn:ge,fadeBasis:W.basis,stateRev:String(W.revision),fades:G(W.fades),leaves:G(W.leaves),motion:he.motion,evaluated:String(z),cellBreaks:String(de),pending:he.pending.join(`,`)||`-`,rules:[...fe].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:N.length>0?`Y`:`N`,clickError:E.kind===`none`?`-`:E.kind,pipeEvent:ne?.hold??`-`,upd:String(k.offer.length),ask:String(A.length),warn:q,diag:String(oe.length),warnRecord:pe?`new`:`kept`,viewer:U===null?`-`:`${U.index}/${oe.length}p${U.page+1}`}),{drawn:{body:he,viewerOpen:U!==null,diagnostics:oe,geometry:me},evaluated:z,cellBreaks:de,clickShown:D,eventsShown:re,delivered:H,lanes:C}}function daemonEventAt(e,t,n,r){return t===null||eventHoldAt(t,60,n,r)===`over`?void 0:{kind:e,message:t.text,event:t}}function recordRequest(e,t){let{sessionState:n}=e,r=t.hookData.session_id,{client:i,...a}=t.hints,o=JSON.stringify(a);n.get(r,`client-hints`)!==o&&n.set(r,SESSION_CLIENT_HINTS_KEY,o);let s=encodeRenderOrigin(t.requested);n.get(r,`render-origin`)!==s&&n.set(r,SESSION_RENDER_ORIGIN_KEY,s)}async function answerRequest(e,t,n,r,i,a,o){try{var s=_usingCtx();let{clock:c,log:l}=e,u=c.monotonic(),d=s.u(setUpRender(e,t,n,a));e.laneActs.noted(t,laneSwitches(d.view.source.effective(),inTmux(t.hints.tmux)),o);let f=c.monotonic(),p=r-(f-u);noteFacts(a,{deadline:`${t.deadline.kind}:${Math.round(p)}ms`});let m=await waitWithin(t=>settleWorld(()=>e.worldStates.of(d.sessionId),()=>d.view.registry.namedRuns().values(),t),p,(e,t)=>l(`error`,`render wait failed after it ended ended=${t} sid=${JSON.stringify(d.sessionId)}: ${inspect(e)}`),c.after,e.renderCache.closing),h=c.monotonic();noteFacts(a,{waited:`${Math.round(h-f)}ms`,ended:m});let g=t.hookData.session_id,{drawn:_,clickShown:v,eventsShown:y,delivered:b,lanes:x}=drawRender(e,d,ANSWERING,i.feeds,i.idleSince),S=handedOffTo(x,i.following),C=roleOf(t.hints.client??null)===`statusline`,w=signingFrames(e.linkSigner)(C?statuslineOf(g,d.state.writable,_,S):_.body);return noteFacts(a,{handoff:(C?S:[]).join(`,`)||`-`,drew:`${elapsedMs(c,h)}ms`}),{frame:w,delivered:answerDelivered(e,g,b,v,y)}}catch(e){s.e=e}finally{s.d()}}function answerDelivered(e,t,n,r,i){return()=>{n(),r!==null&&answeredClickError(e.sessionState,t,r);for(let t of i)e.eventAnswered(t)}}function statuslineOf(e,t,n,r){let[i,...a]=r;return i===void 0||n.viewerOpen?n.body:standIn$1(n.body,handoffRows(laneHandoff(e,t,[i,...a]),n.diagnostics,e,n.geometry))}async function clickTurn({verbs:e,menuIdle:t},{verb:n,value:r,session:i,arrival:a,id:o,latest:s},c,l){let u=e.handler(n);if(u===void 0)throw new BadVerbArgs(`unknown click verb: ${n}`);let d=i?.ok?i.id:null;d!==null&&t.clickArrived(d);try{await u(r,{arrival:a,placeWaited:e=>noteFacts(c,{placeWait:`${e}ms`}),gatherTook:e=>noteFacts(c,{gather:`${e}ms`}),turnWaited:e=>noteFacts(c,{turnWait:`${e}ms`}),click:o,latest:s,effects:l})}finally{d!==null&&t.clickSettled(d)}}function spelled(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?BOOLEAN_TRUE:BOOLEAN_FALSE;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const SETTING_ROWS=Object.entries(SETTINGS),SETTING_KEYS=new Set(SETTING_PROJECTIONS.map(e=>e.sessionKey)),NOT_CUSTOMIZED=()=>!1;function sessionGlobals(e,t){return resolveEffectiveGlobals(e,e=>SETTING_KEYS.has(e)?t(e):null,NOT_CUSTOMIZED)}const SELECTORS=[`preset`,`theme`];function fileThrough(e,t,n){let r=new Set(SELECTORS.slice(0,n).map(e=>SETTINGS[e].sessionKey));return resolveEffectiveGlobals(e,e=>r.has(e)?t(e):null,NOT_CUSTOMIZED)}function baseOf(e,t){let n=Array.from({length:SELECTORS.length+1},(n,r)=>fileThrough(e,t,r));return e=>{let t=SELECTORS.indexOf(e);return n[t===-1?SELECTORS.length:t]}}function differing(e,t,n,r){return e.flatMap(([e,i])=>{let a=spelled(t,e);return a===null||a===spelled(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function sessionSettingValue(e,t,n){return spelled(sessionGlobals(e,t),n)}function settingDrafts(e,t){let n=sessionGlobals(e,t);return differing(SETTING_ROWS,n,baseOf(e,t),t=>landingKey(e,n.preset,t.configKey))}function landingKey(e,t,n){return n in(presetByName(e.presets,t).globals??{})?presetGlobalsKey(t,n):n}function durableLanding(e,t,n){let r=effectivePresetName(t(SETTINGS.preset.sessionKey),e.globals.preset,e.presets),i=parsePersistTarget(n);return{key:i?.scope===`globals`?landingKey(e,r,i.field):n,globals:presetGlobals(e,r)}}function placementDrafts(e,t){let{preset:n}=sessionGlobals(e,t);return slotsOf(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:parseSettingSpelling(a,s);return c===void 0||settingSpelling(c)===settingSpelling(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function placementPickProblems(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return presetNames(e.presets).flatMap(n=>{let i=slotsOf(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 settingOrderProblems(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:parseSettingSpelling(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const SLOTS=new WeakMap;function slotsOf(e,t){let n=SLOTS.get(e)??new Map;SLOTS.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...walkNodes(presetRoot(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=settingsOf(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 presetSnapshot(e,t){let n=sessionGlobals(e,t);return{from:n.preset,globals:presetByName(e.presets,n.preset).globals??{},picks:differing(SETTING_ROWS.filter(([e])=>e!==`preset`),n,baseOf(e,t),e=>e.configKey),placements:placementDrafts(e,t)}}function themeOwnLook(e,t){return resolveEffectiveGlobals({...e,globals:{palette:t},presets:{}},()=>null,NOT_CUSTOMIZED)}function themeDefaultSave(e,t){let n=sessionGlobals(e,t),r=spelled(n,`theme`);if(r===null)return{kind:`rule`};let i=themeOwnLook(e,r),a=presetGlobals(e,n.preset),o=Object.fromEntries(THEME_DEFAULT_FIELDS.map(e=>[e,spelled(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:THEME_DEFAULT_FIELDS.some(e=>o[e]!==spelled(i,e))}}function resetLayers(e){return{sessionKeys:SETTING_PROJECTIONS.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...isPresetGlobalsField(e)?BUNDLED_PRESETS.map(t=>presetGlobalsKey(t,e)):[],...isThemeDefaultField(e)?listResolvablePaletteNames().map(t=>themeDefaultKey(t,e)):[]]}}function fileHeldSettings(e){return new Set(SETTING_PROJECTIONS.map(e=>e.configKey).filter(t=>resetLayers(t).fileKeys.some(t=>holds(e,filePath(t)))))}function settingCounts(e,t,n){let r=settingDrafts(e,n),i=new Set(r.map(e=>e.configKey)),a=perSetting(e=>i.has(SETTINGS[e].configKey)||t.has(SETTINGS[e].configKey)),o=themeDefaultSave(e,n);return{unsaved:r.length+placementDrafts(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function filePath(e){let t=parsePersistTarget(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return persistPath(t)}function holds(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&holds(e[n],r)}function stateKeySeed(e,t,n){let r=SESSION_KEY_TO_SETTING.get(n);if(r!==void 0)return sessionSettingValue(e,t,r);for(let[,t]of stateVarDecls(e))if(t.key===n)return t.default??null;return null}function configKeySeed(e,t){let n=numericGlobalsSeeds(e).get(t);return n===void 0?null:String(n)}const NO_NEST={inside:()=>[],defaultOf:()=>DISCLOSURE_CLOSED,menus:[]},idOf=e=>`${e.key}\0${e.member}`;function buildDisclosureNest(e){let t=new Map,n=n=>{let r=`${n.name}\0${placementId(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:hostedMenus(a,placementId(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(idOf(e))??new Map;n.set(idOf(t),t),o.set(idOf(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(idOf(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 presetNames(e.presets))d(presetRoot(e,t).node,[]);for(let t of Object.values(e.actions)){let e=disclosureOfAction(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(idOf(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(idOf(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(idOf(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const NESTS=new WeakMap;function disclosureNest(e){let t=NESTS.get(e);if(t!==void 0)return t;let n=buildDisclosureNest(e);return NESTS.set(e,n),n}function closeNested(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 openRoots(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 closingView(e,t,n){let r=(r,i,a)=>{let o=closeNested(t(r),t=>e.get(r,t),i);(0,import_dist$1.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 BOOLEAN_TRUTHY=new Set([`1`,`true`]),BOOLEAN_FALSY=new Set([`0`,`false`,``]);function persistValueText(e,t){let n=requireValueTarget(e),r=n.scope===`segment-palette`?`string`:wireKindOf(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(BOOLEAN_TRUTHY.has(t))return`true`;if(BOOLEAN_FALSY.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function docOf(e){return/^\s*$/.test(e)?null:parseDocument(e)}function has(e,t){return e!==null&&nodeAt(e,t)!==void 0}function authoredLayout(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(authoredLayout),...i}}return e}function authoredFragment(e){if(!isRowsFragment(e))return authoredLayout(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,authoredLayout(t)])),...n}}function requireDeclared(e,t,n,r){if(!has(e,t)&&n===void 0)throw new BadVerbArgs(`cannot edit ${r}: neither the config file nor the layers beneath it declare ${t.join(`.`)}`)}function valuePathOf(e,t,n){let r=persistPath(n);return n.scope===`segment-palette`&&requireDeclared(e,[`segments`,n.segment],t.segments[n.segment],r.join(`.`)),r}function inheritedDoc(e){return parseDocument(json5Text(e))}function inheritedRowLayers(e){if(!Object.keys(e.root.rows).every(e=>ROW_NAME_RE.test(e))){let t=authoredLayout(rootNode(e.root));return[{path:[`root`],fragment:inheritedDoc(t),unit:{path:[`root`],value:t}}]}return Object.entries(e.root.rows).map(([e,t])=>{let n=authoredLayout(t);return{path:[`root`],fragment:inheritedDoc({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function fileLayer(e,t){let n=e===null?void 0:nodeAt(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function inheritedRootLayer(e,t){if(t===void 0)return null;let n=authoredFragment(t);return{path:e,fragment:inheritedDoc(n),unit:{path:e,value:n}}}function presetLayer(e,t,n){let r=[`presets`,n],i=[...r,`root`],a=t.presets[n];requireDeclared(e,r,a,i.join(`.`));let o=fileLayer(e,i)??inheritedRootLayer(i,a?.root);return o!==null&&restagesFragment(o.fragment)?o:null}const TREE_BLOCK=`#`;function applyLayer(e,t){let n=rowEntriesOf(t.fragment);return n===null?new Map([[TREE_BLOCK,{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 cascadeOf(e,t,n){return[...inheritedRowLayers(t),fileLayer(e,[`root`]),presetLayer(e,t,n)].filter(e=>e!==null).reduce(applyLayer,new Map)}function layoutPlacementOf(e,t,n,r){for(let{node:i,...a}of cascadeOf(e,t,n).values())if(hasSegmentRef(i,r))return a;throw new BadVerbArgs(`${stagedPathOf(e,t,n).join(`.`)} holds no placement "${r}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`)}function stagedPathOf(e,t,n){return presetLayer(e,t,n)?.path??[`root`]}function resetPathOf(e,t,n){return n.scope===`preset-root`?stagedPathOf(e,t,n.preset):persistPath(n)}function ensureAuthored(e,{unit:t}){return t===null?e:setValue(e,t.path,json5Text(t.value),JSON5_DIALECT)}function requireTarget(e){let t=parsePersistTarget(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function requireValueTarget(e){let t=requireTarget(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function seenBy(e,t){let n=e=>e.flatMap(e=>{let n=t(e.path);return n===null?[]:[{...e,text:n}]});return{...e,below:n(e.below),above:n(e.above)}}function textsOf(e){let t=new Map(e.map(e=>[e.path,e.text]));return e=>t.get(e)}function commit(e,t,n,r,i){let a=loadOrRefuse(t,r),o,s=()=>(o??={chain:loadedOrNull(t,n)}).chain;return refuseNewDrops(t,s,a),i(t,s,a),e.record(t.path,n,r),a.config}function refuseHidden(e,t,n){let r=hiddenBy(e,t(),n);if(r.length>0)throw new BadVerbArgs(`refused: ${e.above.map(e=>e.path).join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — write it to that layer instead`)}const releases=()=>{};function writtenOnly(e,t){try{return t()}catch(t){throw!(t instanceof BadVerbArgs)||e.above.length===0?t:new BadVerbArgs(`${t.message} — or it is declared by ${e.above.map(e=>e.path).join(`, `)}, above it: write to that layer instead`)}}function hiddenBy(e,t,n){if(t===null)return[];let r=new Set(changedPaths(topConfig(t),topConfig(n)));return changedPaths(writtenConfig(e,t),writtenConfig(e,n)).filter(e=>!r.has(e))}function loadedOrNull(e,t){try{return chainOver(e,t)}catch(e){if(e instanceof ConfigError)return null;throw e}}function inheritedOf(e){try{return inheritedConfig(e.locs,e.below,DEFAULT_DSL_CONFIG,{repo:e.repo,cwd:e.cwd},textsOf(e.below))}catch(t){throw t instanceof ConfigError?new BadVerbArgs(`refused: a layer beneath ${e.path} does not load — ${t.message}`):t}}function chainOver(e,t){let n=[...e.below,...t===null?[]:[{path:e.path,role:e.role,text:t}],...e.above];return loadConfigChain(e.locs,n,DEFAULT_DSL_CONFIG,{warned:()=>{}},{repo:e.repo,cwd:e.cwd},textsOf(n))}function writtenConfig(e,t){let n=new Set([...e.below.map(e=>e.path),e.path]);return t.layers.filter(e=>n.has(e.path)).at(-1)?.config??t.base}function topConfig(e){return e.layers.at(-1)?.config??e.base}function changedPaths(e,t,n=``){return!isPlainObject(e)||!isPlainObject(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>changedPaths(e[r],t[r],n===``?r:`${n}.${r}`))}function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function proveLoads(e,t,n){loadOrRefuse(seenBy(e,n),t)}function loadOrRefuse(e,t){try{return chainOver(e,t)}catch(e){throw e instanceof ConfigError?new BadVerbArgs(`refused: the config file would not load after this click — ${e.message}`):e}}function refuseNewDrops(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 BadVerbArgs(`refused: this click would leave a placement of a segment nothing declares — ${o.map(({file:e,issue:t})=>new ConfigError(e,[t]).message).join(`
|
|
227
|
+
`)}`)}function readValue(e,t){let n=requireValueTarget(t),r=docOf(e??``),i=r===null?void 0:nodeAt(r,persistPath(n));return i!==void 0&&`value`in i?i.value:void 0}function writeValues(e,t,n){writeDrafts(e,t,n,[])}function writeDrafts(e,t,n,r){let i=seenBy(t,t=>e.read(t)),a=e.read(i.path),o=inheritedOf(i),s=n.reduce((e,[t,n])=>setValue(e,valuePathOf(docOf(e),o,requireValueTarget(t)),persistValueText(t,n),JSON5_DIALECT),a??``);commit(e,i,a,writtenOnly(i,()=>withPlacements(s,o,i.path,r,e=>e)),refuseHidden)}function withPlacements(e,t,n,r,i){return r.reduce((e,{preset:r,id:a,setting:o,value:s})=>{let c=i(e,t,r,a),l=layoutPlacementOf(docOf(c),t,r,a),u=setPlacementSetting(ensureAuthored(c,l),l.path,a,o,json5Text(s));if(u===null)throw new BadVerbArgs(`${l.path.join(`.`)} in ${n} has no placement "${a}" — the bar you clicked is stale (it reloads on the next render)`);return u},e)}function ownRow(e,t,n,r){let i=docOf(e),a=[`presets`,n,`root`];for(let[o,{path:s,unit:c,node:l}]of cascadeOf(i,t,n)){if(!hasSegmentRef(l,r))continue;if(a.every((e,t)=>s[t]===e))return e;let u=c===null?movableTextOf(e,l):json5Text(c.value);if(o!==TREE_BLOCK)return setValue(e,[...a,`rows`,o],u,JSON5_DIALECT);if(presetLayer(i,t,n)!==null)throw new BadVerbArgs(`cannot give preset "${n}" its own copy of ${s.join(`.`)}: it already stages rows of its own over that tree`);return setValue(e,a,u,JSON5_DIALECT)}return e}function deleteAtPath(e,t,n){return deleteValue(e,n,n[0]===`presets`&&n.length>2&&t.presets[n[1]]===void 0?2:0)}function deleteValues(e,t,n){let r=seenBy(t,t=>e.read(t)),i=n.map(requireTarget),a=e.read(r.path);if(a===null)return;let o=inheritedOf(r),s=i.reduce((e,t)=>deleteAtPath(e,o,resetPathOf(docOf(e),o,t)),a);s!==a&&commit(e,r,a,s,releases)}const SAVED_PRESET_PREFIX=`custom-`;function presetKeys(e){let t=e===null?void 0:nodeAt(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function freePresetName(e,t,n){let r=new Set([...Object.keys(t.presets),...presetKeys(e),...n.above.flatMap(e=>Object.keys(import_lib.default.parse(e.text).presets??{}))].map(ident));return Array.from({length:r.size+1},(e,t)=>`${SAVED_PRESET_PREFIX}${t+1}`).find(e=>!r.has(ident(e)))}function writePreset(e,t,n,r,i,a){let o=seenBy(t,t=>e.read(t)),s=e.read(o.path),c=docOf(s??``),l=inheritedOf(o),u=freePresetName(c,l,o),d=[`presets`,u],f=writtenOnly(o,()=>presetLayer(c,l,n)),p=[...f===null?[]:[[[...d,`root`],f.unit===null?movableTextOf(s??``,f.fragment):json5Text(f.unit.value)]],...Object.keys(r).length===0?[]:[[[...d,`globals`],json5Text(r)]]],m=i.map(([e,t])=>{let n=presetGlobalsKey(u,e);return[valuePathOf(c,l,requireValueTarget(n)),persistValueText(n,t)]}),h=[...p,...m].reduce((e,[t,n])=>setValue(e,t,n,JSON5_DIALECT),setValue(s??``,d,`{}`,JSON5_DIALECT));return commit(e,o,s,writtenOnly(o,()=>withPlacements(h,l,o.path,a.map(e=>({...e,preset:u})),ownRow)),refuseHidden),u}function writeThemeDefault(e,t,n,r){let i=seenBy(t,t=>e.read(t)),a=e.read(i.path);return commit(e,i,a,setValue(a??``,[`themeDefaults`,n],json5Text(r),JSON5_DIALECT),refuseHidden)}function deletePreset$1(e,t,n){let r=seenBy(t,t=>e.read(t)),i=inheritedOf(r);if(i.presets[n]!==void 0)throw new BadVerbArgs(`cannot delete preset "${n}": a layer beneath ${r.path} declares it — reset its settings instead`);let a=[`presets`,n],o=e.read(r.path),s=docOf(o??``);if(o===null||s===null||nodeAt(s,a)===void 0)throw new BadVerbArgs(`cannot delete preset "${n}": ${r.path} declares no ${a.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let c=nodeAt(s,[`globals`,`preset`]);commit(e,r,o,[a,...c?.kind===`string`&&c.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>deleteAtPath(e,i,t),o),releases)}function applyLayoutOp$1(e,t,n,r){let i=seenBy(t,t=>e.read(t)),a=requireTarget(n);if(a.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let o=e.read(i.path),s=r.op===`remove`?r.target:r.anchor,c=inheritedOf(i),l=writtenOnly(i,()=>layoutPlacementOf(docOf(o??``),c,a.preset,s)),u=ensureAuthored(o??``,l),{after:d,placed:f}=spliceOp(u,l.path,r,()=>{let e=loadOrRefuse(i,u).config;return presetNames(e.presets).map(t=>presetRoot(e,t).node)});if(d===null)throw new BadVerbArgs(`${l.path.join(`.`)} in ${i.path} has no placement "${s}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return{placed:f,config:commit(e,i,o,d,refuseHidden)}}function spliceOp(e,t,n,r){switch(n.op){case`remove`:return{after:removeSegmentRef(e,t,n.target),placed:null};case`insert`:{let i=mintPlacement(n.segment,n.anchor,r());return{after:insertSegmentRef(e,t,i,n.anchor,n.relation),placed:i}}}}function recordingView(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 EPHEMERAL_SESSION_STORAGE={load:()=>new Map,save:()=>{},flush:()=>{}},DEFAULT_MAX_SESSIONS=256;var SessionState=class{sessions;storage;head=0;atom=(0,import_dist$1.createAtom)(`SessionState`);constructor(e=EPHEMERAL_SESSION_STORAGE,t=DEFAULT_MAX_SESSIONS){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Array.from(this.storage.load(),([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,import_dist$1.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,import_dist$1.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,import_dist$1.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=EPHEMERAL_SESSION_STORAGE}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 SETTING_SESSION_KEYS=new Set(SETTING_PROJECTIONS.map(e=>e.sessionKey)),isSettingKey=e=>SETTING_SESSION_KEYS.has(e)||e.startsWith(PLACEMENT_DRAFT_NS),EPHEMERAL_HISTORY_STORAGE={load:()=>new Map,save:()=>{}},MAX_STEPS$1=50,MAX_SESSIONS$2=32,MAX_BYTES=8*1024*1024,EMPTY={past:[],future:[]},identity=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var SettingsHistory=class{held=import_dist$1.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,import_dist$1.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=EPHEMERAL_HISTORY_STORAGE,r=n.load()){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(r)}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??EMPTY;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??EMPTY}begin(e){let t=heldWrites(this.sessionState),n=new Map,r={held:t,files:e,historyOf:e=>n.get(e)??this.history(e),move:(e,t)=>n.set(e,t)},i=new Map,a=!1,o=(e,t)=>{a=!0;let n=i.get(e)??new Map,r=n.get(identity(t));n.set(identity(t),r===void 0?t:{...t,before:r.before}),i.set(e,n)},s=new Map,c=recordingView(t,()=>!0,(e,t,n,r)=>{if(a=!0,!(!isSettingKey(t)&&t!==`edit.mode`)){if(t===`edit.mode`){let t=s.get(e);s.set(e,{before:t===void 0?n:t.before,after:r});return}o(e,{kind:`session`,key:t,before:n,after:r})}}),l=()=>{let e=new Map(i),t=new Map(s);i.clear(),s.clear();for(let n of new Set([...e.keys(),...t.keys()])){let i=[...e.get(n)?.values()??[]].filter(e=>e.before!==e.after),a=r.historyOf(n),o=i.length===0?a:afterAppend(a,i),s=t.get(n),c=s===void 0?o:withToggle(o,s);c!==a&&r.move(n,c)}};return{sessionState:c,file:(t,n,r,i)=>{o(t,{kind:`file`,file:n,before:r,after:i}),e.land(n,r,i)},wrote:()=>{a=!0},written:()=>a,undo:e=>(l(),this.undo(r,e)),redo:e=>(l(),this.redo(r,e)),rewind:e=>(l(),this.rewind(r,e)),commit:()=>{l();let e=new Map(n);n.clear();for(let[t,n]of e)this.put(t,n);t.flush()}}}undo(e,t){let n=e.historyOf(t),r=n.past.at(-1);if(r===void 0)throw new BadVerbArgs(`undo: nothing to undo`);return this.apply(e,t,r,`before`,`undo`,afterUndo(n,r)),r}rewind(e,t){let n=e.historyOf(t),{savepoint:r}=n;if(r===void 0)throw new BadVerbArgs(`rewind: edit mode has no savepoint — nothing to cancel`);let i=r.net.flatMap(n=>{let r=stepOf(e,t,n,`before`);return r.kind===`moved`?[r]:[]}),a=new Set(i.map(e=>e.target)),o=r.net.filter(e=>!a.has(identity(e))),s=capped(without(pastAt(n,r),a));if(this.apply(e,t,o,`before`,`rewind`,{past:s,future:[],savepoint:{at:s.length,net:[],below:[]}}),i.length>0)throw new BadVerbArgs(`rewind: ${i.map(e=>e.what).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return o}redo(e,t){let n=e.historyOf(t),{past:r,future:i}=n,a=i.at(-1);if(a===void 0)throw new BadVerbArgs(`redo: nothing to redo`);let o=[...r,a],s=capped(o);return this.apply(e,t,a,`after`,`redo`,{past:s,future:i.slice(0,-1),...savepointAfter(n.savepoint,o.length-s.length,a)}),a}apply(e,t,n,r,i,a){let o=n.map(n=>stepOf(e,t,n,r)),s=o.flatMap(e=>e.kind===`moved`?[e]:[]);if(s.length>0)throw e.move(t,forgotten(e.historyOf(t),new Set(s.map(e=>e.target)))),new BadVerbArgs(`${i}: ${s.map(e=>e.what).join(`, `)} changed since that edit — refusing to overwrite it; this session's undo history no longer steps it`);let c=o.flatMap(e=>e.kind===`file`?[e]:[]),l=new Map(c.map(({file:e,text:t})=>[e,t])),u=t=>{let n=l.get(t);return n===void 0?e.files.read(t):n};for(let{file:t,text:n}of c)e.files.prove(t,n,u);for(let{file:t,text:n}of c)e.files.land(t,e.files.read(t),n);for(let n of o)n.kind===`session`&&(n.value===null?e.held.clear(t,n.key):e.held.set(t,n.key,n.value));e.move(t,a)}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>MAX_SESSIONS$2||weight(n)>MAX_BYTES;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,withoutOldestStep(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${MAX_BYTES} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function weight(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 withoutOldestStep({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...savepointAfter(n,1,[])}:{past:e,future:t.slice(1),...savepointAfter(n,0,[])}}function capped(e){return e.slice(-MAX_STEPS$1)}const isOpen=e=>e===EDIT_MODE_REF.member;function savepointAfter(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:withNet(e.net,n),below:e.below}}}function withNet(e,t){let n=new Map(e.map(e=>[identity(e),e]));for(let e of t){let t=n.get(identity(e));n.set(identity(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const reversed=e=>e.map(e=>({...e,before:e.after,after:e.before}));function afterAppend(e,t){let n=[...e.past,t],r=capped(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...savepointAfter(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...redone(e.future,a),...i.below]},n.length-r.length,t)}}function redone(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function afterUndo(e,t){return{past:e.past.slice(0,-1),future:capped([...e.future,t]),...savepointAfter(e.savepoint,0,reversed(t))}}function pastAt(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...redone(r,t.at-i.length),...t.below]}function withToggle(e,t){if(isOpen(t.after)&&!isOpen(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!isOpen(t.after)&&isOpen(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function without(e,t){return e.map(e=>e.filter(e=>!t.has(identity(e)))).filter(e=>e.length>0)}function describeStep(e){return e.map(describe).join(`, `)}function describe(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function stepOf(e,t,n,r){let i=r===`before`?`after`:`before`;if(n.kind===`session`)return e.held.get(t,n.key)===n[i]?{kind:`session`,key:n.key,value:n[r]}:{kind:`moved`,target:identity(n),what:`session setting "${n.key}"`};let a=applyChanges(e.files.read(n.file),diffChanges(n[i],n[r]));return a.kind===`applied`?{kind:`file`,file:n.file,text:a.text}:{kind:`moved`,target:identity(n),what:`${addressText(a.at)} in ${n.file}`}}function forgotten({past:e,future:t,savepoint:n},r){return{past:without(e,r),future:without(t,r),...n!==void 0&&{savepoint:{at:without([...e,...[...t].reverse()].slice(0,n.at),r).length,net:n.net.filter(e=>!r.has(identity(e))),below:without(n.below,r)}}}}function heldWrites(e){let t=new Map,n=(e,n,r)=>{let i=t.get(e)??new Map;i.set(n,r),t.set(e,i)};return{get:(n,r)=>{let i=t.get(n);return i?.has(r)?i.get(r):e.get(n,r)},revision:t=>e.revision(t),set:(e,t,r)=>n(e,t,r),setBatch:(e,t)=>{for(let{key:r,value:i}of t)n(e,r,i)},clear:(e,t)=>n(e,t,null),flush:()=>(0,import_dist$1.runInAction)(()=>{for(let[n,r]of t){let t=[...r].flatMap(([e,t])=>t===null?[]:[{key:e,value:t}]);t.length>0&&e.setBatch(n,t);for(let[t,i]of r)i===null&&e.clear(n,t)}t.clear()})}}const SESSION_FACT_VARIABLES=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function sessionEnv(e){return{...Object.fromEntries(SESSION_FACT_VARIABLES.map(e=>[e,null])),CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir,...e.claudeConfigDir!==void 0&&{CLAUDE_CONFIG_DIR:e.claudeConfigDir}}}const isRecord=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function parseMarkBook(e){let t=e=>({kind:`failed`,reason:e});if(!isRecord(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!isRecord(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!GLYPH_MARKS.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${GLYPH_MARKS.join(` or `)}`)}return{kind:`ok`,value:e}}function withMark(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const fileMarkBook=e=>stateFile(e,`doctor-marks.json`,{},parseMarkBook),parseClickedTerminals=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},withClicked=(e,t)=>e.includes(t)?e:[...e,t],fileClickedTerminals=e=>stateFile(e,`doctor-clicked-terminals.json`,[],parseClickedTerminals),inTurn=e=>({gathers:!1,prepare:async t=>n=>e(t,n)});function requireSessionId(e){let t=parseSessionId(e);if(!t.ok)throw new BadVerbArgs(`session id ${t.problem}`);return t.id}function oneArg(e){return decodeWire(()=>decodeURIComponent(e))}function ask(e,t){e.acts.ask(e.effects,t)}const copy=async(e,t)=>ask(t,{kind:`copy`,session:t.session,text:oneArg(e)}),DRAWERS=new Set([`request`,`feed`]);function requireDrawer(e){if(!DRAWERS.has(e))throw new BadVerbArgs(`unknown renderer ${JSON.stringify(e)}`);return e}const copyDiagnostic=async(e,t)=>{let[n=``,r=``,i=``]=decodeWire(()=>decodeSegments(e)),a=requireSessionId(n),o=t.diagnosticCopy(a,requireDrawer(r),i);if(o===void 0)throw new BadVerbArgs(`that message is no longer listed in session ${a}'s diagnostics — open the indicator beside the settings door again and copy from there`);ask(t,{kind:`copy`,session:a,text:o})},openVscode=async(e,t)=>ask(t,{kind:`open`,session:t.session,target:oneArg(e)}),setState=async(e,t)=>{let[n=``,...r]=decodeWire(()=>decodeSegments(e)),i=requireSessionId(n),a=t.gates.state.gateFor(sessionConfig(t,i));if(r.length===0)throw new BadVerbArgs(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new BadVerbArgs(`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 BadVerbArgs(`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 BadVerbArgs(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}refuseDisorderedPicks(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})`)},STEP_INT_RE=/^-?\d+$/;function stepWithin(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const stepState=async(e,t)=>{let[n=``,r=``,i=``]=decodeWire(()=>decodeSegments(e)),a=requireSessionId(n);if(!r)throw new BadVerbArgs(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!STEP_INT_RE.test(i))throw new BadVerbArgs(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=sessionConfig(t,a),c=t.gates.state.gateFor(s),l=c.rangeParamsFor(r);if(!l)throw new BadVerbArgs(`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&&STEP_INT_RE.test(u)?clampTo(l,parseInt(u,10)):stepFrom(`step-state`,r,l,stateKeySeed(s,e=>t.sessionState.get(a,e),r)),f=stepWithin(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new BadVerbArgs(`step-state: ${p.reason}`);refuseDisorderedPicks(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 refuseDisorderedPicks(e,t,n,r){let i=r.filter(e=>e.key.startsWith(PLACEMENT_DRAFT_NS));if(i.length===0)return;let a=placementPickProblems(sessionConfig(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new BadVerbArgs(`${n}: refused — ${a.join(`; `)}`)}function clampTo(e,t){return Math.max(e.min,Math.min(e.max,t))}function stepFrom(e,t,n,r){if(r===null)return n.min;if(!STEP_INT_RE.test(r))throw new BadVerbArgs(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return clampTo(n,parseInt(r,10))}function recordedTarget(e,t){return t===null?{source:`search`}:e===`argument`||e===`environment`?{source:e,path:t}:{source:`unknown`,path:t}}function parseRenderOrigin(e){let t;try{t=JSON.parse(e)}catch{throw new BadVerbArgs(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new BadVerbArgs(`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 BadVerbArgs(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,target:recordedTarget(a,i)}}function sessionOrigin(e,t){let n=recordedOrigin(e,t);if(n===null)throw new BadVerbArgs(`session ${t} has not rendered yet — no config to act on`);return n}function recordedOrigin(e,t){let n=e.sessionState.get(t,SESSION_RENDER_ORIGIN_KEY);return n===null?null:parseRenderOrigin(n)}function changeDone(e,t,n,r){let i=e.configWrites.settled(t,n);return i===void 0?!1:(i!==`owed`&&changeLanded(e,i,r),!0)}function changeLanded(e,{session:t,files:n,answered:r,consequence:i,outcome:a},o){let s=[],c=e=>{try{e()}catch(e){s.push(failureOf(e).message)}};if(a.kind===`ok`)c(()=>{let i=recordedOrigin(e,t);i!==null&&(r||originLayers(e,i).some(e=>n.includes(e.path)))&&e.reloadConfig(i)}),c(()=>i(o));else if(a.kind===`closing`)return;else s.push(a.reason);if(s.length===0)return;let l=s.join(`
|
|
228
|
+
`);e.log(`warn`,`config change: ${l} (session=${t})`),holdClickError(e.sessionState,t,l,e.now())}function proveLoadsAsLayer(e,t,n,r,i){let a=t===null?null:recordedOrigin(e,t),o=a===null?void 0:originLayers(e,a).find(e=>e.path===n);if(o===void 0)throw new BadVerbArgs(`${n} is not a config file this session renders from — its step is not taken`);proveLoads(o,r,i)}function sessionConfig(e,t){return e.configFor(sessionOrigin(e,t))}function laneMeter(e,t,n){let r=recordedOrigin(e,t);if(r===null)return null;let i=()=>e.lanes.of(r,t,n);return{sessionId:t,latest:n,before:i(),read:i}}function nestOf(e,t){let n=recordedOrigin(e,t);return n===null?NO_NEST:disclosureNest(e.configFor(n))}function originLayer(e,t,n){let r=writeLayer(e.locations,repoConfigs(e.stateDir).read(),{projectDir:t.projectDir,configFile:t.target.path,cwd:t.cwd},n);if(r.kind===`refused`)throw new BadVerbArgs(`the ${n} layer is not writable: ${r.why}`);return r}function originLayers(e,t){let n=writeLayers(e.locations,repoConfigs(e.stateDir).read(),{projectDir:t.projectDir,configFile:t.target.path,cwd:t.cwd});return LAYER_ROLES.flatMap(e=>{let t=n[e];return t.kind===`layer`?[t]:[]})}function configWire(e,t){let[n=``,r=``,...i]=decodeWire(()=>decodeSegments(t)),a=requireSessionId(n),o=layerRoleOf(r);if(o===null)throw new BadVerbArgs(`${e}: "${r}" is not a config layer (one of ${LAYER_ROLES.join(`, `)})`);return{sid:a,role:o,args:i}}function editStore(e,t){return{read:t=>e.configWrites.read(t),record:(n,r,i)=>e.journal.file(t,n,r,i)}}const setConfig=async(e,t)=>{let{sid:n,role:r,args:[i=``,a=``]}=configWire(`set-config`,e),o=sessionOrigin(t,n),s=t.configFor(o),c=t.gates.config.gateFor(s);if(!i)throw new BadVerbArgs(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(i,a);if(!l.ok)throw new BadVerbArgs(`set-config: ${l.reason}`);let u=originLayer(t,o,r),d=durableLanding(s,e=>t.sessionState.get(n,e),i);writeValues(editStore(t,n),u,[[d.key,l.value]]),t.log(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${n})`)},stepConfig=async(e,t)=>{let{sid:n,role:r,args:[i=``,a=``]}=configWire(`step-config`,e);if(!i)throw new BadVerbArgs(`step-config: <key> is required (shape: <sessionId>/<layer>/<key>/<by>)`);if(!STEP_INT_RE.test(a))throw new BadVerbArgs(`step-config: delta must be an integer, got "${a}"`);let o=parseInt(a,10),s=sessionOrigin(t,n),c=t.configFor(s),l=t.gates.config.gateFor(c),u=l.rangeParamsFor(i);if(!u)throw new BadVerbArgs(`step-config: key "${i}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=originLayer(t,s,r),f=durableLanding(c,e=>t.sessionState.get(n,e),i),p=readValue(editStore(t,n).read(d.path),f.key),m=typeof p==`number`?clampTo(u,p):stepFrom(`step-config`,i,u,configKeySeed(f.globals,i)),h=stepWithin(m,o,u.min,u.max),g=l.validate(i,String(h));if(!g.ok)throw new BadVerbArgs(`step-config: ${g.reason}`);writeValues(editStore(t,n),d,[[f.key,g.value]]),t.log(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${n})`)},save=async(e,t)=>{let{sid:n,role:r}=configWire(`save`,e),i=sessionOrigin(t,n),a=t.configFor(i),o=e=>t.sessionState.get(n,e),s=settingDrafts(a,o),c=placementDrafts(a,o);if(s.length+c.length===0){t.log(`info`,`save: nothing unsaved (session=${n})`);return}let l=t.gates.state.gateFor(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new BadVerbArgs(`save: ${t.reason}`);return[e.target,t.value]});gatePlacements(`save`,l,c);let d=originLayer(t,i,r);writeDrafts(editStore(t,n),d,u,c);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(n,e);t.log(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(placementLog)].join(` `)} → ${d.path} (session=${n})`)},placementLog=e=>`${e.preset}/${e.id}.settings.${e.setting}=${settingSpelling(e.value)}`;function gatePlacements(e,t,n){for(let r of n){let n=t.validate(r.key,settingSpelling(r.value));if(!n.ok)throw new BadVerbArgs(`${e}: ${n.reason}`)}}const savePreset=async(e,t)=>{let{sid:n,role:r}=configWire(`save-preset`,e),i=sessionOrigin(t,n),a=t.configFor(i),o=presetSnapshot(a,e=>t.sessionState.get(n,e)),s=t.gates.state.gateFor(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new BadVerbArgs(`save-preset: ${t.reason}`);return[e.configKey,t.value]});gatePlacements(`save-preset`,s,o.placements);let l=originLayer(t,i,r),u=writePreset(editStore(t,n),l,o.from,o.globals,c,o.placements);for(let e of[...SETTING_PROJECTIONS.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(n,e);t.sessionState.set(n,SETTINGS.preset.sessionKey,u),t.log(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(placementLog)].join(` `)} → ${l.path} (session=${n})`)},saveThemeDefault=async(e,t)=>{let{sid:n,role:r}=configWire(`save-theme-default`,e),i=sessionOrigin(t,n),a=themeDefaultSave(t.configFor(i),e=>t.sessionState.get(n,e));if(a.kind===`rule`)throw new BadVerbArgs(`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=originLayer(t,i,r),s=writeThemeDefault(editStore(t,n),o,a.theme,a.look),c=new Set(settingDrafts(s,e=>t.sessionState.get(n,e)).map(e=>e.sessionKey)),l=THEME_DEFAULT_FIELDS.map(e=>SETTINGS[e].sessionKey).filter(e=>!c.has(e));for(let e of l)t.sessionState.clear(n,e);t.log(`info`,`save-theme-default: ${a.theme} ${THEME_DEFAULT_FIELDS.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${n})`)},deletePreset=async(e,t)=>{let{sid:n,role:r,args:[i=``]}=configWire(`delete-preset`,e);if(!i)throw new BadVerbArgs(`delete-preset: <name> is required (shape: <sessionId>/<layer>/<name>)`);let a=originLayer(t,sessionOrigin(t,n),r);deletePreset$1(editStore(t,n),a,i);let o=SETTINGS.preset.sessionKey;t.sessionState.get(n,o)===i&&t.sessionState.clear(n,o),t.log(`info`,`delete-preset: ${i} ← ${a.path} (session=${n})`)},resetConfig=async(e,t)=>{let{sid:n,role:r,args:i}=configWire(`reset-config`,e),a=sessionOrigin(t,n),o=t.gates.config.gateFor(t.configFor(a)).listKeys(),s=i.length===0?[``]:i.filter(e=>!o.includes(e));if(s.length>0)throw new BadVerbArgs(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=originLayer(t,a,r),l=i.map(resetLayers),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);deleteValues(editStore(t,n),c,u);for(let e of d)t.sessionState.clear(n,e);t.log(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${n})`)};function endedPlacements(e,t){let n=(e,t)=>[...walkNodes(presetRoot(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(presetNames(t.presets).flatMap(e=>n(t,e).map(t=>configureMember(ident(e),placementId(t)))));return presetNames(e.presets).flatMap(t=>n(e,t).map(e=>({member:configureMember(ident(t),placementId(e)),node:e})).filter(({member:e})=>!r.has(e)))}function endedSessionKeys(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[EDIT_CONFIGURE_KEY]:[]])}const applyLayoutOp=async(e,t)=>{let{sid:n,role:r,args:[i=``,a=``]}=configWire(`apply-layout-op`,e),o=sessionOrigin(t,n),s=t.configFor(o),c=t.gates.config.gateFor(s);if(!i)throw new BadVerbArgs(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(i,a);if(!l.ok)throw new BadVerbArgs(`apply-layout-op: ${l.reason}`);let u=decodeLayoutOp(l.value);if(u===null)throw new BadVerbArgs(`apply-layout-op: "${l.value}" is not a layout op token`);let d=originLayer(t,o,r),{placed:f,config:p}=applyLayoutOp$1(editStore(t,n),d,i,u),m=endedSessionKeys(endedPlacements(s,p),t.sessionState.get(n,EDIT_CONFIGURE_KEY)).filter(e=>t.sessionState.get(n,e)!==null);for(let e of m)t.sessionState.clear(n,e);t.log(`info`,`apply-layout-op: ${i} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(m)} (session=${n})`)},undo=async(e,t)=>{let[n=``]=decodeWire(()=>decodeSegments(e)),r=requireSessionId(n),i=t.journal.undo(r);t.journal.wrote(),t.log(`info`,`undo: restored ${describeStep(i)} (session=${r})`)},back=async(e,t)=>{let n=requireSessionId(oneArg(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,t.gates.state.gateFor(sessionConfig(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.log(`info`,`back: ${a} discarded=${i} (session=${n})`)},rewind=async(e,t)=>{let n=requireSessionId(oneArg(e));t.journal.wrote();let r=t.journal.rewind(n);t.log(`info`,`rewind: put back ${describeStep(r)||`nothing`} as edit mode found it (session=${n})`)},redo=async(e,t)=>{let[n=``]=decodeWire(()=>decodeSegments(e)),r=requireSessionId(n),i=t.journal.redo(r);t.journal.wrote(),t.log(`info`,`redo: re-applied ${describeStep(i)} (session=${r})`)},applyUpdate=async(e,t)=>ask(t,{kind:`apply-update`,session:requireSessionId(oneArg(e))});function sessionHints(e,t){let n=e.sessionState.get(t,SESSION_CLIENT_HINTS_KEY);if(n===null)throw new BadVerbArgs(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new BadVerbArgs(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new BadVerbArgs(`client hints record is not an object: ${n}`);return parseClientHints(r)}function writeReport(e,t,n){let r=runDoctor(n);e.sessionState.setBatch(t,doctorReportPairs(r)),e.log(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${configFields(n.config)} ${nerdFontFields(n.nerdFont,n.marks)} ${linkFields(n.terminal,n.clicked)} ${terminalFeatureFields(n.terminal,n.width)} ${installFields(n.install)} ${daemonFields(n.daemon)} ${dataFields(n.data)} ${transcriptFields(n.transcripts)} ${frameFields(n.frames,n.claudeSettings)} ${truecolorEnvFields(n.claudeSettings.origin.sources)} (session=${t})`)}async function clickGather(e,t,n,r){let i={kind:`clicked`,sessionId:t,via:e.arrival.via},[a,o]=await Promise.all([e.clients.ofSession(t,e.now()),e.serving()]),s,c;try{[s,c]=await Promise.all([gatherFacts({...n,loadConfig:()=>r},sessionHints(e,t),sessionOrigin(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:o},{kind:`ok`,value:a.map(e=>e.rateLimits)},{kind:`ok`,value:a.map(e=>e.transcript)},i,{kind:`ok`,value:barsOf(i,a)},sessionWidth(t,a),readStores(e.doctorStores)),e.installFacts(e.bundle,a.map(e=>e.client))])}catch(e){throw e instanceof DoctorBusy?new BadVerbArgs(e.message):e}let l={facts:s,install:c,current:async e=>{let i=n.loadConfig(sessionOrigin(e,t));return i.config===r.config&&i.error===r.error&&i.warning===r.warning?l:clickGather(e,t,n,i)}};return l}const gatherClick=(e,t)=>{let n=oneAskPerClick(e.doctor);return clickGather(e,t,n,n.loadConfig(sessionOrigin(e,t)))};async function clickFacts(e,t,n){let{facts:r,install:i}=await e.gather(n.current),a=readStores(e.doctorStores),o={...r,marks:a.marks,clicked:a.clicked,daemon:{...r.daemon,read:a.postMortemsRead}};return{...o,urlHandler:clickArrived(e.arrival),install:i,clicked:clickedFrom(e,o)}}function clickedFrom(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?sightingOf(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>withClicked(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 doctorRun={gathers:!0,prepare:async(e,t)=>{let n=requireSessionId(oneArg(e)),r=await gatherClick(t,n);return async e=>writeReport(e,n,await clickFacts(e,n,r))}},doctorFix={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``]=decodeWire(()=>decodeSegments(e)),i=requireSessionId(n),a=checkByName(r);if(a===void 0)throw new BadVerbArgs(`doctor-fix: unknown check "${r}"`);let o=await gatherClick(t,i);return async e=>{let t=await clickFacts(e,i,o),n=a.probe(t);if(n.ok||n.fix===void 0)throw new BadVerbArgs(`doctor-fix: ${a.label} — ${n.ok?`nothing to fix`:n.reason}`);let r=applyFix(e.doctorStores,n.fix,t);if(r.kind===`failed`)throw new BadVerbArgs(`doctor-fix: ${a.label} — ${r.reason}`);e.log(`info`,`doctor-fix: ${a.name} → ${describeFix(n.fix)} (session=${i})`),writeReport(e,i,r.value)}}},doctorMark={gathers:!0,prepare:async(e,t)=>{let[n=``,r=``,i=``]=decodeWire(()=>decodeSegments(e)),a=requireSessionId(n),o=checkByName(r);if(o===void 0)throw new BadVerbArgs(`doctor-mark: unknown check "${r}"`);if(!GLYPH_MARKS.includes(i))throw new BadVerbArgs(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${GLYPH_MARKS.join(` or `)}`);let s=await gatherClick(t,a);return async e=>{let t=await clickFacts(e,a,s),n=o.probe(t);if(n.ok||n.sighting===void 0)throw new BadVerbArgs(`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=>withMark(e,...r));if(c.kind===`failed`)throw new BadVerbArgs(`doctor-mark: ${c.reason}`);e.log(`info`,`doctor-mark: ${o.name} ${i} on ${n.sighting.id} (session=${a})`),writeReport(e,a,{...t,marks:c})}}},slash=async(e,t)=>{let[n=``,r=``]=decodeWire(()=>decodeSegments(e)),i=requireSessionId(n),a=Object.values(t.configFor(sessionOrigin(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new BadVerbArgs(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=tmuxPaneOf(sessionHints(t,i).tmux);if(s.kind===`refused`)throw new BadVerbArgs(`${r} was not typed: ${s.reason}`);ask(t,{kind:`type-slash`,session:i,pane:s.hint,line:o.slash})};function runOf([e=``,t=``,n=``,r=``],i){let a=requireSessionId(e),o=sessionOrigin(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 BadVerbArgs(`"${t}" is not a run action this session's config declares`);let l=runDeclaration(c);if(!i.links.verify({sessionId:a,action:t,declaration:l,evaluated:n},r))throw new BadVerbArgs(`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 BadVerbArgs(`run ${t}: what the link carries is not JSON`)}let[d,...f]=u.run;if(d===void 0||d===``)throw new BadVerbArgs(`run ${t}: the program evaluated to nothing`);let p=i.sourcesFor(o);return{kind:`run`,session:a,action:t,program:d,args:f,env:{...sessionEnv({sessionId:a,projectDir:o.projectDir,claudeConfigDir:sessionHints(i,a).claudeConfigDir}),...u.env},cwd:c.cwd??i.locations.home,refreshes:c.refreshes.map(e=>({name:e,folder:p.get(e)}))}}const run=async(e,t)=>ask(t,runOf(decodeWire(()=>decodeSegments(e)),t)),repoConfig=async(e,t)=>{let[n=``,r=``,i=``,a=``]=decodeWire(()=>decodeSegments(e)),o=requireSessionId(n),s=REPO_ANSWERS.find(e=>e===i);if(s===void 0||!t.links.verify(repoAnswerFields(o,r,s),a))throw new BadVerbArgs(`the answer's signature does not match what it carries: it was not drawn by this daemon`);t.configWrites.answer(r,s),t.journal.wrote()},LEAF_VERBS=new Map([[VERB_COPY,inTurn(copy)],[VERB_OPEN_VSCODE,inTurn(openVscode)],[VERB_SET_STATE,inTurn(setState)],[VERB_STEP_STATE,inTurn(stepState)],[VERB_SET_CONFIG,inTurn(setConfig)],[VERB_STEP_CONFIG,inTurn(stepConfig)],[VERB_RESET_CONFIG,inTurn(resetConfig)],[VERB_SAVE,inTurn(save)],[VERB_SAVE_PRESET,inTurn(savePreset)],[VERB_SAVE_THEME_DEFAULT,inTurn(saveThemeDefault)],[VERB_DELETE_PRESET,inTurn(deletePreset)],[VERB_APPLY_LAYOUT_OP,inTurn(applyLayoutOp)],[VERB_UNDO,inTurn(undo)],[VERB_REDO,inTurn(redo)],[VERB_BACK,inTurn(back)],[VERB_REWIND,inTurn(rewind)],[VERB_APPLY_UPDATE,inTurn(applyUpdate)],[VERB_DOCTOR_RUN,doctorRun],[VERB_DOCTOR_FIX,doctorFix],[VERB_DOCTOR_MARK,doctorMark],[VERB_SLASH,inTurn(slash)],[`run`,inTurn(run)],[VERB_REPO_CONFIG,inTurn(repoConfig)],[VERB_COPY_DIAGNOSTIC,inTurn(copyDiagnostic)]]),hoisted=(e,t,n)=>n.journalTurns.gathering(()=>e.prepare(t,n)).catch(e=>()=>Promise.reject(e));async function perform(e,t,n,r){await(r??await n.gather(n=>e.prepare(t,n)))(n)}async function headGather(e,t){let[n]=e,r=n===void 0?void 0:LEAF_VERBS.get(n.verb);return r?.gathers?hoisted(r,n.value,t):void 0}function stepsOf(e,t){return batchAdjacentWrites(e===`dispatch`?parseEffects(t):[{verb:e,value:t}])}async function foldEffects(e,t,n,r){let i=[],a=!1;for(let[t,{verb:o,value:s}]of e.entries()){let e=LEAF_VERBS.get(o);if(!e){i.push(`unknown effect verb "${o}"`);continue}try{await perform(e,s,n,t===0?r:void 0)}catch(e){let t=failureOf(e);if(t.kind!==`bad-request`&&t.kind!==`threw`)throw i.length>0&&n.log(`warn`,`click: ${i.join(`; `)}`),e;t.kind===`threw`&&(a=!0),i.push(`${o}: ${t.message}`)}}if(i.length>0){t!==null&&holdClickError(n.sessionState,t,i.join(`
|
|
229
|
+
`),n.now());let e=i.join(`; `);throw a?Error(e):new BadVerbArgs(e)}}function throwAll(e){if(e.length===1)throw e[0];if(e.length>1)throw Error(e.map(e=>String(e.message??e)).join(`; `))}async function journaled(e,t,n,r,i,a){let o=e===null?null:laneMeter(n,e,t),s=n.history.begin({read:e=>n.configWrites.read(e),land:(e,t,r)=>n.configWrites.land(e,t,r),prove:(t,r,i)=>proveLoadsAsLayer(n,e,t,r,i)}),c=n.navigation.begin(s.sessionState),l=[],u=e=>closingView(e,e=>nestOf(n,e),e=>n.log(`info`,e)),d={...n,session:e,sessionState:u(s.sessionState),journal:s,navigating:u(c.sessionState)};try{await a({...d,gather:e=>i.landed(e(d))})}catch(e){l.push(e)}let f=e=>{let t=[];for(let e of[c,s])try{e.commit()}catch(e){t.push(e)}if(o!==null)try{let t=o.read();n.lanes.clicked(o.sessionId,o.latest,s.written()?o.before:t,t,e)}catch(e){t.push(e)}throwAll(t)};try{n.configWrites.seal(r,e,f)}catch(e){l.push(e)}throwAll(l)}function click(e){return async(t,n)=>{let r=clickSessionOf(e,t),i=r?.ok?r.id:null,a=stepsOf(e,t);return n.journalTurns.click(e,i,{placed:n.placeWaited,waited:n.turnWaited,gone:n.clientGone,gathered:n.gatherTook},()=>headGather(a,n),(e,t)=>journaled(i,n.latest,n,n.effects,t,async t=>{try{await foldEffects(a,i,t,e)}finally{i!==null&&n.clickLanded(i)}}))}}const VERBS=new Map([...LEAF_VERBS.keys(),VERB_DISPATCH].map(e=>[e,click(e)])),VERB_NAMES=Object.freeze([...VERBS.keys()]);function closeIdleMenus(e,t,n,r,i){return r.journalTurns.take(`menu-idle`,{waited:t=>r.log(`info`,`menu-idle: waited=${t}ms (session=${e})`),gone:async()=>!1},a=>journaled(e,t,r,i,a,async t=>{if(!await a.landed(n.confirm())){t.log(`info`,`menu-idle: no longer idle, kept (session=${e})`);return}let r=openRoots(nestOf(t,e),n=>t.navigating.get(e,n));t.navigating.setBatch(e,r.map(({key:e})=>({key:e,value:DISCLOSURE_CLOSED}))),t.log(`info`,`menu-idle: closed=${r.map(({key:e})=>e).join(`,`)||`-`} idle=${n.idleS.toFixed(1)}s timeout=${n.timeoutS}s (session=${e})`)}))}function verbsOver(e,t){return{handler:n=>{let r=VERBS.get(n);return r&&((n,{click:i,...a})=>r(n,{...e,...a,clientGone:()=>t.gone(i)}))},closeIdle:(t,n,r,i)=>closeIdleMenus(t,n,r,e,i),changeDone:(t,n,r)=>changeDone(e,t,n,r)}}const MAX_STEPS=20,MAX_SESSIONS$1=32,isNavigationKey=e=>!isSettingKey(e)&&!isConfirmKey(e)&&e!==`update.dismissed`&&e!==DIAGNOSTICS_VIEWING;var NavigationHistory=class{past=import_dist$1.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:recordingView(e,isNavigationKey,(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 BadVerbArgs(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,import_dist$1.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(-MAX_STEPS))}put(e,t){(0,import_dist$1.runInAction)(()=>{for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>MAX_SESSIONS$1;)this.past.delete(this.past.keys().next().value)})}};const MAX_RECORDS=512,RENDERERS=[`request`,`feed`],generations=new WeakMap;let nextGeneration=0;const generationOf=e=>{let t=generations.get(e);if(t!==void 0)return t;let n=nextGeneration++;return generations.set(e,n),n};var RenderWarningRecords=class{records=new Map;constructor(e=MAX_RECORDS){this.maxRecords=e}of(e,t){return this.records.get(keyOf(e,t))?.warnings??[]}ofSession(e,t,n){let r=generationOf(n.config),i=[];for(let n of RENDERERS){let a=this.records.get(keyOf(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=keyOf(e,t);this.records.delete(a),this.records.set(a,{generation:generationOf(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 keyOf=(e,t)=>`${t}\0${e}`;var ActsOnTheirWay=class{owed=new Set;constructor(e,t){this.mint=e,this.failed=t}ask(e,t){let n=this.mint();this.owed.add(n),e.push({...t,id:n})}done(e,t,n){return this.owed.delete(e)?(t!==null&&(n.kind===`failed`||n.kind===`refused`)&&this.failed(t,n.reason),!0):!1}};const MAX_SESSIONS_OWED=1024,atOf=e=>({sessionId:e.hookData.session_id,tmux:e.hints.tmux,session:{projectDir:e.requested.projectDir,claudeConfigDir:e.hints.claudeConfigDir??null,transcript:e.hookData.transcript_path,answered:answeredOf(e.hookData)}});function inPane(e,t){let n=tmuxPaneOf(e.tmux);return n.kind===`refused`?n:t(n.hint)}const act=e=>({kind:`act`,act:e}),nothing=e=>({kind:`nothing`,said:e}),LANE_SETUP={band:{on:e=>act({kind:`surface`,surface:`band`,on:!0,session:e.sessionId,pane:tmuxPaneOf(e.tmux),at:e.session}),off:()=>nothing(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:e=>inPane(e,t=>act({kind:`restart-claude`,session:e.sessionId,pane:t,at:e.session})),off:()=>nothing(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:e=>inPane(e,t=>act({kind:`surface`,surface:`pane`,on:!0,session:e.sessionId,pane:t})),off:e=>{let t=tmuxPaneOf(e.tmux);return t.kind===`refused`?nothing(`no bar pane to close: ${t.reason}`):act({kind:`surface`,surface:`pane`,on:!1,session:e.sessionId,pane:t.hint})}},tmuxStatus:{on:e=>inPane(e,e=>nothing(`the daemon draws ${e.pane}'s bar in its status line`)),off:()=>nothing(`nothing to stop: the daemon puts the status line back once the lane is off`)}};var LaneActs=class{owed=new Map;constructor(e){this.deps=e}clicked(e,t,n,r,i){let a=LANE_NAMES.filter(e=>n[e]!==r[e]),o=this.take(e);for(let e of a)o.has(e)||o.set(e,n[e]);let s=e=>a.includes(e)?`click`:`owed`;if(t!==null){this.settle(atOf(t),o,r,s,i);return}for(let[e,t]of o)t===r[e]&&o.delete(e);if(a.length>0){let t=[...o.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}o.size>0&&this.owed.set(e,o);for(let[e,t]of this.owed){if(this.owed.size<=MAX_SESSIONS_OWED)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t,n){let r=this.owed.get(e.hookData.session_id);r!==void 0&&(this.owed.delete(e.hookData.session_id),this.settle(atOf(e),r,t,()=>`owed`,n))}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r,i){for(let[a,o]of t){let t=n[a],s=`lane: ${a} ${t?`on`:`off`}`,c=`by=${r(a)} (session=${e.sessionId})`;if(t===o){this.deps.log(`info`,`${s} — nothing owed: its switch is back where the lane is ${c}`);continue}let l=LANE_SETUP[a][t?`on`:`off`](e);switch(l.kind){case`act`:this.deps.log(`info`,`${s} — asked ${c}`),this.deps.ask(i,l.act);break;case`nothing`:this.deps.log(`info`,`${s} — ${l.said} ${c}`);break;case`refused`:this.deps.log(`warn`,`${s}: ${l.reason} ${c}`),this.deps.refused(e.sessionId,`${s}: ${l.reason}`)}}}},WorldStates=class{constructor(e){this.took=e}documents=import_dist$1.observable.map(void 0,{deep:!1});take(e){let t=this.documents.get(e.session);if(t!==void 0&&e.seq<=t.seq){if(e.seq===t.seq&&(0,import_dist$1.compareStructural)(e,t))return;throw Error(`world state seq ${e.seq} for session ${JSON.stringify(e.session)} does not follow the held seq ${t.seq}`)}(0,import_dist$1.runInAction)(()=>this.documents.set(e.session,e)),this.took(e)}of(e){let t=this.documents.get(e);if(t===void 0)throw Error(`no world state for session ${JSON.stringify(e)}: the host hands one in with the config ahead of every request`);return t}drop(e){(0,import_dist$1.runInAction)(()=>this.documents.delete(e))}},UpdateGate=class{newest=null;gate=null;constructor(e){this.gates=e}took(e){if(e.kind===`pending`||this.newest!==null&&e.at<this.newest)return;this.newest=e.at;let t=e.kind===`ok`?updateIdentity(e.value):null;(this.gate?.identity??null)!==t&&(this.gate?.dispose(),this.gate=t===null?null:{identity:t,dispose:this.gates.state.register(UPDATE_DISMISSED_KEY,[t])})}},Watches=class{minted=0;held=new Map;constructor(e){this.host=e}acquire(e,t,n){let r=++this.minted,i={deaf:[],heard:n};return this.held.set(r,i),this.host.watch(r,e,t),{release:()=>{this.held.delete(r)&&this.host.unwatch(r)},get deaf(){return i.deaf}}}follow(e,t,n){return followWatch(e,t,(e,t)=>this.acquire(e,t,n))}pushed(e,t,n){let r=this.held.get(e);if(r===void 0)return;let i=!(0,import_dist$1.compareStructural)(r.deaf,n);r.deaf=n;let a=t??(i?{kind:`unknown`}:null);a!==null&&r.heard(a)}};function sessionSource(e){return({sessionId:t,state:n,store:r,requested:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>resolveEffectiveGlobals(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.compose`,`computed`,()=>{let{hookData:t,hints:n}=i();return{hookData:t,hints:n,home:e.home}}),c=r.derive(`session.draw`,`computed`,()=>({sources:[...n.sources.keys()],effective:o.read(),configFacts:{...settingCounts(n.config,n.fileHeldSettings,a),configPath:n.configPath,layers:layerFlags(n.writable)},history:e.history(t),back:e.navigation(t,n.config)})),l=()=>e.worldStates.of(t),u=r.derive(`session.payload`,`computed`,()=>composePayload(l(),s.read(),c.read()));return{session:t,payload:()=>u.read(),effective:()=>c.read().effective,facts:l,run:e=>l().runs[e]??UNREAD_RUN,hints:()=>s.read().hints,failure:()=>stampFailureOf(l()),selections:()=>c.read().effective}}}function*variablesOf(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*templatesOf(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 presetNames(e.presets)){for(let n of walkNodes(presetRoot(e,t).node))n.when!==void 0&&(yield n.when);let n=presetGlobals(e,t);for(let e of EXPRESSION_SLOTS){let t=n[e];isExpression(t)&&(yield t)}}for(let[,t]of variablesOf(e))for(let[,e]of variableTemplates(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of actionTemplates(t))yield e}function unusedDeclarations(e,t,n){let r=valueReadsOf(t),i=new Set,a=new Set,o=new Set;for(let e of templatesOf(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of templateActionRefs(e,t.helpers))a.add(n);for(let n of templateHelperRefs(e,t.helpers))o.add(n)}for(let[,e]of variablesOf(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 presetNames(t.presets))for(let n of walkNodes(presetRoot(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=>!isReservedName(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(variablesOf(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))]}const ENTRY_BYTES=3*1024*1024,COMPILE_BYTES=10*1024*1024,VIEW_BYTES=2.5*1024*1024,RENDER_CACHE_RESERVE_BYTES=96*1024*1024;function renderCacheBudget(e){return Math.floor(Math.max(e/4,e*NEAR_LIMIT-RENDER_CACHE_RESERVE_BYTES))}const MAX_ENTRIES=256;function pluginLoadLine(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[pluginDataVar(pluginNs(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[pluginNs(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>ownedBy(e)(t)&&t!==pluginDataVar(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${chainName(e,`<default>`)}: projections=${[...projectionsOf(n).keys()].join(`,`)||`-`} instantSegments=${instantSegments(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 heardField=e=>{switch(e.kind){case`changed`:return e.paths.join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},causeField=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${heardField(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function configLoadedLine(e,t,n){let r=e=>valueOf$1(e.join(`,`)||`-`);return`config loaded projectDir=${valueOf$1(e.projectDir)} cwd=${valueOf$1(e.cwd)} cause=${valueOf$1(causeField(t))} state=${n} files=${valueOf$1(chainName(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 configDisposeLine(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function cacheKey(e,t,n){return e+`\0`+t+`\0`+(n??``)}function authoredRoots(e,t){return new Set(presetNames(e.presets).filter(n=>presetRoot(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function watchTargetsFor(e,t){let{loaded:n,dropped:r,unreached:i}=e.state.plugins,a=[...new Set([...e.state.plugins.roots,path.join(e.projectDir,REPO_PLUGIN_DIR)])];return watchTargetsOf({named:[...dslConfigCandidatePaths(t,{projectDir:e.projectDir,configFile:e.configFile}),...a,...n.map(e=>e.path),...[...r,...i].map(e=>e.path),...new Set(e.state.sources.values())],whole:a})}function joinWarnings(e){return e.filter(Boolean).join(`
|
|
230
|
+
`)||null}const thrown=e=>e instanceof Error?e.message:String(e);function plugins(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function loadKey(e){let{loaded:t,chain:n}=e;return digestOf({cwd:e.cwd,chain:{layers:n.layers,home:n.home,writable:n.writable,repo:n.repo,locs:n.locs},loaded:{layers:t.layers.map(e=>({path:e.path,raw:e.raw,config:e.config,plugins:plugins(e.plugins),source:null,warnings:null})),base:t.base,installed:{...plugins(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])})}function declaredSources(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))r.kind===`source`&&t.set(n,r.storage);return t}function resolveLoad(e,t){let n=[];try{let r=loadConfigChain(t.locs,t.layers,DEFAULT_DSL_CONFIG,{warned:e=>n.push(...e)},{repo:t.repo,cwd:e}),i={cwd:e,chain:t,loaded:r,sources:declaredSources(r.config)};return{kind:`resolved`,...i,key:loadKey(i),warnings:n}}catch(e){return e instanceof ConfigError&&n.push(...e.warnings),{kind:`failed`,cause:e,warnings:n}}}function buildRenderState(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??DEFAULT_DSL_CONFIG,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new VariableStore(t.clock),m=new SourceRegistry(p,o.globals.default_empty_value??``,t.sessionState,null,t.env),h;try{h=registerCompiled(o,m,n,t.compile??compileAlone(t.signer),DIRECTORY_SCOPE),f.push(...h.loadWarnings);let e=m.view();f.push(...declareDslVariables(o,e,n,VIEW_SCOPE)),e.dispose(),t.gates.state.gateFor(o),t.gates.config.gateFor(o)}catch(e){return m.dispose(),e instanceof ConfigError&&f.push(...e.warnings),{kind:`failed`,cause:e,warnings:f}}return{kind:`built`,state:{config:o,dropped:c,compileKey:h.compileKey,loadKey:e.key,buildWarnings:f,store:p,registry:m,compiled:h.compiled,authoredRoots:authoredRoots(l,u),fileHeldSettings:fileHeldSettings(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,writable:r.writable,unused:[...new Map(a.flatMap(e=>unusedDeclarations(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 settle(e,t,n,r,i){let a={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:elapsedMs(i,e.started)},o=t=>joinWarnings([...e.advisories,...n,...t]);switch(r.kind){case`built`:case`kept`:return{...a,kind:r.kind,warning:o(r.state.buildWarnings),state:r.state,error:null};case`failed`:return{...a,kind:`failed`,warning:o(r.warnings),state:null,error:thrown(r.cause),cause:r.cause}}}function loadChain(e,t,n,r,i=null){let a=resolveLoad(t,n);if(a.kind===`failed`)return settle(e,n,[],a,r.clock);let o=i?.loadKey===a.key?{kind:`kept`,state:i}:buildRenderState(a,r);return settle(e,n,a.warnings,o,r.clock)}function loadFromDisk(e,t,n,r,i=null){let a=r.clock.monotonic(),o=resolveDslConfig(r.locations,repoConfigs(r.stateDir).read(),{projectDir:e,configFile:n}),{repos:s}=o,c={layers:o.kind===`chain`?o.layers:[],home:o.home,writable:writableRoles(o,{projectDir:e,configFile:n}),repo:s.plugins,locs:r.locations};return loadChain({repos:s,advisories:[detectConfigCollisions(r.locations,e),configResolutionNotice(o),repoUnreadNotice(s)],started:a},t,c,r,i)}function fallbackState(e,t,n){let r=resolveLoad(e,{layers:[],home:``,writable:[`user`],repo:t,locs:n.locations}),i=r.kind===`failed`?r:buildRenderState(r,n);if(i.kind===`failed`)throw Error(`bundled default failed to load: ${thrown(i.cause)}`,{cause:i.cause});return i.state}const DIRECTORY_SCOPE=new Set([`directory`]),VIEW_SCOPE=new Set([`view`]);function openView(e,t,n,{source:r,changed:i,log:a}){let o=n.hookData.session_id,s=e.registry.view();declareDslVariables(e.config,s,t,VIEW_SCOPE);let c=import_dist$1.observable.box(n,{deep:!1}),l;try{l=r({sessionId:o,state:e,store:s.variableStore,requested:()=>c.get()})}catch(e){throw s.dispose(),e}bindView(e.compiled,s.variableStore,s,l);let u=(0,import_dist$1.reaction)(()=>[l.payload(),l.selections(),s.published(),e.registry.published()],()=>i(o),{equals:import_dist$1.compareShallow,fireImmediately:!0,onError:e=>a(`error`,`session view change threw sid=${JSON.stringify(o)}: ${String(e)}`)});return{sessionId:o,state:e,store:s.variableStore,registry:s,source:l,requested:e=>{e!==c.get()&&(0,import_dist$1.runInAction)(()=>c.set(e))},facts:()=>c.get(),lastRenderCellsBySegment:new Map,retire:u,dispose:()=>(u(),s.dispose())}}const subscriptionsOf=({state:e,registry:t})=>[...[...e.sources].map(([e,t])=>({kind:`plugin`,source:e,folder:t})),...t.subscriptions().map(e=>({kind:`run`,run:e}))];var RenderCache=class{entries=new Map;answersWatch;lifetime=new AbortController;closing=this.lifetime.signal;get closed(){return this.closing.aborted}due=new Map;walk=null;holds=new Map;storageHolds=0;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??quietLogger,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},fs.mkdirSync(repoConfigsDir(e.stateDir),{recursive:!0});let{dir:n,name:r}=nearestWatchTarget(repoConfigsPath(e.stateDir));this.answersWatch=e.watchers.acquire(`repo-configs:${n}/${r}`,{dirs:[{path:n,filenames:[r]}]},e=>this.reloadEvery({kind:`answers-watch`,heard:e}))}compileOf(e,t){return this.compiles.get(e)??compileDslConfig(t,this.deps.signer)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*ENTRY_BYTES+e.size*COMPILE_BYTES+this.views.size*VIEW_BYTES}getOrCreate(e,t,n){let r=cacheKey(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`,pluginLoadLine(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??fallbackState(t,a.repos.plugins,this.deps),watch:null};return this.serve(o.state),this.entries.set(r,o),this.holdFolders(o.state),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=${mb(this.accountedBytes())}/${mb(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++;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 this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}pin(e){this.pins.set(e,(this.pins.get(e)??0)+1);let t=!1;return()=>{if(t)throw Error(`render-cache pin released twice`);t=!0;let n=(this.pins.get(e)??0)-1;n>0?this.pins.set(e,n):this.pins.delete(e)}}viewOf(e,t,n,r){let i=n.hookData.session_id,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;try{o=this.opened(e,t,n,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),o}opened(e,t,n,r){let i=n.hookData.session_id,a;try{a=openView(t,e.cwd,n,{source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(i,{error:e}),e}return this.openFailures.delete(i),this.views.set(i,a),this.viewHolds.set(a,{entry:e,holders:0,retired:null}),this.log(`info`,`session view opened sid=${JSON.stringify(i)} by=${r} cwd=${e.cwd} views=${this.views.size}`),a}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}`))}retireSession(e){this.openFailures.delete(e);let t=this.views.get(e);t!==void 0&&this.retireView(t,`idle`)}subscriptions(){return{sources:Object.fromEntries([...this.views].map(([e,t])=>[e,subscriptionsOf(t)]))}}close(){if(this.closed)return;this.lifetime.abort(Error(`the render cache closed`)),this.walk?.(),this.walk=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 loadFromDisk(e,t,n,this.deps,r)}drop(e,t,n){t.watch?.held.handle.release(),this.entries.delete(e),this.due.delete(t),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,due:this.due.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=${mb(this.accountedBytes())}/${mb(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,{id:++this.storageHolds,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}`)}holdFolders(e){this.deps.storage.hold(this.holdOf(e).id,[...e.sources.values()])}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(),`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.deps.storage.release(t.id),this.log(`info`,configDisposeLine(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){this.due.delete(e);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`,pluginLoadLine(i.layers,i.state,i.ms)),i.kind===`built`&&(e.state=i.state,this.serve(i.state)),this.holdFolders(e.state),i.kind===`built`&&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.due.set(t,e);this.armWalk()}armWalk(){this.walk!==null||this.due.size===0||(this.walk=this.deps.clock.defer(()=>this.walkOne()))}walkOne(){this.walk=null;let e=null;for(let t of this.entries.values()){let n=this.due.get(t);n!==void 0&&(e=[t,n])}if(e===null)return;let[t,n]=e;try{this.reloadInto(t,n)}catch(e){this.log(`error`,`every-entry reload threw projectDir=${valueOf$1(t.projectDir)} cwd=${valueOf$1(t.cwd)} configFile=${valueOf$1(t.configFile??`-`)} cause=${valueOf$1(causeField(n))}: ${inspect(e)}`)}finally{this.armWalk()}}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.repos=t.repos;let n=watchTargetsFor(e,this.deps.locations),{targets:r,unresolved:i}=n,a=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${n.key}`,{watch:o,move:s}=this.deps.watchers.follow(e.watch?.held??null,{...n,key:a},t=>this.reloadInto(e,{kind:`config-watch`,heard:t}));if(e.watch={derived:{...n,key:a},held:o},s!==`kept`){this.log(`info`,`config watch bound projectDir=${e.projectDir} cwd=${e.cwd} dirs=${r.dirs.map(e=>e.path).join(`,`)}`);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)}};function buildDebugSnapshot(e,t){switch(e){case`vars`:return{what:e,vars:introspectVars(t)};case`segments`:return{what:e,segments:introspectSegments(t)};case`config`:return{what:e,config:introspectConfig(t)}}}function introspectVars(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=buildSourceKindIndex(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=valueOf(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:ageFromNode(r.lastUpdatedMs(),t.clock)})}return o}function valueOf(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 ageFromNode(e,t){return e===null?null:Math.max(0,t.now()-e)}function buildSourceKindIndex(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,sourceKindOf(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}`,sourceKindOf(i));return t}function sourceKindOf(e){return e.kind}function introspectSegments(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=orderedSegmentNames(n),o=placementsBySegment(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:extractReferencedVars(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function placementsBySegment(e){let t=new Map;for(let n of presetNames(e.presets))for(let r of walkNodes(presetRoot(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=placementId(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function orderedSegmentNames(e){let t=[],n=new Set;for(let r of walkNodes(rootNode(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 extractReferencedVars(e,t,n){let r=new Set([...templateReads(e,t).keys()].flatMap(e=>variableRead(e,n)));return Array.from(r).sort()}function introspectConfig(e){return e===null?null:e.config}const DEBUG_RENDER_OPTS={endcaps:floorOf(`endcaps`),colorCompatibility:floorOf(`colorCompatibility`),wrap:floorOf(`autoWrap`),padding:floorOf(`padding`),width:1/0},EMPTY_RENDER_MAP=new Map;function serializeSegmentCells(e,t){let n=new Map;for(let[r,i]of e)n.set(r,renderStripCells(i,{...DEBUG_RENDER_OPTS,colorCompatibility:t}));return n}function rendererOf(e){function t(t){return t.kind===`event`?e.event(t):e.adapter(t)}return{answer:t}}const DAEMON_WIDE=`journals`,GATHERS=`gathers`;var JournalTurns=class{queue=new KeyedSerialQueue;sessions=new KeyedSerialQueue;gathers=new KeyedSerialQueue;open=!0;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(DAEMON_WIDE,async()=>{await this.deps.changesLanded(),this.queued--;let a=this.deps.monotonic();t(spanMs(i,a)),this.holder={verb:e,since:a};try{if(this.refuseClosed(e),await n())throw new ClickAbandoned(e);return this.refuseClosed(e),await r({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(elapsedMs(this.deps,c)),this.refuseClosed(e),await i())throw new ClickAbandoned(e);this.refuseClosed(e);let t=this.deps.monotonic(),l=await o();a(elapsedMs(this.deps,t));let u=await i();return this.take(e,{waited:r,gone:async()=>!u&&await 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:elapsedMs(this.deps,e.since),queued:t,gathers:this.gathersInFlight}}close(){this.open=!1}refuseClosed(e){if(!this.open)throw new DaemonClosing(e)}},ConfigWrites=class{open=new Map;landing=null;waiting=[];closed=!1;answers=[];constructor(e,t){this.mint=e,this.disk=t}read(e){let t=this.open.get(e);return t===void 0?this.disk(e):t.after}land(e,t,n){let r=this.open.get(e);this.open.set(e,{before:r===void 0?t:r.before,after:n})}answer(e,t){this.answers.push({dir:e,answer:t})}seal(e,t,n){let r=this.answers;if(this.answers=[],this.closed)return this.open.clear();let i=[...this.open].flatMap(([e,{before:t,after:n}])=>{let r=diffChanges(t,n);return r.length===0?[]:[{path:e,list:r}]}),a=i.map(({path:e})=>e);if(this.open.clear(),i.length===0&&r.length===0)return n(e);if(t===null)throw Error(`a click with no session wrote ${[...a,...r.map(e=>`the answer for ${e.dir}`)].join(`, `)}`);let o=[...i.map(({path:e,list:n})=>({kind:`change`,id:this.mint(),session:t,target:{kind:`layer`,path:e},changes:n})),...r.map(({dir:e,answer:n})=>({kind:`approve-repo`,id:this.mint(),session:t,dir:e,answer:n}))];this.landing={of:{session:t,files:a,answered:r.length>0,consequence:n},owed:new Set(o.map(e=>e.id)),missed:null},e.push(...o)}settled(e,t){let n=this.landing;if(!(n===null||!n.owed.delete(e))){if(t.kind!==`ok`&&(n.missed??=t),n.owed.size>0)return`owed`;this.landing=null;for(let e of this.waiting.splice(0))e();return{...n.of,outcome:n.missed??{kind:`ok`}}}}close(){this.closed=!0}landed(){return this.landing===null?Promise.resolve():new Promise(e=>this.waiting.push(e))}};function mainRenderer(e,t){let n=new Map,r={sources:{},tmuxStatus:[]},i=async(t,r,i,a)=>{switch(t.kind){case`start`:for(let{context:n,worldState:a}of t.sessions)configureSession(e,n,a,r,i);return;case`config`:configureSession(e,t.context,t.worldState,r,i);return;case`request`:{let{frame:o,delivered:s}=await answerRequest(e,t.context,r,t.waitMs,{following:new Set(t.following),feeds:t.feeds,idleSince:t.idleSince},i,a),c=e.mint();n.set(c,s),a.push({kind:`present`,id:c,session:t.context.hookData.session_id,surface:`statusline`,request:t.id,frame:o});return}case`world-state`:e.worldStates.take(t.worldState);return;case`retire`:retireSession(e,t.session);return;case`effect-done`:{if(e.verbs.changeDone(t.of,t.outcome,a)||e.acts.done(t.of,t.session,t.outcome))return;let r=n.get(t.of);if(r===void 0)throw Error(`effect-done for effect ${t.of}, which is no present, change or act on its way`);n.delete(t.of),t.outcome.kind===`ok`&&r();return}case`click`:await clickTurn(e,t,i,a);return;case`menu-idle`:await e.verbs.closeIdle(t.session,t.latest,{...t.idle,confirm:()=>e.menuIdle.confirmClose(t.session,t.idle.firedAt)},a);return}};return rendererOf({adapter:async e=>{try{return{kind:`replied`,reply:t(e.push,e.at)}}catch(e){return{kind:`threw`,failure:failureOf(e)}}},event:async t=>{let n=[],a=e.clock.monotonic(),o=[];return{...await i(t.event,t.at,n,o).finally(()=>{let{sources:t}=e.renderCache.subscriptions();r={sources:t,tmuxStatus:Object.keys(t).filter(t=>viewLanes(e,t)?.tmuxStatus===!0)}}).then(()=>({kind:`answered`}),e=>({kind:`threw`,failure:failureOf(e)})),effects:o,record:n,subscriptions:r,turnMs:elapsedMs(e.clock,a)}}})}function loadMainRenderer(e){let t=new SessionState(e.storage.session),n=e.storage.history.load();return{start:r=>startOver(e,t,n,r)}}function startOver(e,t,n,r){let{clock:i,now:a,gates:o,linkSigner:s}=e,{log:c}=r,l=new SettingsHistory(t,c,e.storage.history,n),u=0,d=()=>++u,f=new ConfigWrites(d,readConfigText),p=(e,n)=>holdClickError(t,e,n,a()),m=new ActsOnTheirWay(d,p),h=new LaneActs({ask:(e,t)=>m.ask(e,t),refused:p,log:c}),g=new JournalTurns({monotonic:()=>i.monotonic(),changesLanded:()=>f.landed()}),_=new NavigationHistory,v=new EffectSessions,y=new RenderWarningRecords,b=new UpdateGate(o),x=new WorldStates(e=>b.took(e.daemon.update.newer)),S=new Watches(r.watches),C=new RenderCache({clock:i,stateDir:e.stateDir,locations:e.locations,env:e.env,sessionState:t,watchers:S,log:c,storage:r.storage,signer:s,gates:o,source:sessionSource({sessionState:t,worldStates:x,home:e.home,history:e=>l.depth(e),navigation:(e,n)=>_.depth(e,t,o.state.gateFor(n))})},{budgetBytes:()=>renderCacheBudget(e.memoryLimitBytes),observers:{onReload:(e,t,n,i)=>{c(`info`,configLoadedLine(e,n,i));for(let e of t)r.wake(e,`reload`)},onViewChanged:e=>r.wake(e,`data`)}}),w={...r,clock:i,linkSigner:s,sessionState:t,renderCache:C,worldStates:x,renderWarnings:y,effectSessions:v,laneActs:h},T=e=>C.reload(e.projectDir,e.cwd,e.target.path,{kind:`write`}),{install:E,...D}=r.doctor,O={gates:o,sessionState:t,stateDir:e.stateDir,locations:e.locations,journalTurns:g,configWrites:f,clickLanded:e=>r.menuIdle.clicked(e,a()),log:c,acts:m,now:a,doctor:{...D,loadConfig:e=>{let t=[e.projectDir,e.cwd,e.target.path];C.reload(...t,{kind:`doctor`});let n=C.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}},home:e.home,managedSettingsDir:claudeManagedSettingsDirIn(e.env)},installFacts:E,doctorStores:e.storage.doctor,clients:r.renderSightings,bundle:e.bundle,serving:r.serving,history:l,navigation:_,configFor:e=>C.getOrCreate(e.projectDir,e.cwd,e.target.path).state.config,reloadConfig:T,sourcesFor:e=>C.getOrCreate(e.projectDir,e.cwd,e.target.path).state.sources,links:s,lanes:{of:(e,t,n)=>lanesAt(w,e,t,n),clicked:(e,t,n,r,i)=>h.clicked(e,t,n,r,i)},diagnosticCopy:(e,t,n)=>C.drawnCopy(e,t,n)},k=new Map,A=e=>{if(k.has(e))throw Error(`pin of session ${e}, whose feed is pinned`);let n=C.pin(e),i=(0,import_dist$1.reaction)(()=>t.revision(e),()=>r.wake(e,`state`));k.set(e,()=>{i(),C.stopDrawing(e,`feed`),n()})},j=e=>{let t=k.get(e);if(t===void 0)throw Error(`unpin of session ${e}, whose feed is not pinned`);k.delete(e),t()},M=(e,n)=>{switch(e.kind){case`frame`:return{kind:`frame`,frame:renderFrame(w,e.session,e.fps,n,{following:new Set(e.following),feeds:e.feeds,idleSince:e.idleSince})};case`lanes`:return{kind:`lanes`,lanes:viewLanes(w,e.session)};case`pin`:return A(e.session),{kind:`pin`};case`unpin`:return j(e.session),{kind:`unpin`};case`stats`:return{kind:`stats`,stats:{renderCache:C.stats,effectCache:v.getStats(),sessionState:{sessions:t.size(),observers:t.observers(),revision:t.latestRevision()},journalTurns:g.getStats()}};case`debug`:return{kind:`debug`,snapshot:debugOf(C.latestView(),e.what)};case`watch`:return S.pushed(e.id,e.heard,e.deaf),{kind:`watch`};case`reload-every`:return C.reloadEvery({kind:`events-resumed`,since:e.since}),{kind:`reload-every`};case`reload-config`:return T(e.origin),{kind:`reload-config`};case`close-journal`:return g.close(),f.close(),{kind:`close-journal`};case`close-views`:return C.close(),{kind:`close-views`};case`close-session-state`:return t.close(),{kind:`close-session-state`}}};return mainRenderer({...w,verbs:verbsOver(O,r.clicks),mint:d,acts:m},M)}function debugOf(e,t){return buildDebugSnapshot(t,e===null?null:{store:e.store,registry:e.registry,config:e.state.config,compiled:e.state.compiled,lastRenderBySegment:t===`segments`?serializeSegmentCells(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??floorOf(`colorCompatibility`)):EMPTY_RENDER_MAP})}function bootEnv(e){return Object.fromEntries(Object.entries(e).flatMap(([e,t])=>t===void 0?[]:[[e,t]]))}const REACH_KINDS={wake:`notice`,log:`notice`,doctor:{probeTmux:`call`,remoteLogin:`call`,fontInUse:`call`,daemons:`call`,forge:`call`,transcript:`call`,install:`call`},menuIdle:{clicked:`notice`,clickArrived:`notice`,clickSettled:`notice`,observe:`notice`,confirmClose:`call`},clicks:{gone:`call`},serving:`call`,renderSightings:{ofSession:`call`},eventAnswered:`notice`,watches:{watch:`notice`,unwatch:`notice`},storage:{hold:`notice`,release:`notice`}};function reachesOf(e,t=``){return Object.entries(e).flatMap(([e,n])=>typeof n==`string`?[[`${t}${e}`,n]]:reachesOf(n,`${t}${e}.`))}const REACHES=reachesOf(REACH_KINDS);function reachAt(e,t){let n=t.split(`.`).reduce((e,t)=>e?.[t],e);if(typeof n!=`function`)throw Error(`the renderer reached ${t}, which the host has not`);return n}function lineSplitter(e){let t=``;return{push:n=>{let r=0,i=n.indexOf(`
|
|
228
231
|
`);for(;i!==-1;){let a=t+n.slice(r,i);t=``,e(a),r=i+1,i=n.indexOf(`
|
|
229
232
|
`,r)}t+=n.slice(r)},end:()=>{if(t===``)return;let n=t;t=``,e(n)}}}function rendererOverLines(e){let{send:t,host:n}=e,r=new Map,i=0,a=null,o=(e,n,o)=>new Promise((s,c)=>{if(a!==null){c(a);return}let l=++i;r.set(l,{what:e,settle:e=>o(e,s,c),fail:c}),t(n(l))}),s=e=>o(e.kind===`event`?`${e.event.kind} input`:`${e.push.kind} push`,t=>({kind:`input`,n:t,input:e}),(e,t,n)=>{if(e.kind===`output`)t(e.output);else if(e.kind===`rejected`)n(new CrossedFailure(e.failure));else return!1;return!0}),c=rendererOf({event:e=>s(e),adapter:e=>s(e)}),l=(e,t)=>reachAt(n,e)(...t),u=(e,t)=>{try{return Promise.resolve(l(e,t))}catch(e){return Promise.reject(e)}};return{renderer:c,ping:()=>o(`a ping`,e=>({kind:`ping`,n:e}),(e,t)=>e.kind===`ping`?(t(e.usage),!0):!1),heapSnapshot:e=>o(`a heap snapshot`,t=>({kind:`heap-snapshot`,n:t,file:e}),(e,t,n)=>e.kind===`heap-snapshot`?(e.written.kind===`ok`?t():n(new CrossedFailure(e.written.failure)),!0):!1),heard:n=>{if(a!==null){e.fault(`renderer said ${n.kind} after its end (${a.message})`);return}switch(n.kind){case`notice`:try{l(n.reach,n.args)}catch(t){e.fault(`renderer notice ${n.reach} threw: ${failureOf(t).detail}`)}return;case`call`:u(n.reach,n.args).then(e=>({kind:`ok`,value:e}),e=>({kind:`failed`,failure:failureOf(e)})).then(e=>a===null?t({kind:`returned`,n:n.n,returned:e}):void 0);return;case`output`:case`rejected`:case`ping`:case`heap-snapshot`:{let t=r.get(n.n);if(t===void 0){e.fault(`renderer answered ${n.kind} ${n.n}, owed nothing`);return}r.delete(n.n),t.settle(n)||t.fail(Error(`renderer answered ${t.what} with ${n.kind}`));return}case`started`:case`refused`:e.fault(`renderer said ${n.kind} after its boot`);return}},ended:e=>{a??=e;let t=[...r.values()];r.clear();for(let n of t)n.fail(e)}}}function hostOverLines(e){let t=new Map,n=0,r=(r,i)=>(...a)=>{if(i===`notice`){e({kind:`notice`,reach:r,args:a});return}return new Promise((i,o)=>{let s=++n;t.set(s,{resolve:i,reject:o}),e({kind:`call`,n:s,reach:r,args:a})})},i={};for(let[e,t]of REACHES){let n=e.split(`.`),a=n.pop(),o=n.reduce((e,t)=>e[t]??={},i);o[a]=r(e,t)}return{host:i,returned:(e,n)=>{let r=t.get(e);if(r===void 0)throw Error(`the host returned call ${e}, which is not waiting`);t.delete(e),n.kind===`ok`?r.resolve(n.value):r.reject(new CrossedFailure(n.failure))}}}function serveRenderer(e){let{renderer:t,send:n}=e;return r=>{switch(r.kind){case`input`:t.answer(r.input).then(e=>n({kind:`output`,n:r.n,output:e}),e=>n({kind:`rejected`,n:r.n,failure:failureOf(e)}));return;case`returned`:e.host.returned(r.n,r.returned);return;case`ping`:n({kind:`ping`,n:r.n,usage:e.memory()});return;case`heap-snapshot`:{let t;try{e.heapSnapshot(r.file),t={kind:`ok`}}catch(e){t={kind:`failed`,failure:failureOf(e)}}n({kind:`heap-snapshot`,n:r.n,written:t});return}case`boot`:throw Error(`a second boot`)}}}function processTable(e){let t=new Map;for(let n of e.split(`
|
|
230
233
|
`)){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*lineage(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)}
|
|
@@ -519,7 +522,7 @@ function run(argv) {
|
|
|
519
522
|
`)+`
|
|
520
523
|
`}function formatConfig(e){return e===null?`config: DSL not active
|
|
521
524
|
`:JSON.stringify(e,null,2)+`
|
|
522
|
-
`}function fmtValue(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function fmtAge(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}const EXIT_VALID=0,EXIT_USAGE$2=2;function loadSchemaText(){let e=locateSchema();return e===null?null:fs.readFileSync(e,`utf-8`)}function schemaPlan(){let e;try{e=loadSchemaText()}catch(e){return{stdout:``,stderr:`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`,code:EXIT_USAGE$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:EXIT_USAGE$2}:{stdout:e,stderr:``,code:EXIT_VALID}}function locateSchema(){let e=path.join(`schema`,`cc-candybar.schema.json`),t=process$1.argv[1];if(t===void 0)return null;let n=path.dirname(path.resolve(t));for(;;){let t=path.join(n,e);if(fs.existsSync(t))return t;let r=path.dirname(n);if(r===n)return null;n=r}}var CheckRuns=class{holds=new Holds;lanes=import_dist$1.observable.map(void 0,{deep:!1});answered=new Map;thrown=import_dist$1.observable.box(null,{deep:!1});stop;constructor(e,t,n){this.registry=t,this.at=n,this.stop=(0,import_dist$1.reaction)(()=>t.subscriptions(),t=>{let{result:n}=this.holds.declare(()=>declareRuns(e,this.holds,new Map(t.map(e=>[e.digest,judgeRun(e)])),(e,t)=>t()));for(let e of this.answered.keys())n.has(e)||this.answered.delete(e);(0,import_dist$1.runInAction)(()=>this.lanes.replace([...n]))},{fireImmediately:!0,onError:e=>(0,import_dist$1.runInAction)(()=>this.thrown.set({error:e}))})}run(e){let t=this.lanes.get(e);if(t===void 0)return UNREAD_RUN;let n=t.current(),r=t.fault(),i=this.answered.get(e);if(i?.from===n&&i.fact.fault===r)return i.fact;let a={reading:restamp(void 0,n,this.at),fault:r};return this.answered.set(e,{from:n,fact:a}),a}async settled(e){for(;!e.aborted&&this.awaited().length>0;)try{await(0,import_dist$1.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}return this.awaited()}awaited(){let e=this.thrown.get();if(e!==null)throw e.error;return[...this.registry.namedRuns()].filter(([,e])=>awaitedReading(this.run(e.digest).reading)).map(([e])=>e)}close(){this.stop(),this.holds.close()}};const CHECK_WIDTH=200,SOURCE_SETTLE_MS=5e3;function settleWindow(e,t){return{ms:t,signal:timeoutSignal(e,t)}}function stragglers(e,t){return t.length===0?[]:[`source${t.length===1?``:`s`} still running after ${e.ms} ms, drawn as pending: ${t.join(`, `)}`]}function bindPass({layers:e,config:t,compiled:n,store:r,registry:i,runs:a},o,s,c){let l=renderOptionsOf(o,s);return{drawn:bindPayload(n,r,i,checkPayload(t,o,e.at(-1)??null,c),l,o,CHECK_SESSION,e=>a.run(e)),opts:l}}const CHECK_HOME=`/home/tester`,CHECK_SESSION=sessionIdOf(`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`),CHECK_HINTS={tmux:{socket:`/tmp/tmux.sock`,pane:`%0`,truecolor:null},ssh:!0};function checkHook(e){let t=Math.floor(e);return{hook_event_name:`Status`,session_id:CHECK_SESSION,version:`1.15.0`,cwd:`${CHECK_HOME}/code/cc-candybar/src`,transcript_path:`${CHECK_HOME}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:{current_dir:`${CHECK_HOME}/code/cc-candybar/src`,project_dir:`${CHECK_HOME}/code/cc-candybar`,added_dirs:[]},cost:{total_cost_usd:.39,total_duration_ms:93e4,total_api_duration_ms:4200,total_lines_added:512,total_lines_removed:88},context_window:{total_input_tokens:241400,total_output_tokens:0,context_window_size:1e6,used_percentage:76,remaining_percentage:24,current_usage:{input_tokens:48487,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}},rate_limits:{five_hour:{used_percentage:63,resets_at:t+2*3600},seven_day:{used_percentage:21,resets_at:t+5*86400}}}}function checkReadings(e,t){let n=Math.floor(t),r=Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]);return{lanes:{git:ok$1({branch:`main`,status:`dirty`,aheadBehind:ok$1({ahead:2,behind:1}),head:ok$1(`abc1234def5678`),workingTree:{staged:3,unstaged:2,untracked:1,conflicts:0},sha:ok$1(`abc1234`),operation:ok$1(`rebase`),committedAt:ok$1(n-780),stashCount:ok$1(1),upstream:ok$1(`origin/main`),repoName:ok$1(`cc-candybar`),repoUrl:ok$1(`https://github.com/promptctl/cc-candybar`),pullRequest:ABSENT$2}),usage:ok$1({calculatedCost:.39,tokens:241400,tokenBreakdown:null}),context:ok$1(48487),metrics:ok$1({lastResponseTime:8.2,messageCount:8,nonPrompts:0}),activity:ABSENT$2,tmuxSession:ok$1(`work`),hostName:ok$1(`tester-box`),hostUser:ok$1(`tester`),cache:ok$1(n+900),speed:ABSENT$2,autoCompact:ok$1(4e5),sources:new Map(r.map(e=>[e,ABSENT$2])),runs:new Map},today:ok$1({sums:oneDay(t,12.5,34e5),own:{}}),faults:[]}}function checkPayload(e,t,n,r){let i=checkHook(r),a=assembleFacts(void 0,CHECK_SESSION,checkReadings(e,r),{update:{newer:{...ABSENT$2,at:r},act:IDLE,actsError:null},fileEvents:[],launcher:[],rendererEnded:null,actFailed:null},r),{term:o,...s}=composePayload(a,{hookData:i,hints:CHECK_HINTS,home:CHECK_HOME},{sources:Object.keys(a.sources),effective:t,configFacts:{unsaved:1,resettable:perSetting(()=>!0),themeDefault:t.theme.kind===`decided`?{differs:!0,theme:t.theme.name}:{differs:!1},configPath:n??`${CHECK_HOME}/.config/cc-candybar/config.json5
|
|
525
|
+
`}function fmtValue(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function fmtAge(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}const EXIT_VALID=0,EXIT_USAGE$2=2;function loadSchemaText(){let e=locateSchema();return e===null?null:fs.readFileSync(e,`utf-8`)}function schemaPlan(){let e;try{e=loadSchemaText()}catch(e){return{stdout:``,stderr:`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`,code:EXIT_USAGE$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:EXIT_USAGE$2}:{stdout:e,stderr:``,code:EXIT_VALID}}function locateSchema(){let e=path.join(`schema`,`cc-candybar.schema.json`),t=process$1.argv[1];if(t===void 0)return null;let n=path.dirname(path.resolve(t));for(;;){let t=path.join(n,e);if(fs.existsSync(t))return t;let r=path.dirname(n);if(r===n)return null;n=r}}var CheckRuns=class{holds=new Holds;lanes=import_dist$1.observable.map(void 0,{deep:!1});answered=new Map;thrown=import_dist$1.observable.box(null,{deep:!1});stop;constructor(e,t,n){this.registry=t,this.at=n,this.stop=(0,import_dist$1.reaction)(()=>t.subscriptions(),t=>{let{result:n}=this.holds.declare(()=>declareRuns(e,this.holds,new Map(t.map(e=>[e.digest,judgeRun(e)])),(e,t)=>t()));for(let e of this.answered.keys())n.has(e)||this.answered.delete(e);(0,import_dist$1.runInAction)(()=>this.lanes.replace([...n]))},{fireImmediately:!0,onError:e=>(0,import_dist$1.runInAction)(()=>this.thrown.set({error:e}))})}run(e){let t=this.lanes.get(e);if(t===void 0)return UNREAD_RUN;let n=t.current(),r=t.fault(),i=this.answered.get(e);if(i?.from===n&&i.fact.fault===r)return i.fact;let a={reading:restamp(void 0,n,this.at),fault:r};return this.answered.set(e,{from:n,fact:a}),a}async settled(e){for(;!e.aborted&&this.awaited().length>0;)try{await(0,import_dist$1.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}return this.awaited()}awaited(){let e=this.thrown.get();if(e!==null)throw e.error;return[...this.registry.namedRuns()].filter(([,e])=>awaitedReading(this.run(e.digest).reading)).map(([e])=>e)}close(){this.stop(),this.holds.close()}};const CHECK_WIDTH=200,SOURCE_SETTLE_MS=5e3;function settleWindow(e,t){return{ms:t,signal:timeoutSignal(e,t)}}function stragglers(e,t){return t.length===0?[]:[`source${t.length===1?``:`s`} still running after ${e.ms} ms, drawn as pending: ${t.join(`, `)}`]}function bindPass({layers:e,config:t,compiled:n,store:r,registry:i,runs:a},o,s,c){let l=renderOptionsOf(o,s);return{drawn:bindPayload(n,r,i,checkPayload(t,o,e.at(-1)??null,c),l,o,CHECK_SESSION,e=>a.run(e)),opts:l}}const CHECK_HOME=`/home/tester`,CHECK_SESSION=sessionIdOf(`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`),CHECK_HINTS={tmux:{socket:`/tmp/tmux.sock`,pane:`%0`,truecolor:null},ssh:!0};function checkHook(e){let t=Math.floor(e);return{hook_event_name:`Status`,session_id:CHECK_SESSION,version:`1.15.0`,cwd:`${CHECK_HOME}/code/cc-candybar/src`,transcript_path:`${CHECK_HOME}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:{current_dir:`${CHECK_HOME}/code/cc-candybar/src`,project_dir:`${CHECK_HOME}/code/cc-candybar`,added_dirs:[]},cost:{total_cost_usd:.39,total_duration_ms:93e4,total_api_duration_ms:4200,total_lines_added:512,total_lines_removed:88},context_window:{total_input_tokens:241400,total_output_tokens:0,context_window_size:1e6,used_percentage:76,remaining_percentage:24,current_usage:{input_tokens:48487,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}},rate_limits:{five_hour:{used_percentage:63,resets_at:t+2*3600},seven_day:{used_percentage:21,resets_at:t+5*86400}}}}function checkReadings(e,t){let n=Math.floor(t),r=Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]);return{lanes:{git:ok$1({branch:`main`,status:`dirty`,aheadBehind:ok$1({ahead:2,behind:1}),head:ok$1(`abc1234def5678`),workingTree:{staged:3,unstaged:2,untracked:1,conflicts:0},sha:ok$1(`abc1234`),operation:ok$1(`rebase`),committedAt:ok$1(n-780),stashCount:ok$1(1),upstream:ok$1(`origin/main`),repoName:ok$1(`cc-candybar`),repoUrl:ok$1(`https://github.com/promptctl/cc-candybar`),pullRequest:ABSENT$2}),usage:ok$1({calculatedCost:.39,tokens:241400,tokenBreakdown:null}),context:ok$1(48487),metrics:ok$1({lastResponseTime:8.2,messageCount:8,nonPrompts:0}),activity:ABSENT$2,tmuxSession:ok$1(`work`),hostName:ok$1(`tester-box`),hostUser:ok$1(`tester`),cache:ok$1(n+900),speed:ABSENT$2,autoCompact:ok$1(4e5),sources:new Map(r.map(e=>[e,ABSENT$2])),runs:new Map},today:ok$1({sums:oneDay(t,12.5,34e5),own:{}}),faults:[]}}function checkPayload(e,t,n,r){let i=checkHook(r),a=assembleFacts(void 0,CHECK_SESSION,checkReadings(e,r),{update:{newer:{...ABSENT$2,at:r},act:IDLE,actsError:null},fileEvents:[],launcher:[],rendererEnded:null,actFailed:null},r),{term:o,...s}=composePayload(a,{hookData:i,hints:CHECK_HINTS,home:CHECK_HOME},{sources:Object.keys(a.sources),effective:t,configFacts:{unsaved:1,resettable:perSetting(()=>!0),themeDefault:t.theme.kind===`decided`?{differs:!0,theme:t.theme.name}:{differs:!1},configPath:n??`${CHECK_HOME}/.config/cc-candybar/config.json5`,layers:layerFlags(LAYER_ROLES)},history:{undo:1,redo:1,sinceEdit:1},back:1});return{...s,...instantFacts(a.builtins,r)}}function searchedLayers(e,t){let n=configResolutionNotice(e);return n!==null&&t.push(n),e.kind===`chain`?e.layers:[]}async function checkConfig(e,t,n,r=process$1.cwd(),i=SOURCE_SETTLE_MS){let a=[],o=explicitConfigPath(r,n,e.host.home)??null,s=locations(e.host),c=resolveDslConfig(s,repoConfigs(stateDir(e.host)).read(),{projectDir:r,configFile:o??void 0});a.push(...repoGateLines(c.repos));let l=o===null?searchedLayers(c,a):[homeLayer(o)];if(o!==null){let e;try{e=fs.statSync(o,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:o,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:o,message:`not a file`}}let u=detectConfigCollisions(s,r);u!==null&&a.push(u);try{return{kind:`clean`,layers:l,warnings:a,rendered:await loadRegisterRender(e,t,l,{repo:c.repos.plugins},r,a,i)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&l.some(e=>e.path===t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof ConfigError&&a.push(...e.warnings),{kind:`fatal`,layers:l,message:e instanceof ConfigError||e instanceof Error?e.message:String(e),warnings:a})}}async function prepareConfig(e,t,n,r,i,a,o=SOURCE_SETTLE_MS){let s=t.map(e=>e.path),c=loadConfigChain(locations(e.host),t,DEFAULT_DSL_CONFIG,{warned:e=>i.push(...e)},{...n,cwd:r});refuseDrops(c.dropped);let{config:l}=c,u=new VariableStore(e.clock),d=new SourceRuns({launcher:e.launcher,clock:e.clock}),f=new SourceRegistry(u,l.globals.default_empty_value??``,new SessionState,null,e.host.env),p=new CheckRuns(d,f,a),m=()=>{f.dispose(),p.close(),d.close()};try{let t=registerDslConfig(l,f,{cwd:r,signer:previewSigner()});i.push(...t.loadWarnings);let n=resolveEffectiveGlobals(l,()=>null,()=>!1),d=settleWindow(e.clock,o);return bindPass({layers:s,config:l,compiled:t,store:u,registry:f,runs:p},n,CHECK_WIDTH,a),await p.settled(d.signal),{settle:d,layers:s,droppedPlugins:[...c.installed.dropped,...c.layers.flatMap(e=>e.plugins.dropped)],config:l,compiled:t,store:u,registry:f,runs:p,[Symbol.dispose]:m}}catch(e){throw m(),e}}async function renderEffective(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,runs:d,settle:f}=e,{drawn:p,opts:m}=bindPass(e,t,n,r);for(let e of stragglers(f,await d.settled(f.signal)))a.add(e);let{frame:h}=drawDsl(s,c,l,u,p,r,m,{onSegmentError:(e,t)=>i.set(`segment "${e}"`,t),onRenderWarning:o},t);return{rendered:h,failures:i,advisories:a}}async function loadRegisterRender(e,t,n,r,i,a,o){let s=instantOf(new Date(e.clock.now())),c=await prepareConfig(e,n,r,i,a,s,o),{config:l}=c;try{t.state.gateFor(l),t.config.gateFor(l);let e=effectivePresetName(null,l.globals.preset,l.presets),n=async(e,t)=>{let n=resolveEffectiveGlobals(l,t=>t===`preset`?e:null,()=>t),r;try{r=await renderEffective(c,n,CHECK_WIDTH,s)}catch(e){r={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...r}},r=await n(e,!1),i=[r,await n(e,!0)];for(let t of presetNames(l.presets))t!==e&&i.push(await n(t,!1),await n(t,!0));let o=t=>{let n=new Map;for(let e of i)for(let r of t(e)){let t=n.get(r)??new Map;t.set(e.preset,(t.get(e.preset)??new Set).add(e.customized)),n.set(r,t)}return[...n].map(([t,n])=>n.get(e)?.has(!1)?t:`${t} (under ${[...n].map(([t,n])=>[...t===e?[]:[`preset "${t}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};a.push(...o(e=>e.advisories));let u=o(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=r.rendered,f=c.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
|
|
523
526
|
`)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
|
|
524
527
|
`));return d}finally{c[Symbol.dispose]()}}const EXIT_CLEAN=0,EXIT_FATAL=1,EXIT_USAGE$1=2;function warningLines(e){return e.map(e=>`warning: ${e}\n`).join(``)}function checkPlan(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${chainName(e.layers.map(e=>e.path))}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${ansiOf(e.rendered)}\n`:``),stderr:warningLines(e.warnings),code:EXIT_CLEAN};case`fatal`:return{stdout:``,stderr:warningLines(e.warnings)+`✗ ${chainName(e.layers.map(e=>e.path),`<default>`)}\n${e.message}\n`,code:EXIT_FATAL};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:EXIT_USAGE$1}}}const RENDER_FLAG=`--render`,USAGE$3=`Usage: cc-candybar check [${RENDER_FLAG}] [config-file]\n`;function parseCheckArgs(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==RENDER_FLAG);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${USAGE$3}`}:n.length>1?{kind:`usage`,message:`check: expected at most one path\n${USAGE$3}`}:{kind:`run`,target:n[0],render:t.includes(RENDER_FLAG)}}async function checkCommandPlan(e,t){let n=parseCheckArgs(e),r=process$1.cwd();return n.kind===`usage`?{stdout:``,stderr:n.message,code:EXIT_USAGE$1}:checkPlan(await checkConfig(t,daemonGates(),cliConfigTarget(n.target,t.host,r).path,r),n.render)}const URL_SCHEME=/^[a-z][a-z0-9+.-]*:\/\//i,SCP_LIKE=/^[^@\s/]+@[^:\s/]+:/,GITHUB_SLUG=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function shownUrl(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function parsePluginSource(e,t,n,r){let i=resolveUserPath(t,e,n);if(r(i))return{kind:`path`,dir:i};if(URL_SCHEME.test(e)||SCP_LIKE.test(e))return{kind:`git`,url:e,shown:shownUrl(e)};let a=GITHUB_SLUG.exec(e);if(a){let e=`https://github.com/${a[1]}.git`;return{kind:`git`,url:e,shown:e}}return{error:`"${e}" is not a directory, a GitHub repo slug (owner/repo) or a git URL`}}function repoDefinitions(e,t){let n=path.join(e,REPO_PLUGIN_DIR),r=listFolders(n);if(`error`in r)throw Error(`${t}: could not list ${REPO_PLUGIN_DIR}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${REPO_PLUGIN_DIR}/<name>/${DEFINITION_FILE}`);return r.folders.map(e=>path.join(n,e,DEFINITION_FILE))}function cloneRepo(e,t,n,r){let i=(r,...i)=>{let a=e.launchSync({bin:`git`,args:i,envOverlay:r,category:`plugin.git`});if(!a.ok)throw Error(`git ${i.map(e=>e===t?n:e).join(` `)} failed (${failureText(a)})`);return a.stdout},a={GIT_TERMINAL_PROMPT:`0`};for(let e of i(a,`rev-parse`,`--local-env-vars`).split(`
|
|
525
528
|
`))a[e]=null;i(a,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,t,r),i(a,`-C`,r,`sparse-checkout`,`set`,`--no-cone`,`/${REPO_PLUGIN_DIR}/`)}function withRepo({host:e,launcher:t},n,r){switch(n.kind){case`path`:return r(n.dir);case`git`:{let i=fs.mkdtempSync(path.join(e.tmp,`cc-candybar-plugin-`));try{return cloneRepo(t,n.url,n.shown,path.join(i,`repo`)),r(path.join(i,`repo`))}finally{fs.rmSync(i,{recursive:!0,force:!0})}}}}function targetOf(e){let t;try{t=fs.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 place(e,t,n,r){switch(r){case`updated`:fs.renameSync(path.join(e,DEFINITION_FILE),path.join(t,DEFINITION_FILE));return;case`replaced`:fs.renameSync(t,n),fs.renameSync(e,t);return;case`installed`:fs.renameSync(e,t);return}}function installFromRepo(e,t,n,r){let i=repoDefinitions(e,n);fs.mkdirSync(t,{recursive:!0});let a=fs.mkdtempSync(path.join(t,`.install-`));try{let o=i.map(e=>{let t=path.join(a,path.basename(path.dirname(e)));fs.mkdirSync(t);try{fs.copyFileSync(e,path.join(t,DEFINITION_FILE))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),s=definitionProblems(o.map(e=>pluginDefinition(path.join(e,DEFINITION_FILE),`plugins`)),DEFAULT_DSL_CONFIG,{root:e,git:!1},r);if(s.length>0)throw Error(s.map(e=>`${n}: ${path.join(REPO_PLUGIN_DIR,path.relative(a,e.path))} would not load: ${e.reason.split(a).join(path.join(n,REPO_PLUGIN_DIR))}`).join(`
|
|
@@ -527,7 +530,7 @@ function run(argv) {
|
|
|
527
530
|
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`busy`:return{output:`
|
|
528
531
|
`,kick:!1,debug:`daemon busy (${e.message}) — not kicking`};case`permanent`:return{output:formatPermanentGlyph(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function detectTermExtent(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 SSH_ENV_VARS=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function detectClientHints(e,t,n){let{env:r}=e;return{termCols:detectTermExtent(r.COLUMNS,n.columns),termRows:detectTermExtent(r.LINES,n.rows),ssh:SSH_ENV_VARS.some(e=>(r[e]??``)!==``),tmux:detectTmuxHint(r),configEnv:detectConfigEnv(e,t),claudeConfigDir:detectClaudeConfigDir(r,t),terminalEnv:detectTerminalEnv(r)}}function sightingRecords(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function parseDaemonClients(e){let t=shapeSkew(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=sightingRecords(e);if(!n.every(e=>typeof e.ago==`number`))return{kind:`failed`,reason:`the running daemon (${e.version}) reported clients without their age: ${JSON.stringify(e.clients)}`};let r=[];for(let t of n){let n=parseSessionId(t.sessionId);if(!n.ok)return{kind:`failed`,reason:`the running daemon (${e.version}) reported a client whose session id ${n.problem}: ${JSON.stringify(e.clients)}`};r.push({client:sanitizeClient(t.client)??null,sessionId:n.id,ago:t.ago})}return{kind:`ok`,value:{bundle:e.bundle,clients:r}}}const isPostMortem=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},isProcessMemory=e=>{let t=e??{};return(t.role===`host`||t.role===`renderer`)&&typeof t.pid==`number`&&(t.sizes===null||typeof t.sizes?.rss==`number`&&typeof t.sizes.heapTotal==`number`)},isMemoryReading=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`&&Array.isArray(t.processes)&&t.processes.every(isProcessMemory)&&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 askedOnWire(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 parseServingDaemon(e){let t=shapeSkew(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=askedOnWire(n?.postMortems,e=>Array.isArray(e)&&e.every(isPostMortem)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});if(typeof n?.pid==`number`&&isMemoryReading(n.memory)&&typeof n.limit==`number`&&r.kind!==`misshapen`)return{kind:`ok`,value:{...n,postMortems:r}};let i=buildSkew(e);return{kind:`failed`,reason:`the running daemon (${e.version}) reported itself as ${JSON.stringify(e.daemon)}${i===null?``:`; ${i}`}`}}function sightingHalf(e,t,n){let r=shapeSkew(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=sightingRecords(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 isRole=e=>SIGHTING_ROLES.includes(e.role),parseRateLimitSightings=e=>sightingHalf(e,e=>typeof e.ago==`number`&&parseSessionId(e.sessionId).ok&&typeof e.claudeConfigDir==`string`&&RATE_LIMITS_SEEN.includes(e.rateLimits),`the rate-limit windows they carried`),parseTranscriptSightings=e=>sightingHalf(e,e=>{let t=e.transcript;return typeof e.ago==`number`&&parseSessionId(e.sessionId).ok&&typeof t?.path==`string`&&typeof t.answered==`boolean`},`their transcripts`),parseFrameSightings=e=>sightingHalf(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&parseSessionId(e.sessionId).ok&&isRole(e)&&FRAMES_SEEN.includes(e.frame),`what they drew and from which project`),parseWidthSightings=e=>sightingHalf(e,e=>parseSessionId(e.sessionId).ok&&typeof e.ago==`number`&&isRole(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function answeredStore(e,t,n){let r=e.doctorStores?.[t],i=askedOnWire(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 parseDoctorStores(e){let t=shapeSkew(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:answeredStore(e,`marks`,parseMarkBook),clicked:answeredStore(e,`clicked`,parseClickedTerminals),postMortemsRead:answeredStore(e,`postMortemsRead`,parsePostMortemsRead)}}async function askDaemon(e){let t=await fetchStats(e);if(t.kind!==`ok`){let e={kind:`failed`,reason:describeFailure(t).split(`
|
|
529
532
|
`).join(` — `)};return{clients:e,rateLimits:e,transcripts:e,frames:e,widths:e,serving:e,stores:{marks:e,clicked:e,postMortemsRead:e}}}return{clients:parseDaemonClients(t.value),rateLimits:parseRateLimitSightings(t.value),transcripts:parseTranscriptSightings(t.value),frames:parseFrameSightings(t.value),widths:parseWidthSightings(t.value),serving:parseServingDaemon(t.value),stores:parseDoctorStores(t.value)}}const EXIT_OK=0,EXIT_FAILED=1,EXIT_USAGE=2,FIX_HINT=` (fix: click the settings menu (${DOOR_GLYPH} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,MARK_HINT=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${DOOR_GLYPH} by default) › 🧰 tools › 🩺 doctor`;function reportLine({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:FIX_HINT}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${MARK_HINT}\n`)}function loadConfigOnce({host:e,clock:t},n){let r={clock:t,locations:locations(e),env:e.env,sessionState:new SessionState,signer:previewSigner(),gates:daemonGates(),stateDir:stateDir(e)},i=loadFromDisk(n.projectDir,n.cwd,n.target.path,r),a=i.state??fallbackState(n.cwd,i.repos.plugins,r);return a.registry.dispose(),{layers:i.layers,error:i.error??(a.dropped.map(e=>e.message).join(`
|
|
530
|
-
`)||null),warning:i.warning,unused:a.unused,config:a.config}}function installOf(e,t,n){return n.kind===`failed`?n:installFacts(e,n.value.bundle,inScope(t,n.value.clients).map(({client:e})=>e))}function rateLimitsOf(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:inScope(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function transcriptsOf(e,t){return t.kind===`failed`?t:{kind:`ok`,value:inScope(e,t.value).map(e=>e.transcript)}}function framesOf(e,t){return t.kind===`failed`?t:{kind:`ok`,value:barsOf(e,t.value)}}function widthOf(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:sessionWidth(e.sessionId,inScope(e,t.value))}async function doctorPlan(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=detectClientHints({env:r,home:e.home},i,a()),u=scopeOf$
|
|
533
|
+
`)||null),warning:i.warning,unused:a.unused,config:a.config}}function installOf(e,t,n){return n.kind===`failed`?n:installFacts(e,n.value.bundle,inScope(t,n.value.clients).map(({client:e})=>e))}function rateLimitsOf(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:inScope(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function transcriptsOf(e,t){return t.kind===`failed`?t:{kind:`ok`,value:inScope(e,t.value).map(e=>e.transcript)}}function framesOf(e,t){return t.kind===`failed`?t:{kind:`ok`,value:barsOf(e,t.value)}}function widthOf(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:sessionWidth(e.sessionId,inScope(e,t.value))}async function doctorPlan(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=detectClientHints({env:r,home:e.home},i,a()),u=scopeOf$2(r.CLAUDE_CODE_SESSION_ID);s={...await gatherFacts(e,l,{projectDir:ownProject(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,target:cliConfigTarget(o,{env:r,home:e.home},i)},()=>null,c.serving,rateLimitsOf(u,c.rateLimits,claudeConfigDir(l.claudeConfigDir,e.home)),transcriptsOf(u,c.transcripts),u,framesOf(u,c.frames),widthOf(u,c.widths,l.termCols??null),c.stores),urlHandler:await probeUrlHandler(t),install:installOf(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:EXIT_USAGE}}let c=runDoctor(s);return{stdout:c.map(reportLine).join(``),stderr:``,code:c.every(e=>e.verdict.ok)?EXIT_OK:EXIT_FAILED}}function commandTerminal(){if(process$1.stderr.isTTY)return process$1.stderr;let e;try{e=openSync(`/dev/tty`,`r+`)}catch{return{}}let t=new WriteStream(e),{columns:n}=t;return t.destroy(),{columns:n}}const USAGE$1=`Usage: cc-candybar doctor [config-file]
|
|
531
534
|
`;function parseDoctorArgs(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${USAGE$1}`}:n.length>1?{kind:`usage`,message:`doctor: expected at most one config file\n${USAGE$1}`}:{kind:`run`,configFile:n[0]}}async function doctorCommandPlan(e,t){let n=parseDoctorArgs(e);return n.kind===`usage`?{stdout:``,stderr:n.message,code:EXIT_USAGE}:await doctorPlan(productionEdge(t.launcher,e=>loadConfigOnce(t,e),t.host),productionHandlerProbeEdge(t.launcher,t),()=>askDaemon(t),t.host.env,process$1.cwd(),commandTerminal,n.configFile)}function isRefusal(e){return!e.ok&&e.code!==`RENDER_FAILED`}function openFrameStream(e,t,n,r,i){let a=null,o=e=>{a===null&&(a=e,s.destroy(),i(e))},s=net.createConnection({path:e}),c={v:3,kind:`subscribe`,sessionId:t,lane:n};return s.once(`connect`,()=>s.write(encodeFrame(c))),s.on(`data`,makeFrameReader(e=>{let t=e;isRefusal(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`})}}const RECONNECT_FIRST_MS=250,RECONNECT_MAX_MS=2e3,SWITCHED_OFF_RETRY_MS=5e3;function nextRetryMs(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(RECONNECT_MAX_MS,e*2)}}function afterStreamEnd(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 followFrames(e,t,n,r,i){let a=null,o=null,s=!1,c=250,l=(t,n)=>{o=e.clock.after(t,()=>{o=null,((n?i.beforeReconnect?.():void 0)??Promise.resolve()).then(()=>{s||u()})})},u=()=>{a=openFrameStream(t,n,r,e=>{c=nextRetryMs(c,e.ok?`frame-ok`:`frame-failed`),i.frame(e)},t=>{if(t.kind===`closed-here`||s)return;let n=afterStreamEnd(t);switch(n.kind){case`exit`:i.exit(n.reason);return;case`off`:i.off(n.resp),l(SWITCHED_OFF_RETRY_MS,!1);return;case`reconnect`:{i.fault(n.reason,c),n.kick&&obtainDaemonKick(e);let t=c;c=nextRetryMs(c,`fault`),l(t,!0);return}}})};return u(),{close:()=>{s=!0,o?.(),a?.close()}}}function worthSaying(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function runFrames(e,t,n){let{values:r,tokens:i}=parseArgs({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=process$1.cwd(),s=e=>{process$1.stderr.write(`cc-candybar frames: ${e}\n`)},c=parseLane(r.lane);c===null&&(s(`--lane needs one of ${LANE_NAMES.join(`, `)}`),process$1.exit(2)),process$1.stdout.on(`error`,()=>process$1.exit(0));let l=newestWins(process$1.stdout),u=null,d=null,f=null,p={kind:`none`},m=(e,t)=>{worthSaying(p,e)&&t(),p=e},h=async e=>{let r=await tryRenderViaDaemon(n,e,a,o,{...detectClientHints(n.host,o,process$1.stderr),client:nodeClientHint(`frames`,t)});r.kind!==`ok`&&(s(describeFailure(r)),planOutcome(r).kick&&obtainDaemonKick(n))},g=e=>{f?.close(),f=followFrames(n,socketPath(n.host),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),process$1.exit(1)},beforeReconnect:()=>d===null?Promise.resolve():h(d)})};for await(let e of createInterface({input:process$1.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))}process$1.exit(0)}const DRAWING=`\x1B[?25l\x1B[?7l`,RESTORED=`\x1B[?25h\x1B[?7h`,FRAME_START=`\x1B[?2026h`,FRAME_END=`\x1B[?2026l`,ERASE_RIGHT=`\x1B[0m\x1B[K`,ERASE_BELOW=`\x1B[J`;function paint(e){let t=e.replace(/\n+$/,``).split(`
|
|
532
535
|
`);return{bytes:FRAME_START+t.map((e,t)=>`\x1b[${t+1}H${e}${ERASE_RIGHT}`).join(``)+ERASE_BELOW+FRAME_END,rows:t.length}}const TICK_MS=500,TMUX_PATIENCE_MS=5e3,USAGE=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function placementFrom(e,t,n,r){let i=e.split(`
|
|
533
536
|
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?shownPanes(e,controlledSessions(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function askPlacement(e,t,n){let[r,i]=await Promise.all([runTmuxAsync(e.launcher,t,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${n}},#{==:#{pane_id},${t.pane}}}`,`-F`,LIST_PANES_FORMAT]),runTmuxAsync(e.launcher,t,`bar-pane.tmux`,[`list-clients`,`-F`,LIST_CLIENTS_FORMAT])]);return r.kind===`ok`?i.kind===`ok`?{kind:`ok`,placement:placementFrom(r.stdout,i.stdout,n,t.pane)}:i:r}function tmuxPatience(e){let t=e.monotonic();return n=>{if(n.kind===`ok`)t=e.monotonic();else if(e.monotonic()-t>TMUX_PATIENCE_MS)throw Error(`tmux has not answered for ${TMUX_PATIENCE_MS/1e3} s: ${n.reason}`)}}function parseArgs$1(e){let{positionals:t}=(()=>{try{return parseArgs({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${USAGE}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(USAGE);return{pane:n}}async function runBarPane(e,t){try{return await drawBarPane(e,t),0}catch(e){return process$1.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function drawBarPane(e,t){let{pane:n}=parseArgs$1(e),r=detectTmuxHint(t.host.env);if(r===null)throw Error(`cc-candybar bar-pane runs in a tmux pane`);if(!process$1.stdout.isTTY)throw Error(`cc-candybar bar-pane draws on its pane's terminal`);let i=await askPlacement(t,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})`);process$1.stdout.write(DRAWING),process$1.on(`exit`,()=>process$1.stdout.write(RESTORED));for(let[e,t]of[[`SIGINT`,130],[`SIGTERM`,143],[`SIGHUP`,129]])process$1.once(e,()=>process$1.exit(t));let o=e=>{process$1.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),process$1.exit(1)},s=null,c=`waiting for pane ${n}'s bar`,l=()=>s?.said.latest??c,u=``,d=tmuxPatience(t.clock),f=async()=>{if(a.kind!==`shown`)return;let e=paint(l());e.rows!==process$1.stdout.rows&&!a.zoomed&&d(await runTmuxAsync(t.launcher,r,`bar-pane.tmux`,[`resize-pane`,`-t`,r.pane,`-y`,String(e.rows)])),e.bytes!==u&&process$1.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)};process$1.stdout.on(`resize`,()=>{u=``,h()});let g=e=>{if(s?.sessionId===e)return;if(s?.follower.close(),e===null){s=null;return}let n={latest:null},r=e=>{n.latest=e,h()};s={sessionId:e,said:n,follower:followFrames(t,socketPath(t.host),e,`pane`,{frame:e=>r(planOutcome(renderOutcomeOf(e)).output),off:e=>r(e.error),fault:r,exit:e=>o(Error(e))})}},_=tmuxPatience(t.clock);for(;a.kind!==`gone`;){if(a.kind===`hidden`)g(null);else{let e=await trySessionInPane(t,r.socket,n);e.kind===`ok`?(g(e.value),c=e.value===null?`waiting for pane ${n}'s statusline to render on ${socketPath(t.host)}`:`waiting for pane ${n}'s bar`):(e.kind===`transient`&&(obtainDaemonKick(t),u=``),c=describeFailure(e))}h(),await sleep(t.clock,TICK_MS);let e=await askPlacement(t,r,n);_(e),e.kind===`ok`&&(a=e.placement)}g(null),process$1.stderr.write(`cc-candybar bar-pane: pane ${n} closed\n`)}const written=(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 exitWith(e){let t=debugText(()=>`delivered stdout=${Buffer.byteLength(e.stdout)} stderr=${Buffer.byteLength(e.stderr)} code=${e.code}`),n=[];for(let[r,i]of[[process$1.stdout,e.stdout],[process$1.stderr,e.stderr+t]])await written(r,i).catch(e=>n.push(e));if(n.length>0)throw n[0];process$1.exit(e.code)}const RUNNING_BUNDLE=fileURLToPath(import.meta.url),world=processWorld(),{host}=world;setDebug(!!host.env.CC_CANDYBAR_DEBUG);const hasFlag=e=>e.some(e=>process$1.argv.includes(e));function showHelpText(){console.log(HELP_TEXT);let e=stableAttachPreload(RUNNING_BUNDLE,host),t=fs.existsSync(e)?``:" (nothing is there yet: run `cc-candybar install` first — in a checkout, `pnpm build`)\n";console.log(`Starting Claude Code on ${LANES.statusline.label} yourself (a Bun-compiled Claude Code):\n ${attachCommandLine(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const SUBCOMMANDS={install:async e=>{await runInstall(e,RUNNING_BUNDLE,world),process$1.exit(0)},"install-url-handler":async()=>{runInstallUrlHandler(RUNNING_BUNDLE,world),process$1.exit(0)},"url-handle":async e=>{await runUrlHandle(e[0],world)},daemon:async()=>{runDaemon(world)},renderer:async()=>{runRenderer(world)},"daemon-stats":async e=>{await exitWith(await daemonStatsPlan(world,e))},frames:async()=>{await runFrames(process$1.argv,RUNNING_BUNDLE,world)},check:async e=>{await exitWith(await checkCommandPlan(e,world))},lint:async e=>{await exitWith(await checkCommandPlan(e,world))},plugin:async e=>{process$1.exit(runPlugin(e,world))},schema:async()=>{await exitWith(schemaPlan())},doctor:async e=>{await exitWith(await doctorCommandPlan(e,world))},"bar-pane":async e=>{process$1.exit(await runBarPane(e,world))},...Object.fromEntries(DEBUG_WHATS.map(e=>[e,async t=>{await exitWith(await debugCommandPlan(world,e,t))}]))};async function main(){let e=process$1.argv[2],t=e!==void 0&&!e.startsWith(`-`)?e:null;try{if(t!==null&&!Object.hasOwn(SUBCOMMANDS,t)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(t)} — see --help`),process$1.exit(2)),hasFlag(NODE_FLAGS.help)&&(showHelpText(),process$1.exit(0)),hasFlag(NODE_FLAGS.version)&&(console.log(`cc-candybar ${PACKAGE_VERSION}`),process$1.exit(0)),t!==null){await SUBCOMMANDS[t](process$1.argv.slice(3));return}process$1.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|