@promptctl/cc-candybar 1.116.0 → 1.116.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +51 -51
  2. package/package.json +5 -5
package/dist/index.mjs CHANGED
@@ -87,14 +87,14 @@ Use 'override' annotation for methods overridden by subclass.`)}}var na=ca(0),ra
87
87
  `,1)[0]??``}function Py(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?Y:J(n)}function Fy(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?J(t):Y}const Iy=/^[A-Za-z]:[\\/]/;function Ly(e){let t=e.trim();if(Iy.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 Ry(e){return Ly(e)?.host||null}function zy(e){let t=Ry(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}function By(e){let t=new Map;for(let n of e.split(`
88
88
  `)){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 Vy(e){return e.urls.find(e=>Ky(e)!==null)??e.urls[0]??null}function Hy(e){return e.find(e=>e.name===`origin`)??e[0]??null}function Uy(e){let t=Hy(e);return t?Vy(t):null}function Wy(e){let t=Hy(e);return t?t.urls.find(e=>zy(e)!==null)??Vy(t):null}function Gy(e){let t=(Ly(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function Ky(e){let t=Ly(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 qy(e){let t=Uy(e);return t===null?null:Ky(t)}function Jy(e,t,n,r){return t.ok?r(t.stdout):t.reason===`spawn-error`&&/ENOENT/i.test(t.error??``)||t.reason===`non-zero`&&n.test(t.stderr)?Y:X(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??Ny(t.stderr)].filter(Boolean).join(`, `)}`)}function Yy(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xy(e){let t=`detached`,n=Y,r=Y,i=Y,a=0,o=0,s=0,c=0;for(let l of e.split(`
89
89
  `)){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)`?Y:J(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=J(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=J({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 Zy(e){let t;try{t=JSON.parse(e)}catch(e){return X(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!Yy(t))return X(`gh pr view: JSON is not an object`);let{number:n,state:r,url:i}=t;return typeof n!=`number`||typeof r!=`string`||typeof i!=`string`?X(`gh pr view: missing number/state/url`):r.toUpperCase()===`OPEN`?J({number:n,state:r,url:i}):Y}function Qy(e){let t;try{t=JSON.parse(e)}catch(e){return X(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!Yy(t))return X(`glab mr view: JSON is not an object`);let n=t.iid,r=t.state,i=t.web_url;return typeof n!=`number`||typeof r!=`string`||typeof i!=`string`?X(`glab mr view: missing iid/state/web_url`):r.toLowerCase()===`opened`?J({number:n,state:r,url:i}):Y}function $y(e){try{let t=r.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var eb=class{isGitRepo(e){try{return r.existsSync(c.join(e,`.git`))}catch{return!1}}async execGitAsync(e,t){return ke({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}async resolveEffectiveGitDir(e,t){return this.isWorktree(e)?J(e):t&&this.isGitRepo(t)?J(t):this.isGitRepo(e)?J(e):this.findGitRoot(e)}async findGitRoot(e){let t=c.resolve(e);for(;;){if(this.isGitRepo(t))return J(t);let e=c.dirname(t);if(e===t)return Y;t=e}}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return X(`git: ${e instanceof Error?e.message:String(e)}`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=await this.findGitRoot(e);if(t.kind!==`ok`)return t;r=t.value}let a=await this.getCoreAsync(r);if(a.kind!==`ok`)return a;let o={branch:a.value.branch,status:a.value.status,aheadBehind:a.value.aheadBehind};t.showWorkingTree&&(o.workingTree=a.value.workingTree),t.showSha&&(o.sha=Py(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showTimeSinceCommit&&(o.timeSinceCommit=await this.timeSinceCommit(r,a.value.oid)),t.showStashCount&&(o.stashCount=this.getStashCount(r));let s=t.showRepoName||t.showRepoUrl?await this.getRemotesAsync(r):void 0;return s!==void 0&&t.showRepoName&&(o.repoName=Py(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=Py(s,qy)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),J(o)}resolveGitDir(e){let t=c.join(e,`.git`);try{if(r.existsSync(t)&&r.statSync(t).isFile()){let n=r.readFileSync(t,`utf-8`).match(/^gitdir:\s*(.+)$/m);if(n?.[1])return c.resolve(e,n[1].trim())}}catch{}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return r.existsSync(c.join(t,`MERGE_HEAD`))?J(`MERGE`):r.existsSync(c.join(t,`CHERRY_PICK_HEAD`))?J(`CHERRY-PICK`):r.existsSync(c.join(t,`REVERT_HEAD`))?J(`REVERT`):r.existsSync(c.join(t,`BISECT_LOG`))?J(`BISECT`):r.existsSync(c.join(t,`rebase-merge`))||r.existsSync(c.join(t,`rebase-apply`))?J(`REBASE`):Y}catch(e){return X(`git operation probe: ${e instanceof Error?e.message:String(e)}`)}}async getNearestTagAsync(e){return Fy(My(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async timeSinceCommit(e,t){return t.kind===`ok`?Py(await this.commitTimestampMs(e,t.value),e=>Math.floor((Date.now()-e)/1e3)):t}commitTimes=new Map;async commitTimestampMs(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.readCommitTimestampMs(e,t);for(this.commitTimes.set(t,r),r.then(e=>{e.kind!==`ok`&&this.commitTimes.get(t)===r&&this.commitTimes.delete(t)},()=>{this.commitTimes.get(t)===r&&this.commitTimes.delete(t)});this.commitTimes.size>256;){let e=this.commitTimes.keys().next().value;if(e===void 0)break;this.commitTimes.delete(e)}return r}async readCommitTimestampMs(e,t){let n=Fy(My(`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)*1e3;return Number.isNaN(r)?X(`git log -1: unparseable timestamp "${n.value}"`):J(r)}resolveCommonGitDir(e){let t=this.resolveGitDir(e);try{let e=r.readFileSync(c.join(t,`commondir`),`utf-8`).trim();if(e)return c.resolve(t,e)}catch{}return t}getStashCount(e){let t=c.join(this.resolveCommonGitDir(e),`logs`,`refs`,`stash`),n;try{n=r.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?J(0):X(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`)}let i=n.trim();return J(i?i.split(`
90
- `).length:0)}async getRemotesAsync(e){let t=$y(c.join(this.resolveCommonGitDir(e),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){let t=My(`git config --get-regexp remote url`,await this.execGitAsync([`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`],{cwd:e,timeout:2e3}),1);return t.kind===`failed`?t:J(t.kind===`ok`?By(t.value):[])}repoNameFrom(e,t){let n=Uy(e);return(n===null?null:Gy(n))??c.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=Wy(t.value);return n===null?Y:J(n)}async execForgeAsync(e,t,n){return ke({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=zy(t);return n===`github`?Jy(`gh pr view`,await this.execForgeAsync(`gh`,[`pr`,`view`,`--json`,`number,state,url`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,Zy):n===`gitlab`?Jy(`glab mr view`,await this.execForgeAsync(`glab`,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,Qy):Y}isWorktree(e){try{let t=c.join(e,`.git`);return!!(r.existsSync(t)&&r.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){O(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=My(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?J(Xy(t.value)):t}};let tb=null;function nb(e){if(tb!==null)return tb;r.mkdirSync(c.dirname(e),{recursive:!0});try{tb=r.statSync(e).size}catch{tb=0}return tb}function rb(e){for(let t=2;t>=1;t--){let n=`${e}.${t}`,i=`${e}.${t+1}`;try{r.renameSync(n,i)}catch{}}try{r.renameSync(e,`${e}.1`)}catch{}tb=0}const ib=(e,t)=>O(t);function Z(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=Xe(),t=nb(e);r.appendFileSync(e,n),tb=t+Buffer.byteLength(n,`utf8`),tb>=5242880&&rb(e)}catch(e){tb=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}const ab=(e,t)=>O(t);var ob=class{slots=new Map;maxWatchers;counters;logger;closed=!1;constructor(e={}){this.maxWatchers=e.maxWatchers??128,this.counters=e.counters,this.logger=e.logger??ab}acquire(e,t,n){if(this.closed)return{release:()=>{}};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,r.lastTouched=Date.now(),this.slots.delete(e),this.slots.set(e,r),this.makeHandle(e);let i={key:e,watchers:[],refcount:1,debounceTimer:null,onInvalidate:n,targets:t,lastTouched:Date.now()};return this.openWatchers(i),this.slots.set(e,i),this.counters&&this.counters.watchersOpened++,this.evictIfNeeded(),this.makeHandle(e)}makeHandle(e){let t=!1;return{release:()=>{if(t)return;t=!0;let n=this.slots.get(e);n&&(n.refcount=Math.max(0,n.refcount-1),n.refcount===0&&(this.closeSlot(n),this.slots.delete(e)))}}}openWatchers(e){let t=()=>{e.debounceTimer||(e.debounceTimer=setTimeout(()=>{e.debounceTimer=null;try{e.onInvalidate()}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50),e.debounceTimer.unref())};for(let n of e.targets.files)try{let i=r.watch(n,{persistent:!1},t);i.on(`error`,e=>{this.logger(`warn`,`watcher error ${n}: ${e.message}`)}),e.watchers.push(i)}catch(e){this.logger(`warn`,`watch failed ${n}: ${e.message}`)}for(let n of e.targets.dirs)try{let i=n.filenames?new Set(n.filenames):null,a=r.watch(n.path,{persistent:!1},(e,n)=>{i&&(!n||!i.has(n))||t()});a.on(`error`,e=>{this.logger(`warn`,`watcher error ${n.path}: ${e.message}`)}),e.watchers.push(a)}catch(e){this.logger(`warn`,`watch failed ${n.path}: ${e.message}`)}}closeSlot(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}evictIfNeeded(){for(;this.slots.size>this.maxWatchers;){let e=this.slots.keys().next().value;if(e===void 0)break;let t=this.slots.get(e);this.closeSlot(t),this.slots.delete(e),this.counters&&this.counters.watchersEvicted++;try{t.onInvalidate()}catch{}this.logger(`info`,`watcher LRU evict ${e}`)}}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}},sb=class{running=new Set;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:(this.running.add(e),{kind:`started`,done:this.loop(e,t)})}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 cb={showSha:!0,showStashCount:!0};function lb(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function ub(e){let t=t=>{try{return r.statSync(c.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function db(e,t){return e.head!==t.head||e.index!==t.index}function fb(e){let t=[],n=c.join(e,`refs/heads`);try{r.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[c.join(e,`HEAD`),c.join(e,`index`)],dirs:t}}var pb=class extends eb{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new sb;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new eb,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??ib,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new ob({logger:this.logger}),this.ownsWatchers=!0);let t=e.sanityIntervalMs??3e5;t>0&&(this.sanityTimer=setInterval(()=>this.runSanityCheck(),t),this.sanityTimer.unref())}getWatcherRegistry(){return this.watchers}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,invalidations:this.invalidations,watchers:this.watchers.size()}}resolveEffectiveGitDir(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.resolutions.delete(n),this.resolutions.set(n,i),i.dir;let a=this.inner.resolveEffectiveGitDir(e,t);return this.resolutions.set(n,{dir:a,computedAt:r}),a.catch(()=>{this.resolutions.get(n)?.dir===a&&this.resolutions.delete(n)}),this.evictResolutionsIfNeeded(),a}evictResolutionsIfNeeded(){for(;this.resolutions.size>this.maxEntries;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}}async getGitInfo(e,t={},n){let r=await this.resolveEffectiveGitDir(e,n);return r.kind===`ok`?this.getGitInfoForRoot(r.value,t):r}getGitInfoForRoot(e,t){let n=`${e}|${lb(t)}`,r=Date.now(),i=this.entries.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.entries.delete(n),this.entries.set(n,i),this.hits++,Promise.resolve(J(i.info));let a=this.fetchInFlight.get(n);if(a)return a;let o=this.doFetch(e,n,t,r).finally(()=>{this.fetchInFlight.delete(n)});return this.fetchInFlight.set(n,o),o}async doFetch(e,t,n,r){this.misses++;let i=this.inner.resolveGitDir(e),a=ub(i),o=await this.inner.getGitInfo(e,n);if(o.kind!==`ok`)return o;let s=o.value;n.showPullRequest&&(s.pullRequest=await this.getPullRequestCached(e,s.branch)),this.dropEntry(t);let c=this.watchers.acquire(`git:${e}`,fb(i),()=>this.invalidateRepo(e));return this.entries.set(t,{info:s,computedAt:r,mtime:a,watcher:c,repoRoot:e}),this.evictIfNeeded(),o}async getPullRequestCached(e,t){let n=await this.inner.getRepoRemoteUrl(e);if(n.kind===`failed`)return n;if(n.kind===`absent`)return Y;let r=n.value,i=`${e}|${t}|${r}`,a=Date.now(),o=this.prCache.get(i);if(o){let e=o.pr.kind===`failed`?45e3:3e5;if(a-o.computedAt<e)return this.prCache.delete(i),this.prCache.set(i,o),o.pr}let s=this.prFetchInFlight.get(i);if(s)return s;let c=this.inner.resolvePullRequest(e,r).then(e=>(this.prCache.set(i,{pr:e,computedAt:Date.now()}),this.evictPrIfNeeded(),e)).finally(()=>{this.prFetchInFlight.delete(i)});return this.prFetchInFlight.set(i,c),c}evictPrIfNeeded(){for(;this.prCache.size>this.maxEntries;){let e=this.prCache.keys().next().value;if(e===void 0)break;this.prCache.delete(e)}}deliverable(e,t){return e.kind===`failed`?(this.logger(`warn`,`git fetch failed (${t}): ${e.reason}`),null):e.kind===`ok`?e.value:null}subscribe(e,t){let n=!1,r=null;return{firstDelivery:(async()=>{let i=await this.resolveEffectiveGitDir(e);if(n)return;if(i.kind!==`ok`){i.kind===`failed`&&this.logger(`warn`,`git resolve failed (subscribe ${e}): ${i.reason}`),this.safeInvoke(t,null);return}let a=i.value,o=this.subscribersByRepo.get(a);if(!o){let t=this.inner.resolveGitDir(a),n=this.watchers.acquire(`git:${a}`,fb(t),()=>this.invalidateRepo(a));o={workingDir:e,repoRoot:a,callbacks:new Set,watcher:n},this.subscribersByRepo.set(a,o)}o.callbacks.add(t),r={repoRoot:a,entry:o};let s=await this.getGitInfoForRoot(a,{...cb});n||this.safeInvoke(t,this.deliverable(s,a))})(),unsubscribe:()=>{if(n=!0,!r)return;let{repoRoot:e,entry:i}=r;i.callbacks.delete(t),i.callbacks.size===0&&(i.watcher.release(),this.subscribersByRepo.delete(e))}}}invalidateRepo(e){let t=0;for(let[n,r]of this.entries)r.repoRoot===e&&(r.watcher.release(),this.entries.delete(n),t++);t>0&&(this.invalidations+=t,this.logger(`info`,`gitCache invalidate ${e} dropped=${t}`)),this.refreshSubscribers(e)}refreshSubscribers(e){let t=this.subscribersByRepo.get(e);!t||t.callbacks.size===0||this.refreshes.run(e,()=>this.refreshOnce(e))}async refreshOnce(e){let t=this.subscribersByRepo.get(e);if(!t||t.callbacks.size===0)return;let n=await this.getGitInfoForRoot(e,{...cb}),r=this.deliverable(n,e),i=this.subscribersByRepo.get(e);if(!(!i||i.callbacks.size===0))for(let e of[...i.callbacks])i.callbacks.has(e)&&this.safeInvoke(e,r)}safeInvoke(e,t){try{e(t)}catch(e){this.logger(`warn`,`git subscriber threw: ${e.message??String(e)}`)}}dropEntry(e){let t=this.entries.get(e);t&&(t.watcher.release(),this.entries.delete(e))}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.dropEntry(e),this.logger(`info`,`gitCache evict ${e}`)}}runSanityCheck(){let e=new Map;for(let t of this.entries.values()){let n=e.get(t.repoRoot);n||(n=ub(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),db(t.mtime,n)&&this.invalidateRepo(t.repoRoot)}}runSanityCheckNow(){this.runSanityCheck()}close(){this.sanityTimer&&=(clearInterval(this.sanityTimer),null);for(let e of this.entries.values())e.watcher.release();this.entries.clear();for(let e of this.subscribersByRepo.values())e.callbacks.clear(),e.watcher.release();this.subscribersByRepo.clear(),this.refreshes.clear(),this.fetchInFlight.clear(),this.prCache.clear(),this.prFetchInFlight.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}};const mb=/\r\n|\r|\n/g,hb=e=>J(e.replace(mb,` `).trim());function gb(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?X(`regex no-match`):J(n.replace(mb,` `))}}const _b=e=>{try{return J(JSON.parse(e))}catch(e){return X(`JSON parse failed: ${e.message}`)}};function vb(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(O(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function yb(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const bb=`session.id`;function xb(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await ke({bin:`/bin/sh`,args:[`-c`,e],cwd:t,category:`user-shell`,signal:n});if(!r.ok&&r.reason===`aborted`)throw n.reason;return r.ok?J(r.stdout):X(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function Sb(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await S(e,{encoding:`utf8`,signal:n});return J(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return X(`file unreadable: ${e}`)}}}}function Cb(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?X(`${r.reason} in ${n}`):r}const wb=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Tb=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Eb=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],Db=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function Ob(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>wb[e.getMonth()]],[`Monday`,e=>Eb[e.getDay()]],[`Jan`,e=>Tb[e.getMonth()]],[`Mon`,e=>Db[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const kb={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function Ab(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=kb[t];try{return Pb(r,e)}catch{return Fb(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return jy(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return jy(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return jy(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return jy(e.stashCount,0)}}var jb=class{watchers=new Map;subscribe(e,t){let n=this.watchers.get(e);if(!n){let t=new Set,r;try{r=s(e,()=>{for(let e of t)e()})}catch{return()=>{}}n={watcher:r,callbacks:t},this.watchers.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(n.watcher.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e.close();this.watchers.clear()}size(){return this.watchers.size}},Mb=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:te(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(ee(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())ee(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function Nb(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function Pb(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`?Fv(e):t===`number`?Iv(e):Lv(e)}function Fb(e){return e===`number`?0:e===`boolean`?!1:``}var Ib=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new jb;ttlMgr=new Mb;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new sb;abort=new AbortController;drawn=Mv.observable.box(F.TRUECOLOR);drawnAt=()=>this.drawn.get();engine=Ey(void 0,void 0,this.drawnAt);gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new pb({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Pv(t),t)}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,xb(t,n.cwd,this.abort.signal),vb(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,Sb(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,hb,t.default,n);case`regex`:return this.scalarPublisher(e,gb(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=Cb(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,jy(a,i))}}documentPublisher(e,t,n){let r=t===void 0?Y:J(t);return this.store.defineDocument(e,r),i=>{let a=Cb(i,_b,n);this.noteOutcome(e,a),this.store.setDocument(e,a.kind===`ok`||t===void 0?a:r)}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.store.defineComputed(e,`string`,t=>{let i=Dy(this.store);try{let t=r.evaluate(i).map(e=>e.plain).join(``);return this.lastErrors.delete(e),t}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n.varDefault===void 0)throw Error(`variable "${e}": ${r}`);return n.varDefault}});try{this.store.read(e)}catch{}}declareTime(e,t){let n=t.ttlMs??1e3;this.store.defineBox(e,`string`,(e=>{try{return Ob(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,Ob(t.format,new Date)),this.lastErrors.delete(e)}catch(n){this.applyFallback(e,`string`,t.varDefault,n instanceof Error?n.message:String(n))}});this.cleanups.push(r)}declareGit(e,t){let n=kb[t.field],r=t.varDefault===void 0?Fb(n):Pb(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,Ab(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(bb);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=Nb(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,Pb(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}drawAt(e){this.store.runInAction(()=>this.drawn.set(e))}getLastError(e){return this.lastErrors.get(e)}dispose(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let e=this.watchMgr.subscribe(t.path,n);this.cleanups.push(e);break}case`key`:{let e=this.engine.parse(t.template),r=(0,Mv.reaction)(()=>{let t=Dy(this.store);try{return e.evaluate(t).map(e=>e.plain).join(``)}catch{return``}},n);this.cleanups.push(r);break}case`depends_on`:{let e=(0,Mv.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,Pb(this.defaultEmptyValue,t))}catch{this.store.setBox(e,Fb(t))}}defaultFor(e){try{return Pb(this.defaultEmptyValue,e)}catch{return Fb(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};const Lb={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[bb]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`,default:``},config_path:{kind:`input`,path:`configPath`,default:``},"theme.effective":{kind:`input`,path:`theme.effective`,default:``},"style.effective":{kind:`input`,path:`style.effective`,default:``},"preset.effective":{kind:`input`,path:`preset.effective`,default:``},"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},"endcaps.effective":{kind:`input`,path:`endcaps.effective`,default:``},"variation.effective":{kind:`input`,path:`variation.effective`,default:``},"charset.effective":{kind:`input`,path:`charset.effective`,default:``},"colorCompatibility.effective":{kind:`input`,path:`colorCompatibility.effective`,default:``},"autoWrap.effective":{kind:`input`,path:`autoWrap.effective`,type:`boolean`,default:!0},"padding.effective":{kind:`input`,path:`padding.effective`,type:`number`,default:1},"updateNotice.effective":{kind:`input`,path:`updateNotice.effective`,type:`boolean`,default:!0},"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:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},Rb=`ne .tmux.pane ""`,zb={theme:{configKey:`palette`,sessionKey:`theme`,effectiveVar:`theme.effective`,label:`🎨`},preset:{configKey:`preset`,sessionKey:`preset`,effectiveVar:`preset.effective`,label:`▦`},style:{configKey:`style`,sessionKey:`style`,effectiveVar:`style.effective`,label:`◐`},endcaps:{configKey:`endcaps`,sessionKey:`endcaps`,effectiveVar:`endcaps.effective`,label:`✦`},variation:{configKey:`variation`,sessionKey:`variation`,effectiveVar:`variation.effective`,label:`🎼`},autoWrap:{configKey:`autoWrap`,sessionKey:`autoWrap`,effectiveVar:`autoWrap.effective`,label:`wrap`},padding:{configKey:`padding`,sessionKey:`padding`,effectiveVar:`padding.effective`,label:`padding`},updateNotice:{configKey:`updateNotice`,sessionKey:`updateNotice`,effectiveVar:`updateNotice.effective`,label:`update notice`}},Bb=Object.values(zb),Vb=[{configKey:`charset`,effectiveVar:`charset.effective`},{configKey:`colorCompatibility`,effectiveVar:`colorCompatibility.effective`}],Hb=new Set(Vb.map(e=>e.configKey)),Ub=new Map([...Bb,...Vb].map(e=>[e.configKey,e.effectiveVar])),Wb=new Map(Bb.map(e=>[e.sessionKey,e.effectiveVar]));function Gb(e){return Object.fromEntries(Object.keys(zb).map(t=>[t,e(t)]))}const Kb=new Map(Object.keys(zb).map(e=>[zb[e].sessionKey,e]));function qb(e,t,n){let r=new Set,i=e=>{for(let t of xv(e??``,n).keys())r.add(t)};for(let t of Object.values(e.segments))i(t.template),i(t.bg),i(t.fg),i(t.when);for(let e of t)for(let t of Ps(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(bb);for(let t of Object.values(e.actions)){r.add(bb),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?Wb.get(t.set):void 0,n=`persist`in t?Ub.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function Jb(e,t,n){let r=Ov({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of qb(e,t,n.helpers)){if(Dv(a,r))continue;let e=Lb[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}const Yb=new Map,Xb=new Map;function Zb(e){let t=$b(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 Qb(e,t){return e===`bar`?t:Zb(e)}function $b(e){let t=Yb.get(e);if(t!==void 0)return t;let n=Er(e);return n===null?null:(Yb.set(e,n),n)}function ex(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=Xb.get(n);if(r!==void 0)return r;let i=Pr(e,t);return Xb.set(n,i),i}function tx(e){let t=$b(e);return t===null?null:{kind:`decided`,name:e,value:t}}function nx(e,t,n){let r=tx(e);return r===null?(n(`${t} rendered "${Za}": "${e}" names no installed theme${Xa(e)}`),ix()):r}function rx(e,t,n){return oo(e,t,n,ix(),tx)}function ix(){return tx(Za)}function ax(e){return so(rx(void 0,null,e),ix).value}const ox=new Map;function sx(e,t,n){ox.set(e,{permanent:!0,resolve:t,paletteOf:n})}sx(`themes`,()=>$a(),e=>Zb(e));const cx=`placementThemes`;sx(cx,eo,(e,t)=>Qb(e,t.palette)),sx(`endcaps`,()=>po),sx(`variations`,()=>bo),sx(`charsets`,()=>go),sx(`colorCompatibilities`,()=>vo);function lx(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>ex(n.basePalette,e.styles[t])}],[`presets`,{members:j_(e.presets)}]])}function ux(e){return[...new Set([...ox.keys(),...e.keys()])]}function dx(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=ox.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf};throw Error(`unknown option domain "${e}" (have: ${ux(t).join(`, `)})`)}function fx(e,t,n){return e===`bool`?Do(t)!==null:`from`in e?dx(e.from,n).members.includes(t):Oo(t,e)!==null}function px(e,t){if(e===`bool`)return To.join(` or `);if(`from`in e){let{members:n}=dx(e.from,t),r=n.map(e=>JSON.stringify(e));if(n.length<=8)return`one of ${r.join(`, `)}`;let i=typeof e.from==`string`?` "${e.from}"`:``;return`one of the ${n.length}${i} names, such as ${r.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function mx(e){return{label:e.label,domain:hx(e.domain)}}function hx(e){return e===`theme`?{from:cx}:e===`bool`||`min`in e?e:{from:e}}function gx(e,t,n,r,i){let a=Xc(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...To]}},variables:{}};if(`from`in o)return _x(a,t,r,i,o.from);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 _x(e,t,n,r,i){let a={variable:r,key:r,member:n},o=C_(r,n),s=`${n}.open`,c=w_(r),l=`${c}.first`;return{kind:`picker`,template:`{{ "${e}" }} {{ carousel "${n}" 0 "${s}" }}`,actions:{[n]:{set:t,from:i},[o]:il(r,n),[c]:{set:c,int:!0},[l]:{set:c,to:`0`},[s]:{do:[o,l]}},variables:{[r]:rl(r,Kc),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,template:`{{ picker "${n}" "${c}" false true true }}`}}}const vx=/^segments\.([^.]+)\.palette$/,yx=/^presets\.(.+)\.root$/,bx=/^presets\.(.+)\.globals\.([^.]+)$/;function xx(e){return`presets.${e}.root`}function Sx(e,t){return`presets.${e}.globals.${t}`}function Cx(e){if(Ml(e))return{scope:`globals`,field:e};let t=vx.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=bx.exec(e);if(n&&Tl(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=yx.exec(e);return r?{scope:`preset-root`,preset:r[1]}:null}function wx(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`]}}const Tx=`open`;function Ex(e,t,n,r){let i={variable:e,key:e,member:Tx};return r.variables[e]=rl(e,Kc),r.actions[e]=il(e,Tx),r.segments[e]={template:el(e,`(?)`,`✕`),...Dx(n)},Zc(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 Dx(e){let[t,...n]=e;return t===void 0?{}:{when:Qc(t,...n)}}const Ox=`none`;var kx=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function Ax(e,t,n,r,i){let{palette:a,tint:o}=e,s=jx(n,i),c=s!==Ox,l=c?s===void 0?o:Mx(a,s,`bg`):Mx(a,`background`,`bg`);e.bg=l;let u=jx(r,i),d=u===void 0?c?ja(a,l,t):void 0:Mx(a,u,`fg`);return new V({...c&&{bgcolor:L.fromRgba(l)},...d!==void 0&&{color:L.fromRgba(d)}})}function jx(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function Mx(e,t,n){try{return er(e,t)}catch(e){throw e instanceof Zn?new kx(t,n,e.message):e}}const Nx={help:[`-h`,`--help`],version:[`-V`,`--version`]},Px=[`✚ inserts`,`✖ removes`,`⚙️ configures`,`↺ resets layout`],Fx=`
90
+ `).length:0)}async getRemotesAsync(e){let t=$y(c.join(this.resolveCommonGitDir(e),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){let t=My(`git config --get-regexp remote url`,await this.execGitAsync([`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`],{cwd:e,timeout:2e3}),1);return t.kind===`failed`?t:J(t.kind===`ok`?By(t.value):[])}repoNameFrom(e,t){let n=Uy(e);return(n===null?null:Gy(n))??c.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=Wy(t.value);return n===null?Y:J(n)}async execForgeAsync(e,t,n){return ke({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=zy(t);return n===`github`?Jy(`gh pr view`,await this.execForgeAsync(`gh`,[`pr`,`view`,`--json`,`number,state,url`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,Zy):n===`gitlab`?Jy(`glab mr view`,await this.execForgeAsync(`glab`,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,Qy):Y}isWorktree(e){try{let t=c.join(e,`.git`);return!!(r.existsSync(t)&&r.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){O(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=My(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?J(Xy(t.value)):t}};let tb=null;function nb(e){if(tb!==null)return tb;r.mkdirSync(c.dirname(e),{recursive:!0});try{tb=r.statSync(e).size}catch{tb=0}return tb}function rb(e){for(let t=2;t>=1;t--){let n=`${e}.${t}`,i=`${e}.${t+1}`;try{r.renameSync(n,i)}catch{}}try{r.renameSync(e,`${e}.1`)}catch{}tb=0}const ib=(e,t)=>O(t);function Z(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=Xe(),t=nb(e);r.appendFileSync(e,n),tb=t+Buffer.byteLength(n,`utf8`),tb>=5242880&&rb(e)}catch(e){tb=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}const ab=(e,t)=>O(t);var ob=class{slots=new Map;maxWatchers;counters;logger;closed=!1;constructor(e={}){this.maxWatchers=e.maxWatchers??128,this.counters=e.counters,this.logger=e.logger??ab}acquire(e,t,n){if(this.closed)return{release:()=>{}};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,r.lastTouched=Date.now(),this.slots.delete(e),this.slots.set(e,r),this.makeHandle(e);let i={key:e,watchers:[],refcount:1,debounceTimer:null,onInvalidate:n,targets:t,lastTouched:Date.now()};return this.openWatchers(i),this.slots.set(e,i),this.counters&&this.counters.watchersOpened++,this.evictIfNeeded(),this.makeHandle(e)}makeHandle(e){let t=!1;return{release:()=>{if(t)return;t=!0;let n=this.slots.get(e);n&&(n.refcount=Math.max(0,n.refcount-1),n.refcount===0&&(this.closeSlot(n),this.slots.delete(e)))}}}openWatchers(e){let t=()=>{e.debounceTimer||(e.debounceTimer=setTimeout(()=>{e.debounceTimer=null;try{e.onInvalidate()}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50),e.debounceTimer.unref())};for(let n of e.targets.files)try{let i=r.watch(n,{persistent:!1},t);i.on(`error`,e=>{this.logger(`warn`,`watcher error ${n}: ${e.message}`)}),e.watchers.push(i)}catch(e){this.logger(`warn`,`watch failed ${n}: ${e.message}`)}for(let n of e.targets.dirs)try{let i=n.filenames?new Set(n.filenames):null,a=r.watch(n.path,{persistent:!1},(e,n)=>{i&&(!n||!i.has(n))||t()});a.on(`error`,e=>{this.logger(`warn`,`watcher error ${n.path}: ${e.message}`)}),e.watchers.push(a)}catch(e){this.logger(`warn`,`watch failed ${n.path}: ${e.message}`)}}closeSlot(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}evictIfNeeded(){for(;this.slots.size>this.maxWatchers;){let e=this.slots.keys().next().value;if(e===void 0)break;let t=this.slots.get(e);this.closeSlot(t),this.slots.delete(e),this.counters&&this.counters.watchersEvicted++;try{t.onInvalidate()}catch{}this.logger(`info`,`watcher LRU evict ${e}`)}}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}},sb=class{running=new Set;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:(this.running.add(e),{kind:`started`,done:this.loop(e,t)})}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 cb={showSha:!0,showStashCount:!0};function lb(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function ub(e){let t=t=>{try{return r.statSync(c.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function db(e,t){return e.head!==t.head||e.index!==t.index}function fb(e){let t=[],n=c.join(e,`refs/heads`);try{r.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[c.join(e,`HEAD`),c.join(e,`index`)],dirs:t}}var pb=class extends eb{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new sb;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new eb,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??ib,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new ob({logger:this.logger}),this.ownsWatchers=!0);let t=e.sanityIntervalMs??3e5;t>0&&(this.sanityTimer=setInterval(()=>this.runSanityCheck(),t),this.sanityTimer.unref())}getWatcherRegistry(){return this.watchers}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,invalidations:this.invalidations,watchers:this.watchers.size()}}resolveEffectiveGitDir(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.resolutions.delete(n),this.resolutions.set(n,i),i.dir;let a=this.inner.resolveEffectiveGitDir(e,t);return this.resolutions.set(n,{dir:a,computedAt:r}),a.catch(()=>{this.resolutions.get(n)?.dir===a&&this.resolutions.delete(n)}),this.evictResolutionsIfNeeded(),a}evictResolutionsIfNeeded(){for(;this.resolutions.size>this.maxEntries;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}}async getGitInfo(e,t={},n){let r=await this.resolveEffectiveGitDir(e,n);return r.kind===`ok`?this.getGitInfoForRoot(r.value,t):r}getGitInfoForRoot(e,t){let n=`${e}|${lb(t)}`,r=Date.now(),i=this.entries.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.entries.delete(n),this.entries.set(n,i),this.hits++,Promise.resolve(J(i.info));let a=this.fetchInFlight.get(n);if(a)return a;let o=this.doFetch(e,n,t,r).finally(()=>{this.fetchInFlight.delete(n)});return this.fetchInFlight.set(n,o),o}async doFetch(e,t,n,r){this.misses++;let i=this.inner.resolveGitDir(e),a=ub(i),o=await this.inner.getGitInfo(e,n);if(o.kind!==`ok`)return o;let s=o.value;n.showPullRequest&&(s.pullRequest=await this.getPullRequestCached(e,s.branch)),this.dropEntry(t);let c=this.watchers.acquire(`git:${e}`,fb(i),()=>this.invalidateRepo(e));return this.entries.set(t,{info:s,computedAt:r,mtime:a,watcher:c,repoRoot:e}),this.evictIfNeeded(),o}async getPullRequestCached(e,t){let n=await this.inner.getRepoRemoteUrl(e);if(n.kind===`failed`)return n;if(n.kind===`absent`)return Y;let r=n.value,i=`${e}|${t}|${r}`,a=Date.now(),o=this.prCache.get(i);if(o){let e=o.pr.kind===`failed`?45e3:3e5;if(a-o.computedAt<e)return this.prCache.delete(i),this.prCache.set(i,o),o.pr}let s=this.prFetchInFlight.get(i);if(s)return s;let c=this.inner.resolvePullRequest(e,r).then(e=>(this.prCache.set(i,{pr:e,computedAt:Date.now()}),this.evictPrIfNeeded(),e)).finally(()=>{this.prFetchInFlight.delete(i)});return this.prFetchInFlight.set(i,c),c}evictPrIfNeeded(){for(;this.prCache.size>this.maxEntries;){let e=this.prCache.keys().next().value;if(e===void 0)break;this.prCache.delete(e)}}deliverable(e,t){return e.kind===`failed`?(this.logger(`warn`,`git fetch failed (${t}): ${e.reason}`),null):e.kind===`ok`?e.value:null}subscribe(e,t){let n=!1,r=null;return{firstDelivery:(async()=>{let i=await this.resolveEffectiveGitDir(e);if(n)return;if(i.kind!==`ok`){i.kind===`failed`&&this.logger(`warn`,`git resolve failed (subscribe ${e}): ${i.reason}`),this.safeInvoke(t,null);return}let a=i.value,o=this.subscribersByRepo.get(a);if(!o){let t=this.inner.resolveGitDir(a),n=this.watchers.acquire(`git:${a}`,fb(t),()=>this.invalidateRepo(a));o={workingDir:e,repoRoot:a,callbacks:new Set,watcher:n},this.subscribersByRepo.set(a,o)}o.callbacks.add(t),r={repoRoot:a,entry:o};let s=await this.getGitInfoForRoot(a,{...cb});n||this.safeInvoke(t,this.deliverable(s,a))})(),unsubscribe:()=>{if(n=!0,!r)return;let{repoRoot:e,entry:i}=r;i.callbacks.delete(t),i.callbacks.size===0&&(i.watcher.release(),this.subscribersByRepo.delete(e))}}}invalidateRepo(e){let t=0;for(let[n,r]of this.entries)r.repoRoot===e&&(r.watcher.release(),this.entries.delete(n),t++);t>0&&(this.invalidations+=t,this.logger(`info`,`gitCache invalidate ${e} dropped=${t}`)),this.refreshSubscribers(e)}refreshSubscribers(e){let t=this.subscribersByRepo.get(e);!t||t.callbacks.size===0||this.refreshes.run(e,()=>this.refreshOnce(e))}async refreshOnce(e){let t=this.subscribersByRepo.get(e);if(!t||t.callbacks.size===0)return;let n=await this.getGitInfoForRoot(e,{...cb}),r=this.deliverable(n,e),i=this.subscribersByRepo.get(e);if(!(!i||i.callbacks.size===0))for(let e of[...i.callbacks])i.callbacks.has(e)&&this.safeInvoke(e,r)}safeInvoke(e,t){try{e(t)}catch(e){this.logger(`warn`,`git subscriber threw: ${e.message??String(e)}`)}}dropEntry(e){let t=this.entries.get(e);t&&(t.watcher.release(),this.entries.delete(e))}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.dropEntry(e),this.logger(`info`,`gitCache evict ${e}`)}}runSanityCheck(){let e=new Map;for(let t of this.entries.values()){let n=e.get(t.repoRoot);n||(n=ub(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),db(t.mtime,n)&&this.invalidateRepo(t.repoRoot)}}runSanityCheckNow(){this.runSanityCheck()}close(){this.sanityTimer&&=(clearInterval(this.sanityTimer),null);for(let e of this.entries.values())e.watcher.release();this.entries.clear();for(let e of this.subscribersByRepo.values())e.callbacks.clear(),e.watcher.release();this.subscribersByRepo.clear(),this.refreshes.clear(),this.fetchInFlight.clear(),this.prCache.clear(),this.prFetchInFlight.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}};const mb=/\r\n|\r|\n/g,hb=e=>J(e.replace(mb,` `).trim());function gb(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?X(`regex no-match`):J(n.replace(mb,` `))}}const _b=e=>{try{return J(JSON.parse(e))}catch(e){return X(`JSON parse failed: ${e.message}`)}};function vb(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(O(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function yb(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const bb=`session.id`;function xb(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await ke({bin:`/bin/sh`,args:[`-c`,e],cwd:t,category:`user-shell`,signal:n});if(!r.ok&&r.reason===`aborted`)throw n.reason;return r.ok?J(r.stdout):X(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function Sb(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await S(e,{encoding:`utf8`,signal:n});return J(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return X(`file unreadable: ${e}`)}}}}function Cb(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?X(`${r.reason} in ${n}`):r}const wb=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Tb=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Eb=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],Db=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function Ob(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>wb[e.getMonth()]],[`Monday`,e=>Eb[e.getDay()]],[`Jan`,e=>Tb[e.getMonth()]],[`Mon`,e=>Db[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const kb={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function Ab(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=kb[t];try{return Pb(r,e)}catch{return Fb(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return jy(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return jy(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return jy(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return jy(e.stashCount,0)}}var jb=class{watchers=new Map;subscribe(e,t){let n=this.watchers.get(e);if(!n){let t=new Set,r;try{r=s(e,()=>{for(let e of t)e()})}catch{return()=>{}}n={watcher:r,callbacks:t},this.watchers.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(n.watcher.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e.close();this.watchers.clear()}size(){return this.watchers.size}},Mb=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:te(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(ee(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())ee(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function Nb(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function Pb(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`?Fv(e):t===`number`?Iv(e):Lv(e)}function Fb(e){return e===`number`?0:e===`boolean`?!1:``}var Ib=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new jb;ttlMgr=new Mb;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new sb;abort=new AbortController;drawn=Mv.observable.box(F.TRUECOLOR);drawnAt=()=>this.drawn.get();engine=Ey(void 0,void 0,this.drawnAt);gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new pb({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Pv(t),t)}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,xb(t,n.cwd,this.abort.signal),vb(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,Sb(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,hb,t.default,n);case`regex`:return this.scalarPublisher(e,gb(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=Cb(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,jy(a,i))}}documentPublisher(e,t,n){let r=t===void 0?Y:J(t);return this.store.defineDocument(e,r),i=>{let a=Cb(i,_b,n);this.noteOutcome(e,a),this.store.setDocument(e,a.kind===`ok`||t===void 0?a:r)}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.store.defineComputed(e,`string`,t=>{let i=Dy(this.store);try{let t=r.evaluate(i).map(e=>e.plain).join(``);return this.lastErrors.delete(e),t}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n.varDefault===void 0)throw Error(`variable "${e}": ${r}`);return n.varDefault}});try{this.store.read(e)}catch{}}declareTime(e,t){let n=t.ttlMs??1e3;this.store.defineBox(e,`string`,(e=>{try{return Ob(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,Ob(t.format,new Date)),this.lastErrors.delete(e)}catch(n){this.applyFallback(e,`string`,t.varDefault,n instanceof Error?n.message:String(n))}});this.cleanups.push(r)}declareGit(e,t){let n=kb[t.field],r=t.varDefault===void 0?Fb(n):Pb(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,Ab(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(bb);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=Nb(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,Pb(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}drawAt(e){this.store.runInAction(()=>this.drawn.set(e))}getLastError(e){return this.lastErrors.get(e)}dispose(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let e=this.watchMgr.subscribe(t.path,n);this.cleanups.push(e);break}case`key`:{let e=this.engine.parse(t.template),r=(0,Mv.reaction)(()=>{let t=Dy(this.store);try{return e.evaluate(t).map(e=>e.plain).join(``)}catch{return``}},n);this.cleanups.push(r);break}case`depends_on`:{let e=(0,Mv.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,Pb(this.defaultEmptyValue,t))}catch{this.store.setBox(e,Fb(t))}}defaultFor(e){try{return Pb(this.defaultEmptyValue,e)}catch{return Fb(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};const Lb={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[bb]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`,default:``},config_path:{kind:`input`,path:`configPath`,default:``},"theme.effective":{kind:`input`,path:`theme.effective`,default:``},"style.effective":{kind:`input`,path:`style.effective`,default:``},"preset.effective":{kind:`input`,path:`preset.effective`,default:``},"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},"endcaps.effective":{kind:`input`,path:`endcaps.effective`,default:``},"variation.effective":{kind:`input`,path:`variation.effective`,default:``},"charset.effective":{kind:`input`,path:`charset.effective`,default:``},"colorCompatibility.effective":{kind:`input`,path:`colorCompatibility.effective`,default:``},"autoWrap.effective":{kind:`input`,path:`autoWrap.effective`,type:`boolean`,default:!0},"padding.effective":{kind:`input`,path:`padding.effective`,type:`number`,default:1},"updateNotice.effective":{kind:`input`,path:`updateNotice.effective`,type:`boolean`,default:!0},"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:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},Rb=`ne .tmux.pane ""`,zb={theme:{configKey:`palette`,sessionKey:`theme`,effectiveVar:`theme.effective`,label:`🎨`},preset:{configKey:`preset`,sessionKey:`preset`,effectiveVar:`preset.effective`,label:`▦`},style:{configKey:`style`,sessionKey:`style`,effectiveVar:`style.effective`,label:`◐`},endcaps:{configKey:`endcaps`,sessionKey:`endcaps`,effectiveVar:`endcaps.effective`,label:`✦`},variation:{configKey:`variation`,sessionKey:`variation`,effectiveVar:`variation.effective`,label:`🎼`},autoWrap:{configKey:`autoWrap`,sessionKey:`autoWrap`,effectiveVar:`autoWrap.effective`,label:`wrap`},padding:{configKey:`padding`,sessionKey:`padding`,effectiveVar:`padding.effective`,label:`padding`},updateNotice:{configKey:`updateNotice`,sessionKey:`updateNotice`,effectiveVar:`updateNotice.effective`,label:`update notice`}},Bb=Object.values(zb),Vb=[{configKey:`charset`,effectiveVar:`charset.effective`},{configKey:`colorCompatibility`,effectiveVar:`colorCompatibility.effective`}],Hb=new Set(Vb.map(e=>e.configKey)),Ub=new Map([...Bb,...Vb].map(e=>[e.configKey,e.effectiveVar])),Wb=new Map(Bb.map(e=>[e.sessionKey,e.effectiveVar]));function Gb(e){return Object.fromEntries(Object.keys(zb).map(t=>[t,e(t)]))}const Kb=new Map(Object.keys(zb).map(e=>[zb[e].sessionKey,e]));function qb(e,t,n){let r=new Set,i=e=>{for(let t of xv(e??``,n).keys())r.add(t)};for(let t of Object.values(e.segments))i(t.template),i(t.bg),i(t.fg),i(t.when);for(let e of t)for(let t of Ps(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(bb);for(let t of Object.values(e.actions)){r.add(bb),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?Wb.get(t.set):void 0,n=`persist`in t?Ub.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function Jb(e,t,n){let r=Ov({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of qb(e,t,n.helpers)){if(Dv(a,r))continue;let e=Lb[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}const Yb=new Map,Xb=new Map;function Zb(e){let t=$b(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 Qb(e,t){return e===`bar`?t:Zb(e)}function $b(e){let t=Yb.get(e);if(t!==void 0)return t;let n=Er(e);return n===null?null:(Yb.set(e,n),n)}function ex(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=Xb.get(n);if(r!==void 0)return r;let i=Pr(e,t);return Xb.set(n,i),i}function tx(e){let t=$b(e);return t===null?null:{kind:`decided`,name:e,value:t}}function nx(e,t,n){let r=tx(e);return r===null?(n(`${t} rendered "${Za}": "${e}" names no installed theme${Xa(e)}`),ix()):r}function rx(e,t,n){return oo(e,t,n,ix(),tx)}function ix(){return tx(Za)}function ax(e){return so(rx(void 0,null,e),ix).value}const ox=new Map;function sx(e,t,n){ox.set(e,{permanent:!0,resolve:t,paletteOf:n})}sx(`themes`,()=>$a(),e=>Zb(e));const cx=`placementThemes`;sx(cx,eo,(e,t)=>Qb(e,t.palette)),sx(`endcaps`,()=>po),sx(`variations`,()=>bo),sx(`charsets`,()=>go),sx(`colorCompatibilities`,()=>vo);function lx(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>ex(n.basePalette,e.styles[t])}],[`presets`,{members:j_(e.presets)}]])}function ux(e){return[...new Set([...ox.keys(),...e.keys()])]}function dx(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=ox.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf};throw Error(px(e,t))}const fx=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function px(e,t){let n=fx.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${ux(t).join(`, `)})`}function mx(e,t,n){return e===`bool`?Do(t)!==null:`from`in e?dx(e.from,n).members.includes(t):Oo(t,e)!==null}function hx(e,t){if(e===`bool`)return To.join(` or `);if(`from`in e){let{members:n}=dx(e.from,t),r=n.map(e=>JSON.stringify(e));if(n.length<=8)return`one of ${r.join(`, `)}`;let i=typeof e.from==`string`?` "${e.from}"`:``;return`one of the ${n.length}${i} names, such as ${r.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function gx(e){return{label:e.label,domain:_x(e.domain)}}function _x(e){return e===`theme`?{from:cx}:e===`bool`||`min`in e?e:{from:e}}function vx(e,t,n,r,i){let a=Xc(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...To]}},variables:{}};if(`from`in o)return yx(a,t,r,i,o.from);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 yx(e,t,n,r,i){let a={variable:r,key:r,member:n},o=C_(r,n),s=`${n}.open`,c=w_(r),l=`${c}.first`;return{kind:`picker`,template:`{{ "${e}" }} {{ carousel "${n}" 0 "${s}" }}`,actions:{[n]:{set:t,from:i},[o]:il(r,n),[c]:{set:c,int:!0},[l]:{set:c,to:`0`},[s]:{do:[o,l]}},variables:{[r]:rl(r,Kc),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,template:`{{ picker "${n}" "${c}" false true true }}`}}}const bx=/^segments\.([^.]+)\.palette$/,xx=/^presets\.(.+)\.root$/,Sx=/^presets\.(.+)\.globals\.([^.]+)$/;function Cx(e){return`presets.${e}.root`}function wx(e,t){return`presets.${e}.globals.${t}`}function Tx(e){if(Ml(e))return{scope:`globals`,field:e};let t=bx.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=Sx.exec(e);if(n&&Tl(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=xx.exec(e);return r?{scope:`preset-root`,preset:r[1]}:null}function Ex(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`]}}const Dx=`open`;function Ox(e,t,n,r){let i={variable:e,key:e,member:Dx};return r.variables[e]=rl(e,Kc),r.actions[e]=il(e,Dx),r.segments[e]={template:el(e,`(?)`,`✕`),...kx(n)},Zc(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 kx(e){let[t,...n]=e;return t===void 0?{}:{when:Qc(t,...n)}}const Ax=`none`;var jx=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function Mx(e,t,n,r,i){let{palette:a,tint:o}=e,s=Nx(n,i),c=s!==Ax,l=c?s===void 0?o:Px(a,s,`bg`):Px(a,`background`,`bg`);e.bg=l;let u=Nx(r,i),d=u===void 0?c?ja(a,l,t):void 0:Px(a,u,`fg`);return new V({...c&&{bgcolor:L.fromRgba(l)},...d!==void 0&&{color:L.fromRgba(d)}})}function Nx(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function Px(e,t,n){try{return er(e,t)}catch(e){throw e instanceof Zn?new jx(t,n,e.message):e}}const Fx={help:[`-h`,`--help`],version:[`-V`,`--version`]},Ix=[`✚ inserts`,`✖ removes`,`⚙️ configures`,`↺ resets layout`],Lx=`
91
91
  cc-candybar - Beautiful powerline statusline for Claude Code
92
92
 
93
93
  Usage: cc-candybar [options]
94
94
 
95
95
  Standalone Commands:
96
- ${Nx.help.join(`, `).padEnd(25)}Show this help
97
- ${Nx.version.join(`, `).padEnd(25)}Print the version of this runtime (cc-candybar <version>)
96
+ ${Fx.help.join(`, `).padEnd(25)}Show this help
97
+ ${Fx.version.join(`, `).padEnd(25)}Print the version of this runtime (cc-candybar <version>)
98
98
 
99
99
  Debugging:
100
100
  CC_CANDYBAR_DEBUG=1 Enable debug logging for troubleshooting
@@ -117,7 +117,7 @@ Configuration:
117
117
  failed row's [fix] to repair it (the same checks \`cc-candybar doctor\` runs).
118
118
 
119
119
  Anywhere the bar shows (?), clicking it reveals these same instructions
120
- in place. In edit mode: ${Px.join(`, `)}.
120
+ in place. In edit mode: ${Ix.join(`, `)}.
121
121
 
122
122
  Subcommands:
123
123
  install One-shot setup: stages the runtime (native render
@@ -158,27 +158,27 @@ Config tooling:
158
158
  config [--json] The effective merged config. (All three query the
159
159
  running daemon; none spawn one.)
160
160
 
161
- `,Ix=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`,Lx={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function Rx(e){let t=e[Lx.socket]??``,n=e[Lx.pane]??``;if(t===``||n===``)return null;let r=e[Lx.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}function zx(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const Bx=Lx.truecolor,Vx={name:`tmuxTruecolor`,label:`tmux truecolor`,probe:({tmux:e,claudeSettings: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`:{if(e.termfeatures.kind===`failed`)return{ok:!1,reason:`tmux could not be asked: ${e.termfeatures.reason}`};if(!e.termfeatures.value.includes(`RGB`)||e.hint.truecolor!==null)return{ok:!0};let n=t.env[Bx];return typeof n==`string`&&n!==``?{ok:!1,reason:`${Bx} is set in ${t.path} — restart Claude Code to apply`}:{ok:!1,reason:`Claude Code renders the bar in 256 colours inside tmux`,fix:{kind:`claude-settings-env`,name:Bx,value:`1`}}}}}},Hx={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},Ux={name:`config`,label:`config`,probe:({config:e})=>{switch(e.kind){case`failed`:{let[t=`the config failed to load`,...n]=[...e.error.split(`
162
- `).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return zx([...e.warnings,...e.shadowed.map(t=>`${t} is never read — ${e.path??`another config`} is found first`),...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${Hx[e]}`)])}}},Wx="re-run `cc-candybar install`";function Gx(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:// — ${Wx}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${Wx}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${Wx}`)}const Kx=[Ux,{name:`urlHandler`,label:`URL handler`,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${Wx}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${Wx}`};case`lost`:return zx([...Gx(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}`])}}},Vx];function qx(e){return Kx.map(t=>({check:t,verdict:t.probe(e)}))}function Jx(e){return Kx.find(t=>t.name===e)}const Yx=`${Eu}doctor.`;function Xx(e){let t=`${Yx}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`}}function Zx(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function Qx(e){return e.flatMap(({check:e,verdict:t})=>{let n=Xx(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:``},{key:n.fixable,value:wo}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:Zx(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?wo:Co}]})}const $x={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function eS(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries($x).map(([t,n])=>[`${e}${t}`,n]))}}const tS=`armed`,nS=`disarmed`,rS=`.armed`,iS=e=>e.endsWith(rS);function aS(e,t,n){let r=`${e}${rS}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${tS}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:tS},[a]:{set:r,to:nS},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:nS}},disarm:a}}const oS=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function sS(e){return typeof e==`string`&&oS.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 cS(e){let t=sS(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const lS=[`/compact`,`/model`],uS=`/clear`;function dS(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=aS(`${e}clear`,{arm:uS,confirm:`${uS} ✓ confirm`},[n]);return{template:lS.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${Rb} }}`,actions:{...Object.fromEntries(lS.map(e=>[t(e),{slash:cS(e)}])),...r.actions,[n]:{slash:cS(uS)}},variables:r.variables,disarm:r.disarm}}function fS(e,t){let n=(e.CLAUDE_CONFIG_DIR??``).split(`,`)[0].trim();return n===``?void 0:c.resolve(t,n)}function pS(e){return e??c.join(m.homedir(),`.claude`)}function mS(e){return c.join(e,`settings.json`)}function hS(e){return c.join(e,`plugins`,`installed_plugins.json`)}function gS(e){return r.existsSync(e)?r.readFileSync(e,`utf8`):``}function _S(e){let t;try{let n=gS(e);if(/^\s*$/.test(n))return{};t=Jo.parse(n)}catch(t){throw Error(`cannot read ${e}: ${vS(t)}`,{cause:t})}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`cannot read ${e}: not a JSON object`);return t}const vS=e=>e instanceof Error?e.message:String(e),yS=Array.from({length:10},(e,t)=>(t+1)*1e5),bS=yS[0],xS=yS[yS.length-1];function SS(e){let t;try{t=_S(e)}catch(e){return X(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?J(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=bS&&n<=xS?J(n):X(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${bS}–${xS} tokens)`)}function CS(e,t){let n=Math.min(t??xS,xS),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:yS.filter(e=>e<r).at(-1)??0,higher:yS.find(e=>e>r&&e<=n)??0}}function wS(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${Rb} }}{{ 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:cS(`/autocompact auto`)},...Object.fromEntries(yS.map(t=>[`${e}${t}`,{slash:cS(`/autocompact ${t}`)}]))}}}const TS=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 }}`,ES=`${Eu}menu`,DS=`open`,OS=`${Eu}edit`,kS=`${Eu}toolbar`,AS=eS(Eu),jS=`${Eu}commands`,MS=dS(`${jS}.`),NS=`${Eu}autocompact`,PS=wS(`${NS}.`,TS),FS=e=>({kind:`segment`,name:e}),IS=`${Eu}tab`,LS=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],RS=e=>`${IS}.${e}`,zS=e=>`${RS(e)}.toggle`,BS=e=>({variable:IS,key:IS,member:e}),VS=`${Eu}save`,HS=`${Eu}preset.save`,US=`${Eu}preset.delete`,WS=`${Eu}resetAll`,GS=`${ES}.toggle`,KS={variable:ES,key:ES,member:DS},qS=`${Eu}undo`,JS=`${Eu}back`,YS=`${JS}.step`,XS=`${Eu}navigation.back`,ZS=JS,QS={template:`{{ if gt .${XS} 0 }}{{ action "${JS}" "◁" }}{{ else }}{{ fg (${Ix}) "◁" }}{{ end }}`},$S=`${Eu}redo`,eC=`${Eu}doctor`,tC=`${eC}.run`,nC=e=>`${eC}.fix.${e}`,rC=e=>`${eC}.${e}`,iC=S_(`${Eu}pickers`),aC=[{template:`{{ themePreview }}`}],oC={template:`{{ layoutPreview }}`},sC={preset:[oC,{when:`{{ not .preset.bundled }}`,template:`{{ action "${US}" (printf "🗑 delete %s" .${zb.preset.effectiveVar}) }}`}],theme:aC,style:aC,variation:[oC]},cC=e=>`${Eu}${e}`,lC=e=>`${Eu}apply.${e}`,uC=e=>`${Eu}reset.${e}`,dC=e=>`${Eu}list.${e}`,fC=(e,t)=>`${dC(e)}.${t}`,pC=e=>`${Eu}resettable.${e}`,mC=e=>e.length===0?`false`:`(or ${e.map(e=>`.${pC(e)}`).join(` `)})`,hC=Object.keys(zb).map(e=>{let t=zb[e],n=gl(t.configKey),r=gx({label:t.label,domain:n},t.sessionKey,t.effectiveVar,lC(e),iC);return{...t,name:e,control:r,beneath:sC[e]??[]}}),gC={preset:`door`,theme:`look`,style:`look`,variation:`look`,endcaps:`look`,autoWrap:`layout`,padding:`layout`,updateNotice:`config`},_C=e=>hC.filter(t=>gC[t.name]===e),vC=e=>_C(e).map(AC);new Set(hC.flatMap(e=>[e.sessionKey,e.configKey]));const yC=aS(WS,{arm:`⟲`,confirm:`⟲ reset all?`},hC.map(e=>uC(e.name))),bC=[`unsaved`,`history.undo`,`history.redo`],xC=e=>`${Eu}${e}`,SC=xC(`unsaved`),CC=(e,t)=>({body:t,shown:`(gt .${xC(e)} 0)`}),wC=[CC(`unsaved`,`{{ action "${VS}" (printf "💾 save %d" .${SC}) }}`),CC(`history.undo`,`{{ action "${qS}" "↶" }}`),CC(`history.redo`,`{{ action "${$S}" "↷" }}`),{body:yC.template,shown:`(or ${mC(hC.map(e=>e.name))} ${yC.armed})`}],TC={when:`{{ or ${wC.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+wC.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},EC=[{step:yC,place:`door`},{step:MS,place:`session`}],DC=e=>e.map(e=>e.step.disarm),OC=DC(EC),kC=DC(EC.filter(e=>e.place!==`door`));function AC(e){let t=cC(e.name);return e.control.kind===`inline`?FS(t):Zc(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[FS(dC(e.name)),...e.beneath.map((t,n)=>FS(fC(e.name,n)))]},`drop`)}function jC(e){return e===ES}function MC(e){let t=FS(ES);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[MC(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}return e.kind===`container`&&e.when===void 0?{...e,children:[t,...e.children]}:{kind:`container`,direction:`horizontal`,children:[t,e]}}function NC(e){return PC(e)>0?e:MC(e)}function PC(e){let t=0;for(let n of Ps(e))n.kind===`segment`&&jC(n.name)&&(t+=1);return t}function FC(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&jC(e.name)||e.opens!==void 0&&FC(e.opens.body,!0):e.children.some(e=>FC(e,n))}const IC={session:{direction:`vertical`,content:[FS(kS),{kind:`container`,direction:`horizontal`,children:[FS(jS),FS(NS)]}]},look:{direction:`horizontal`,content:[]},layout:{direction:`horizontal`,content:[FS(HS),FS(OS)]},config:{direction:`horizontal`,content:[]},tools:{direction:`vertical`,content:[FS(eC),...Kx.map(e=>FS(rC(e.name)))]}},LC=e=>({kind:`container`,direction:IC[e].direction,children:[...IC[e].content,...vC(e)]});function RC(e){return e.kind===`segment`?jC(e.name)?Zc(e.name,KS,BC,`above`):e:HC(e)}function zC(){return{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[FS(ZS),...vC(`door`),FS(VS)]},{kind:`container`,direction:`horizontal`,children:LS.map(({member:e})=>Zc(RS(e),BS(e),LC(e),`drop`))}]}}const BC=zC();function VC(e){let t=new Map;for(let e of Ps(BC))e.kind===`segment`&&e.opens!==void 0&&t.set(e.opens.ref.key,e.opens.ref.variable);return[...t].map(([t,n])=>{let r=e.variables[n];if(r?.kind!==`state`||r.default===void 0)throw Error(`settings menu: the door folds "${t}", but "${n}" is not a state variable the menu declares with a default`);let i=`${ES}.fold.${Su(t)}`;return e.actions[i]={set:t,to:r.default},i})}function HC(e){return{...e,children:e.children.map(e=>RC(e))}}function UC(e){let t={variables:{[ES]:rl(ES,Kc)},actions:{[GS]:il(ES,DS),[tC]:{doctor:`run`},[OS]:{do:[...$_]},...AS.actions,...MS.actions,...PS.actions,[VS]:{save:!0},[qS]:{undo:!0},[YS]:{back:!0},[JS]:{do:[YS,...OC]},[$S]:{redo:!0},[HS]:{preset:`save`},[US]:{preset:`delete`,name:`{{ .${zb.preset.effectiveVar} }}`}},segments:{[ES]:{template:`{{ $door := ${tl(ES,nl(e),nl(`✖`))} }}{{ if ${$c(KS)} }}{{ fg (color "error") $door }}{{ else }}{{ $door }}{{ end }}`},[kS]:{template:AS.template},[jS]:{template:MS.template,when:MS.when},[NS]:{template:PS.template,bg:PS.bg,when:PS.when},[ZS]:QS,[VS]:TC,[HS]:{template:`{{ action "${HS}" "+ preset" }}`},[eC]:{template:`{{ action "${tC}" "🩺 doctor" }}`},[OS]:{template:`{{ action "${OS}" "✎ arrange" "✎ done" }}`}}};t.variables[XS]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of bC)t.variables[xC(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[IS]=rl(IS,`session`);for(let{member:e,label:n}of LS){t.actions[zS(e)]=il(IS,e),t.actions[RS(e)]={do:[zS(e),...kC]};let r=mC(_C(e).map(e=>e.name)),i=`(ternary ${nl(` •`)} "" ${r})`,a=e=>`(print ${nl(e)} ${i})`;t.segments[RS(e)]={template:`{{ ${tl(RS(e),a(n),a(`▾ ${n}`))} }}`}}return Object.assign(t.variables,MS.variables,yC.variables),GC(t),WC(t),t.actions[ES]={do:[GS,...OC,...VC(t)]},t}function WC(e){for(let t of Kx){let n=Xx(t.name),r=nC(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},e.segments[rC(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${Co}" }} {{ action "${r}" "[fix]" }}{{ end }}{{ end }}`}}}function GC(e){for(let t of hC){Object.assign(e.actions,t.control.actions);let n=uC(t.name);e.actions[n]={reset:t.configKey},e.variables[pC(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${pC(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[cC(t.name)]={template:`${t.control.template}${r}`},t.control.kind===`picker`&&(e.segments[dC(t.name)]={template:t.control.list.template}),t.beneath.forEach((n,r)=>{e.segments[fC(t.name,r)]=n})}Object.assign(e.actions,yC.actions)}function KC(e){let{variables:t,actions:n}=cv();Object.assign(e.variables,t),Object.assign(e.actions,n)}function qC(e){let t=UC(e.globals.menuGlyph??`🍫`);KC(t);let n={...e.presets},r=[];for(let t of j_(e.presets)){let{node:i}=P_(e,t),a=RC(NC(i));r.push(a),n[t]={...N_(e.presets,t),root:a}}let i=Jb(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const JC=`${Tu}live`,YC=[`☐ live`,`☑ live`],XC=`${Tu}done`,ZC=`${Tu}cancel`,QC=`${Tu}rewind`,$C=`${Tu}changes`,ew=`(gt .${$C} 0)`,tw=`(or ${ew} (gt .${SC} 0))`,nw={variable:JC,key:JC,member:`open`};function rw(e){return`${Tu}configuring.p${e}`}function iw(e){return`and ${$c(rv)} (not ${$c(nw)}) (ne .${rw(e)} "true")`}function aw(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${X_} "${Xc(e)}")`).join(` `)} false }}`}}function ow(e,t,n){return`{{ if ${iw(e)} }}${t}{{ else }}${n}{{ end }}`}const sw=`{{ and ${$c(rv)} .preset.customized }}`,cw=Ou,lw=`${Tu}addable`;function uw(e){return new Map([[lw,{members:Object.keys(e.segments).filter(e=>!cw(e)),library:{groups:bu.map(e=>({id:e,label:xu[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function dw(e,t,n){return n.segments[e]={template:t,when:iv,bg:Ox},{kind:`segment`,name:e}}function fw(e,t,n){let r=`${Tu}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Aa}`}) (action "${r}" "✖") }}`}function pw(e){return`{{ if ${$c(rv)} }}${e}{{ end }}`}function mw(e,t){return e.reduce((e,t)=>`{{ if and ${$c(rv)} ${$c(t)} }}true{{ else }}${e}{{ end }}`,t)}function hw(e){return e.flatMap(e=>[...Ps(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function gw(e,t,n){return`${tv}${e}.${t}.${n}`}function _w(e,t,n,r){let i=As(n),a=`${Tu}${e.presetIdent}`,o=nv(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=S_(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:Kc},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:X_,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=gw(e.presetIdent,i,r),l=`${tv}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Js(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=gx(mx(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};let p=`${d}.list`;return e.artifacts.segments[d]={template:f.template},e.artifacts.segments[p]={template:f.list.template},Zc(d,f.list.ref,{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:p}]},`drop`)});return{term:`{{ action "${s}" "⚙️" }}`,ref:{variable:X_,key:X_,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const vw=`${Tu}label:`;function yw(e){if(e.startsWith(vw)){let t=e.slice(vw.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function bw(e,t,n,r){let{artifacts:i}=n,a=As(e),o=`${vw}${a}:${e.name}`;i.segments[o]={template:`{{ "${Xc(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=e.settings?.[Us];return{...Zc(o,r.ref,r.body,`drop`,mw([r.ref],`{{ ${iw(n.presetIdent)} }}`)),...s!==void 0&&{settings:{theme:s}},drafts:{[Us]:r.drafts[Us]}}}function xw(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${Tu}${i}.insert.${t}`,s=`${Tu}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:lw,anchor:n,relation:r};let c=b_(o),l=x_(s,o,void 0),u=w_(l),d=C_(l,c);return a.variables[l]=rl(l,Kc),a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=il(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${$c({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Aa}`}) $m }}{{ end }}`}}function Sw(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!cw(e.name)),i=e=>Sw(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Ns(o,i);if(cw(o.name)){n.push(s);continue}let c=As(o),l=a===r?[xw(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=xw(t,u,c,`after`),f=fw(t,u,c),p=t.segments[o.name],m=_w(t,u,o,Ws(p)),h=pw(f),g=pw(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>dw(e.host,e.template,t.artifacts)),{...bw(o,p,t,m),lead:h,trail:g},{...s,when:ow(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},dw(d.host,d.template,t.artifacts)]};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[_]}:_)}return{...e,children:n,...e.when!==void 0&&{when:mw(hw(n),ow(t.presetIdent,`true`,e.when))}}}function Cw(e,t,n,r,i,a,o){let s=`${Tu}${t}.resetLayout`,c=`${Tu}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:sw},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},ww(e,o)]}}function ww(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),ww(n,t)]}:{...e,children:[...e.children,t]}}function Tw(e,t,n,r,i,a){let{node:o}=P_(e,t),s={presetIdent:Su(t),rootKey:xx(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=Sw(o,s);return n.variables[rw(s.presetIdent)]=aw(s.configured),Cw(c,s.presetIdent,s.rootKey,n,r,i,a)}function Ew(e){let t={variables:{},actions:{},segments:{}},n=Ex(`${Tu}help`,Px,[rv],t);t.variables[JC]=rl(JC,Kc),t.actions[JC]=il(JC,nw.member),t.segments[JC]={template:el(JC,...YC),when:iv};let r={kind:`segment`,name:JC},i=n;t.variables[$C]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[XC]={do:[VS,...$_]},t.segments[XC]={template:`{{ if ${tw} }}{{ action "${XC}" "✓ save" }}{{ else }}{{ action "${XC}" "✓ done" }}{{ end }}`,when:iv},t.actions[QC]={rewind:!0},t.actions[ZC]={do:[QC,...$_]},t.segments[ZC]={template:`{{ action "${ZC}" "↩ cancel" }}`,when:`{{ and ${$c(rv)} ${ew} }}`};let a=[{kind:`segment`,name:XC},{kind:`segment`,name:ZC}],o={...e.presets},s=[];for(let n of j_(e.presets)){let c=Tw(e,n,t,a,r,i);s.push(c),o[n]={...N_(e.presets,n),root:c}}let c=Jb(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}const Dw=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`doctor`,`ceiling`,`slash`,`do`];function Ow(e){return e.ceiling===`set`?[`set`,e.to]:[`clear`]}function kw(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function Aw(e,t){if(t===void 0)return{};if(!ic(t))return Q(e,`actions`,`actions must be an object, got ${ac(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=jw(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Q(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function jw(e,t,n){if(!ic(n))return Q(e,t,`${t} must be an action object, got ${ac(n)}`),null;if(`persistWhen`in n)return Q(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 r=Dw.filter(e=>e in n);return r.length===1?Mw[r[0]](e,t,n):(Q(e,t,`action must declare exactly one of: ${Dw.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const Mw={set:(e,t,n)=>uT(e,t,n,`set`,oT),persist:(e,t,n)=>uT(e,t,n,`persist`,sT),copy:Nw(`copy`),open:Nw(`open`),reset:Pw,undo:Iw(`undo`),redo:Iw(`redo`),back:Iw(`back`),rewind:Iw(`rewind`),save:Iw(`save`),preset:Lw,doctor:Rw,ceiling:zw,slash:Bw,do:Vw};function Nw(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=$s(t,n,r,e);return i===null?null:{[e]:i}}}function Pw(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=Hw(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 Fw={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 Iw(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Q(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${Fw[e]}), got ${K(r[e])}`),null)}}function Lw(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Q(e,`${t}.preset`,`preset must be "save" or "delete", got ${K(r)}`),null;if(r===`save`)return{preset:`save`};let a=$s(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function Rw(e,t,n){let r=n.doctor,i=r===`run`?[`doctor`]:[`doctor`,`check`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${i.join(`, `)}`);if(r!==`run`&&r!==`fix`)return Q(e,`${t}.doctor`,`doctor must be "run" or "fix", got ${K(r)}`),null;if(r===`run`)return{doctor:`run`};let a=n.check;return typeof a!=`string`||Jx(a)===void 0?(Q(e,`${t}.check`,`doctor fix must name a check (have: ${Kx.map(e=>e.name).join(`, `)}), got ${K(a)}`),null):{doctor:`fix`,check:a}}function zw(e,t,n){let r=n.ceiling,i=r===`clear`?[`ceiling`]:[`ceiling`,`to`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a ceiling action. Expected only: ${i.join(`, `)}`);if(r===`clear`)return{ceiling:`clear`};if(r!==`set`)return Q(e,`${t}.ceiling`,`ceiling must be "set" or "clear", got ${K(r)}`),null;let a=n.to;return typeof a!=`string`||a.trim()===``?(Q(e,`${t}.to`,`ceiling set needs \`to\`: a memento ceiling value such as "+100_000", "400000" or "off", got ${K(a)}`),null):{ceiling:`set`,to:a}}function Bw(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=sS(n.slash);return r.kind===`refused`?(Q(e,`${t}.slash`,r.reason),null):{slash:r.line}}function Vw(e,t,n){for(let r of Object.keys(n))r!==`do`&&Q(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===``)?(Q(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 ${K(r)}`),null):{do:r}}function Hw(e,t,n,r,i,a){let o=$s(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Q(e,s,i),null):o.includes(`/`)?(Q(e,s,a(o)),null):o}const Uw={set:`the SessionState key to write`,persist:`the config globals field to write`};function Ww(e,t,n,r){let i=Uw[r],a=Hw(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 Gw(e){return e===`set`?`set-state`:`set-config`}const Kw={to:dT(`set`)},qw={to:dT(`persist`)},Jw={from:fT(`set`)},Yw={from:fT(`persist`)},Xw={min:_T(),max:_T(),by:_T()},Zw={int:mT()},Qw={cycle:pT(`set`)},$w={cycle:pT(`persist`)},eT={removeSegment:hT(`removeSegment`)},tT={insertSegment:hT(`insertSegment`),anchor:hT(`anchor`),relation:gT()},nT={insertSegmentFrom:fT(`persist`),anchor:hT(`anchor`),relation:gT()},rT={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},iT={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function aT(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>cc(e,t,n,r),c=Ec(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?gc(s,...n):s}}const oT=[aT(`set`,Kw),aT(`set`,Jw),aT(`set`,Xw,[rT,iT]),aT(`set`,Zw),aT(`set`,Qw)],sT=[aT(`persist`,qw),aT(`persist`,Yw),aT(`persist`,Xw,[rT,iT]),aT(`persist`,$w),aT(`persist`,eT),aT(`persist`,tT,[],[`insertSegment`]),aT(`persist`,nT,[],[`insertSegmentFrom`])];function cT(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 lT(e){let t=cT(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 uT(e,t,n,r,i){let a=Ww(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Q(e,t,`${lT(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)||Q(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 dT(e){let t=Gw(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>Hw(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 fT(e){let t=Gw(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===``){Q(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){Q(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===``)){Q(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){Q(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){Q(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Q(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${K(o)}`)}}}function pT(e){let t=Gw(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`)){Q(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${ac(o)}`);return}let c=o;if(c.length<2){Q(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){Q(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Q(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){Q(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function mT(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Q(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${K(r[n])}`);return}return!0}}}function hT(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=$s(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Q(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Q(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 gT(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Q(e,`${t}.${n}`,`relation must be "before" or "after", got ${K(i)}`);return}return i}}}function _T(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Q(e,`${t}.${n}`,`${n} must be an integer, got ${K(i)}`);return}return i}}}function vT(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const yT={noun:`style key`,fields:{hueShift:bc(),chromaScale:bc({min:0}),lightnessScale:bc(),lightnessShift:bc()}};function bT(e,t){if(!ic(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${ac(t)}`,line:G(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:G(e.source,[`styles`,r])});continue}if(mo(r)){e.issues.push({path:`styles.${r}`,message:vT(`styles.${r}`,r,`globals.endcaps`),line:G(e.source,[`styles`,r])});continue}let t=oc(e,yT,`styles.${r}`,i);t!==null&&(n[r]={...Bn,...t})}return n}const xT={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:gd(e,`${t}.${n}`,r[n])},globals:{required:!1,json:kl(),parse:(e,t,n,r)=>r[n]===void 0?void 0:Ol(e,`${t}.${n}`,r[n])}}};function ST(e,t){if(!ic(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${ac(t)}`,line:G(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:G(e.source,[`presets`,r])});continue}let t=oc(e,xT,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function CT(e,t){if(t===void 0)return{};if(!ic(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${ac(t)}`,line:G(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 ${K(i)}`,line:G(e.source,[`helpers`,r])});continue}n[r]=i}return n}const wT=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 TT(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 ET(e){let t=wT.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${TT(t)}`}function DT(e){let t=wT.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${TT(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}function OT(e,t){let n=new Map;for(let e of Object.keys(t)){let t=Su(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:G(e.source,[`presets`])})}function kT(e,t,n){let r=[[[`globals`],t.globals.style],[[`editGlobals`],t.editGlobals.style],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style])];for(let[n,i]of r){if(i===void 0||ao(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:mo(i)?vT(r,i,`${n.join(`.`)}.endcaps`):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:G(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:G(e.source,[`globals`,`preset`])}),OT(e,t.presets);let i=lx(t),a=ux(i);for(let[n,r]of Object.entries(t.actions)){if(!(`set`in r))continue;if(Hb.has(r.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${r.set}", which has no session pick — globals.${r.set} is set in the config file only, so a click would change nothing; write it with { persist: "${r.set}", … } instead`,line:G(e.source,[`actions`,n,`set`])}),`from`in r&&typeof r.from==`string`&&!a.includes(r.from)){e.issues.push({path:`actions.${n}.from`,message:`actions.${n} from: references unknown option domain "${r.from}" (have: ${a.join(`, `)})`,line:G(e.source,[`actions`,n,`from`])});continue}let t=Kb.get(r.set);t!==void 0&&KT(e,n,r,t,i)}for(let[n,r]of Object.entries(t.actions))`do`in r&&r.do.forEach((i,a)=>{let o=Object.prototype.hasOwnProperty.call(t.actions,i)?t.actions[i]:void 0,s=o===void 0?`references unknown action "${i}"`:`do`in o?`"${i}" is itself a do action — list its members here instead`:r.do.indexOf(i)===a?a>0&&kw(o)?`"${i}" 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:`"${i}" 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:G(e.source,[`actions`,n,`do`])})});for(let[n,r]of Object.entries(t.actions)){let i=`persist`in r?r.persist:`reset`in r?r.reset:null;if(i===null)continue;let a=`persist`in r?`persist`:`reset`,o=Cx(i);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a config globals field (have: ${Nl().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, or a "presets.<name>.root" target`,line:G(e.source,[`actions`,n,a])});continue}let s=AT.filter(e=>e in r);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){jT(e,t,n,a,i,o.preset,r);continue}if(o.scope===`preset-globals`&&!j_(t.presets).includes(o.preset)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" names preset "${o.preset}" which is not declared (have: ${j_(t.presets).join(`, `)})`,line:G(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}: "${i}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${Mu(o.segment)}`,line:G(e.source,[`actions`,n,a])});continue}`min`in r&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:G(e.source,[`actions`,n,a])})}}let o=Ov(t);for(let t of o.names)t!==`settings`&&!t.startsWith(MT)||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:G(e.source,[`variables`,t])});let s=(t,n,r)=>{PC(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${ES}" ${PC(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:r}),FC(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${ES}" 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:r}),c(t)&&e.issues.push({path:n,message:`${n} sets "distribution" on a container inside a bar cell — everything inside a cell wears that cell's hue and tone, so it would place nothing. Set it on the row whose children are the cells (the horizontal container) or on the root, which places the rows.`,line:r});let i=new Map;for(let e of Ps(t)){if(e.kind!==`segment`)continue;let t=As(e);i.set(t,[...i.get(t)??[],e])}for(let[t,a]of i){if(a.length<2)continue;let o=a[1].name,s=Ms(o,new Set(i.keys()));e.issues.push({path:n,message:`${n} has ${a.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: "${o}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:r})}};function c(e,t=!1){return e.kind===`segment`?!1:t&&e.distribution!==void 0||e.children.some(n=>c(n,t||ks[e.direction]===`cell`))}let l=(n,r)=>{for(let[i,a]of zc(n,r)){let n=G(e.source,a.split(`.`));if(i.when!==void 0&&(WT(e,`${a}.when`,i.when,o,{line:n}),UT(e,`${a}.when`,i.when,n)),i.kind===`segment`){if(jC(i.name)){(i.id!==void 0||i.settings!==void 0)&&e.issues.push({path:a,message:`${r} gives the global settings menu anchor "${ES}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${ES}"`,line:n});continue}Object.prototype.hasOwnProperty.call(t.segments,i.name)||e.issues.push({path:a,message:`${r} entry "${i.name}" does not match any declared segment${Mu(i.name)}`,line:n}),BT(e,t,i,a,n)}}};n.root!==void 0&&l(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&l(t.root,`presets.${e}.root`);let u=new Map([[`root`,Lc(t.root)]]);for(let e of j_(t.presets)){let{node:n,path:r}=P_(t,e);u.set(r,n)}for(let[t,n]of u)s(n,t,G(e.source,t.split(`.`)));for(let[n,r]of Object.entries(t.variables)){VT(e,`variables.${n}`,r,o);let t=ET(n);t!==void 0&&e.issues.push({path:`variables.${n}`,message:t,line:G(e.source,[`variables`,n])})}for(let[n,r]of Object.entries(t.segments)){if(r.vars)for(let[t,i]of Object.entries(r.vars))VT(e,`segments.${n}.vars.${t}`,i,o,n);let i=Ws(r);PT(e,n,i);let a=NT(o,i);for(let o of[`template`,`bg`,`fg`,`when`]){let s=r[o];if(typeof s==`string`){WT(e,`segments.${n}.${o}`,s,a,{segCtx:n,settings:i});for(let{name:r,site:i,via:a}of Tv(s,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,r))continue;let s=i===`options`?` (in a picker, menu or carousel)`:``;if(a!==null){GT(e,a,`Template references unknown action "${r}"${s}`);continue}e.issues.push({path:`segments.${n}.${o}`,message:`${o} references unknown action "${r}"${s}`,line:G(e.source,[`segments`,n,o])})}}}}for(let[n,r]of Object.entries(t.variables))HT(e,`variables.${n}`,r,o);for(let[n,r]of Object.entries(t.segments))if(r.vars)for(let[t,i]of Object.entries(r.vars))HT(e,`segments.${n}.vars.${t}`,i,o,n)}const AT=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function jT(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=G(e.source,[`actions`,n,r]);if(!j_(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${j_(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(`, `)})${Mu(i)}`,line:c})},p=new Set(js(P_(t,a).node)),m=(r,i)=>{!ju.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${Mu(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 MT=`settings.`;function NT(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>MT+e)])}}function PT(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:G(e.source,[`segments`,t,`settings`,n])})},a=LT(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of Ks(n,IT(n)))i(e,`the defaults do not stand together: ${t}`)}function FT(e){return LT(e).length>0||Ks(e,IT(e)).length>0}function IT(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function LT(e){let t=t=>Gs(RT(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||Gs(RT(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${zT(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 RT(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function zT(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&Gs(n)!==void 0).map(([e])=>e)}function BT(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=Ws(a),s=`${r}: placement "${As(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(`, `)})`:qs(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Xa(a):``}, but it must be ${Xs(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])=>qs(o[e],t))||FT(o)))for(let{message:t}of Ks(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function VT(e,t,n,r,i){n.kind===`template`&&WT(e,`${t}.template`,n.template,r,{segCtx:i}),Vs(n)&&n.cache&&`key`in n.cache&&WT(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function HT(e,t,n,r,i){if(Vs(n)&&n.cache&&`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:G(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function UT(e,t,n,r){try{J_.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function WT(e,t,n,r,i){for(let[a,o]of xv(n,r.helpers)){if(Dv(a,r))continue;if(a.startsWith(MT)){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??G(e.source,t.split(`.`))});continue}if(o!==null){GT(e,o,`Template references unknown variable ".${a}"${DT(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&Dv(n,r)?` (segment-local vars are namespaced — write ".${n}")`:DT(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??G(e.source,t.split(`.`))})}}function GT(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:G(e.source,[`helpers`,t])})}function KT(e,t,n,r,i){let a=n.set,o=gl(zb[r].configKey),s=`${a} takes ${px(o,i)}`;if(`min`in n&&(o===`bool`||`from`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:G(e.source,[`actions`,t,`min`])});return}let c=YT(n,i);if(c===JT){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:G(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!fx(o,e.value,i));if(l.length!==0){if(a===zb.style.sessionKey&&c.every(e=>mo(e.value))){let r=zb.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:vT(`actions.${t}.to`,n.to,`set: "${r}", to`),line:G(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:G(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<=qT?r.join(`, `):`${r.slice(0,qT).join(`, `)} and ${r.length-qT} 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:G(e.source,[`actions`,t,n])})}}}const qT=3,JT=Symbol(`any integer`);function YT(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?dx(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)}]:JT}function XT(e,t){let{graph:n,nodeInfo:r}=ZT(t),i=new Map,a=[];for(let e of n.keys())i.set(e,0);for(let e of n.keys())if(i.get(e)===0&&o(e))return;function o(t){i.set(t,1),a.push(t);for(let s of n.get(t)??[]){let t=i.get(s);if(t===1){let t=a.indexOf(s),n=[...a.slice(t),s],i=n[0],o=r.get(i);return e.issues.push({path:o?.declarationPath??`variables.${i}`,message:`Dependency cycle: ${n.join(` → `)}`,line:G(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function ZT(e){let t=new Set(Object.keys(e.variables)),n=new Map;for(let t of Object.keys(e.variables))n.set(t,{declarationPath:`variables.${t}`,linePathParts:[`variables`,t]});for(let[r,i]of Object.entries(e.segments))if(i.vars)for(let e of Object.keys(i.vars)){let i=`${r}.${e}`;t.add(i),n.set(i,{declarationPath:`segments.${r}.vars.${e}`,linePathParts:[`segments`,r,`vars`,e]})}let r=new Map;for(let e of t)r.set(e,new Set);let i=(n,i)=>{for(let a of xv(i,e.helpers).keys()){if(t.has(a)){r.get(n).add(a);continue}let e=a.split(`.`)[0];e!==a&&t.has(e)&&r.get(n).add(e)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),Vs(n)&&(n.cache&&`key`in n.cache&&i(e,n.cache.key),n.cache&&`depends_on`in n.cache))for(let i of n.cache.depends_on)t.has(i)&&r.get(e).add(i)};for(let[t,n]of Object.entries(e.variables))a(t,n);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))a(`${t}.${e}`,r);return{graph:r,nodeInfo:n}}const QT=[`json5`,`json`];function $T(e){try{return r.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function eE(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?m.homedir()+e.slice(1):e}function tE(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?QT.map(t=>c.join(e,`.cc-candybar.${t}`)):[],...QT.map(e=>c.join(r,`.cc-candybar.${e}`)),...QT.map(e=>`${nE()}.${e}`)])]}function nE(){let e=process.env.XDG_CONFIG_HOME??c.join(m.homedir(),`.config`);return c.join(e,`cc-candybar`,`config`)}function rE(e,t,n){let r=[];for(let i of tE(e,t,n)){let e=$T(i);if(e===`present`)return{kind:`file`,path:i,unchecked:r};e!==`absent`&&r.push(e)}if(n===void 0)return{kind:`default`,unchecked:r};let[i]=r;return i===void 0?{kind:`missing`,path:n}:{kind:`unreadable`,...i}}function iE(e,t,n){let r=rE(e,t,n);return r.kind===`default`?`${nE()}.${QT[0]}`:r.path}function aE(e){return oE(e).join(`
163
- `)||null}function oE(e){switch(e.kind){case`file`:case`default`: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 sE(e,t,n){let i=new Map;for(let a of tE(e,t,n)){if($T(a)!==`present`)continue;let e=r.realpathSync(c.dirname(a));i.has(e)||i.set(e,a)}return[...i.values()].slice(1)}function cE(e,t){let n=tE(e,t).filter(e=>$T(e)===`present`),r=new Map;for(let e of n){let t=c.dirname(e),n=c.basename(e).replace(/\.(json5|json)$/,``),i=c.join(t,n);r.has(i)||r.set(i,[]),r.get(i).push(e)}let i=[...r.values()].filter(e=>e.length>1);return i.length===0?null:`config-extension collision: ${i.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function lE(e,t,n){return e===null?{...dE,config:Hc(dE.raw,t)}:uE(e,r.readFileSync(e,`utf-8`),t,n)}function uE(e,t,n,r){let i={source:t,...mE(e,t,r,Ku(n))};return{...i,config:Hc(i.raw,n)}}const dE={raw:{},source:``,warnings:[]};function fE({config:e,raw:t,source:n},r=`<config>`,i=new Set($a())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(kT(o,e,t),XT(o,e),a.length>0)throw new Cs(r,a);let s=q_(e,a);if(a.length>0)throw new Cs(r,a);return Ew(qC(s))}function pE(e,t,n=new Set($a()),r=hE){return mE(e,t,n,r).raw}function mE(e,t,n,r){let i=gE(e,t),a=Es(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set($a()),groups:[]};if(!ic(i))throw new Cs(e,[{path:``,message:`Config root must be an object, got ${ac(i)}`}],o);let l=_E(c,i,r);if(s.length>0)throw new Cs(e,s,o);return{raw:l,warnings:o}}const hE=new Set;function gE(e,t){try{return rt.default.parse(t)}catch(t){let n=t;throw new Cs(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function _E(e,t,n){for(let n of Object.keys(t))vE.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...vE].join(`, `)}`,line:G(e.source,[n])});let r={};return t.globals!==void 0&&(r.globals=Dl(e,`globals`,t.globals)),t.variables!==void 0&&(r.variables=ql(e,`variables`,t.variables)),t.segments!==void 0&&(r.segments=qu(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.
161
+ `,Rx=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`,zx={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function Bx(e){let t=e[zx.socket]??``,n=e[zx.pane]??``;if(t===``||n===``)return null;let r=e[zx.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}function Vx(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const Hx=zx.truecolor,Ux={name:`tmuxTruecolor`,label:`tmux truecolor`,probe:({tmux:e,claudeSettings: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`:{if(e.termfeatures.kind===`failed`)return{ok:!1,reason:`tmux could not be asked: ${e.termfeatures.reason}`};if(!e.termfeatures.value.includes(`RGB`)||e.hint.truecolor!==null)return{ok:!0};let n=t.env[Hx];return typeof n==`string`&&n!==``?{ok:!1,reason:`${Hx} is set in ${t.path} — restart Claude Code to apply`}:{ok:!1,reason:`Claude Code renders the bar in 256 colours inside tmux`,fix:{kind:`claude-settings-env`,name:Hx,value:`1`}}}}}},Wx={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},Gx={name:`config`,label:`config`,probe:({config:e})=>{switch(e.kind){case`failed`:{let[t=`the config failed to load`,...n]=[...e.error.split(`
162
+ `).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return Vx([...e.warnings,...e.shadowed.map(t=>`${t} is never read — ${e.path??`another config`} is found first`),...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${Wx[e]}`)])}}},Kx="re-run `cc-candybar install`";function qx(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:// — ${Kx}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${Kx}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${Kx}`)}const Jx=[Gx,{name:`urlHandler`,label:`URL handler`,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${Kx}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${Kx}`};case`lost`:return Vx([...qx(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}`])}}},Ux];function Yx(e){return Jx.map(t=>({check:t,verdict:t.probe(e)}))}function Xx(e){return Jx.find(t=>t.name===e)}const Zx=`${Eu}doctor.`;function Qx(e){let t=`${Zx}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`}}function $x(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function eS(e){return e.flatMap(({check:e,verdict:t})=>{let n=Qx(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:``},{key:n.fixable,value:wo}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:$x(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?wo:Co}]})}const tS={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function nS(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries(tS).map(([t,n])=>[`${e}${t}`,n]))}}const rS=`armed`,iS=`disarmed`,aS=`.armed`,oS=e=>e.endsWith(aS);function sS(e,t,n){let r=`${e}${aS}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${rS}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:rS},[a]:{set:r,to:iS},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:iS}},disarm:a}}const cS=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function lS(e){return typeof e==`string`&&cS.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 uS(e){let t=lS(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const dS=[`/compact`,`/model`],fS=`/clear`;function pS(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=sS(`${e}clear`,{arm:fS,confirm:`${fS} ✓ confirm`},[n]);return{template:dS.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${Rb} }}`,actions:{...Object.fromEntries(dS.map(e=>[t(e),{slash:uS(e)}])),...r.actions,[n]:{slash:uS(fS)}},variables:r.variables,disarm:r.disarm}}function mS(e,t){let n=(e.CLAUDE_CONFIG_DIR??``).split(`,`)[0].trim();return n===``?void 0:c.resolve(t,n)}function hS(e){return e??c.join(m.homedir(),`.claude`)}function gS(e){return c.join(e,`settings.json`)}function _S(e){return c.join(e,`plugins`,`installed_plugins.json`)}function vS(e){return r.existsSync(e)?r.readFileSync(e,`utf8`):``}function yS(e){let t;try{let n=vS(e);if(/^\s*$/.test(n))return{};t=Jo.parse(n)}catch(t){throw Error(`cannot read ${e}: ${bS(t)}`,{cause:t})}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`cannot read ${e}: not a JSON object`);return t}const bS=e=>e instanceof Error?e.message:String(e),xS=Array.from({length:10},(e,t)=>(t+1)*1e5),SS=xS[0],CS=xS[xS.length-1];function wS(e){let t;try{t=yS(e)}catch(e){return X(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?J(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=SS&&n<=CS?J(n):X(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${SS}–${CS} tokens)`)}function TS(e,t){let n=Math.min(t??CS,CS),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:xS.filter(e=>e<r).at(-1)??0,higher:xS.find(e=>e>r&&e<=n)??0}}function ES(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${Rb} }}{{ 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:uS(`/autocompact auto`)},...Object.fromEntries(xS.map(t=>[`${e}${t}`,{slash:uS(`/autocompact ${t}`)}]))}}}const DS=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 }}`,OS=`${Eu}menu`,kS=`open`,AS=`${Eu}edit`,jS=`${Eu}toolbar`,MS=nS(Eu),NS=`${Eu}commands`,PS=pS(`${NS}.`),FS=`${Eu}autocompact`,IS=ES(`${FS}.`,DS),LS=e=>({kind:`segment`,name:e}),RS=`${Eu}tab`,zS=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],BS=e=>`${RS}.${e}`,VS=e=>`${BS(e)}.toggle`,HS=e=>({variable:RS,key:RS,member:e}),US=`${Eu}save`,WS=`${Eu}preset.save`,GS=`${Eu}preset.delete`,KS=`${Eu}resetAll`,qS=`${OS}.toggle`,JS={variable:OS,key:OS,member:kS},YS=`${Eu}undo`,XS=`${Eu}back`,ZS=`${XS}.step`,QS=`${Eu}navigation.back`,$S=XS,eC={template:`{{ if gt .${QS} 0 }}{{ action "${XS}" "◁" }}{{ else }}{{ fg (${Rx}) "◁" }}{{ end }}`},tC=`${Eu}redo`,nC=`${Eu}doctor`,rC=`${nC}.run`,iC=e=>`${nC}.fix.${e}`,aC=e=>`${nC}.${e}`,oC=S_(`${Eu}pickers`),sC=[{template:`{{ themePreview }}`}],cC={template:`{{ layoutPreview }}`},lC={preset:[cC,{when:`{{ not .preset.bundled }}`,template:`{{ action "${GS}" (printf "🗑 delete %s" .${zb.preset.effectiveVar}) }}`}],theme:sC,style:sC,variation:[cC]},uC=e=>`${Eu}${e}`,dC=e=>`${Eu}apply.${e}`,fC=e=>`${Eu}reset.${e}`,pC=e=>`${Eu}list.${e}`,mC=(e,t)=>`${pC(e)}.${t}`,hC=e=>`${Eu}resettable.${e}`,gC=e=>e.length===0?`false`:`(or ${e.map(e=>`.${hC(e)}`).join(` `)})`,_C=Object.keys(zb).map(e=>{let t=zb[e],n=gl(t.configKey),r=vx({label:t.label,domain:n},t.sessionKey,t.effectiveVar,dC(e),oC);return{...t,name:e,control:r,beneath:lC[e]??[]}}),vC={preset:`door`,theme:`look`,style:`look`,variation:`look`,endcaps:`look`,autoWrap:`layout`,padding:`layout`,updateNotice:`config`},yC=e=>_C.filter(t=>vC[t.name]===e),bC=e=>yC(e).map(MC);new Set(_C.flatMap(e=>[e.sessionKey,e.configKey]));const xC=sS(KS,{arm:`⟲`,confirm:`⟲ reset all?`},_C.map(e=>fC(e.name))),SC=[`unsaved`,`history.undo`,`history.redo`],CC=e=>`${Eu}${e}`,wC=CC(`unsaved`),TC=(e,t)=>({body:t,shown:`(gt .${CC(e)} 0)`}),EC=[TC(`unsaved`,`{{ action "${US}" (printf "💾 save %d" .${wC}) }}`),TC(`history.undo`,`{{ action "${YS}" "↶" }}`),TC(`history.redo`,`{{ action "${tC}" "↷" }}`),{body:xC.template,shown:`(or ${gC(_C.map(e=>e.name))} ${xC.armed})`}],DC={when:`{{ or ${EC.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+EC.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},OC=[{step:xC,place:`door`},{step:PS,place:`session`}],kC=e=>e.map(e=>e.step.disarm),AC=kC(OC),jC=kC(OC.filter(e=>e.place!==`door`));function MC(e){let t=uC(e.name);return e.control.kind===`inline`?LS(t):Zc(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[LS(pC(e.name)),...e.beneath.map((t,n)=>LS(mC(e.name,n)))]},`drop`)}function NC(e){return e===OS}function PC(e){let t=LS(OS);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[PC(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}return e.kind===`container`&&e.when===void 0?{...e,children:[t,...e.children]}:{kind:`container`,direction:`horizontal`,children:[t,e]}}function FC(e){return IC(e)>0?e:PC(e)}function IC(e){let t=0;for(let n of Ps(e))n.kind===`segment`&&NC(n.name)&&(t+=1);return t}function LC(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&NC(e.name)||e.opens!==void 0&&LC(e.opens.body,!0):e.children.some(e=>LC(e,n))}const RC={session:{direction:`vertical`,content:[LS(jS),{kind:`container`,direction:`horizontal`,children:[LS(NS),LS(FS)]}]},look:{direction:`horizontal`,content:[]},layout:{direction:`horizontal`,content:[LS(WS),LS(AS)]},config:{direction:`horizontal`,content:[]},tools:{direction:`vertical`,content:[LS(nC),...Jx.map(e=>LS(aC(e.name)))]}},zC=e=>({kind:`container`,direction:RC[e].direction,children:[...RC[e].content,...bC(e)]});function BC(e){return e.kind===`segment`?NC(e.name)?Zc(e.name,JS,HC,`above`):e:WC(e)}function VC(){return{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[LS($S),...bC(`door`),LS(US)]},{kind:`container`,direction:`horizontal`,children:zS.map(({member:e})=>Zc(BS(e),HS(e),zC(e),`drop`))}]}}const HC=VC();function UC(e){let t=new Map;for(let e of Ps(HC))e.kind===`segment`&&e.opens!==void 0&&t.set(e.opens.ref.key,e.opens.ref.variable);return[...t].map(([t,n])=>{let r=e.variables[n];if(r?.kind!==`state`||r.default===void 0)throw Error(`settings menu: the door folds "${t}", but "${n}" is not a state variable the menu declares with a default`);let i=`${OS}.fold.${Su(t)}`;return e.actions[i]={set:t,to:r.default},i})}function WC(e){return{...e,children:e.children.map(e=>BC(e))}}function GC(e){let t={variables:{[OS]:rl(OS,Kc)},actions:{[qS]:il(OS,kS),[rC]:{doctor:`run`},[AS]:{do:[...$_]},...MS.actions,...PS.actions,...IS.actions,[US]:{save:!0},[YS]:{undo:!0},[ZS]:{back:!0},[XS]:{do:[ZS,...AC]},[tC]:{redo:!0},[WS]:{preset:`save`},[GS]:{preset:`delete`,name:`{{ .${zb.preset.effectiveVar} }}`}},segments:{[OS]:{template:`{{ $door := ${tl(OS,nl(e),nl(`✖`))} }}{{ if ${$c(JS)} }}{{ fg (color "error") $door }}{{ else }}{{ $door }}{{ end }}`},[jS]:{template:MS.template},[NS]:{template:PS.template,when:PS.when},[FS]:{template:IS.template,bg:IS.bg,when:IS.when},[$S]:eC,[US]:DC,[WS]:{template:`{{ action "${WS}" "+ preset" }}`},[nC]:{template:`{{ action "${rC}" "🩺 doctor" }}`},[AS]:{template:`{{ action "${AS}" "✎ arrange" "✎ done" }}`}}};t.variables[QS]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of SC)t.variables[CC(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[RS]=rl(RS,`session`);for(let{member:e,label:n}of zS){t.actions[VS(e)]=il(RS,e),t.actions[BS(e)]={do:[VS(e),...jC]};let r=gC(yC(e).map(e=>e.name)),i=`(ternary ${nl(` •`)} "" ${r})`,a=e=>`(print ${nl(e)} ${i})`;t.segments[BS(e)]={template:`{{ ${tl(BS(e),a(n),a(`▾ ${n}`))} }}`}}return Object.assign(t.variables,PS.variables,xC.variables),qC(t),KC(t),t.actions[OS]={do:[qS,...AC,...UC(t)]},t}function KC(e){for(let t of Jx){let n=Qx(t.name),r=iC(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},e.segments[aC(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${Co}" }} {{ action "${r}" "[fix]" }}{{ end }}{{ end }}`}}}function qC(e){for(let t of _C){Object.assign(e.actions,t.control.actions);let n=fC(t.name);e.actions[n]={reset:t.configKey},e.variables[hC(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${hC(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[uC(t.name)]={template:`${t.control.template}${r}`},t.control.kind===`picker`&&(e.segments[pC(t.name)]={template:t.control.list.template}),t.beneath.forEach((n,r)=>{e.segments[mC(t.name,r)]=n})}Object.assign(e.actions,xC.actions)}function JC(e){let{variables:t,actions:n}=cv();Object.assign(e.variables,t),Object.assign(e.actions,n)}function YC(e){let t=GC(e.globals.menuGlyph??`🍫`);JC(t);let n={...e.presets},r=[];for(let t of j_(e.presets)){let{node:i}=P_(e,t),a=BC(FC(i));r.push(a),n[t]={...N_(e.presets,t),root:a}}let i=Jb(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const XC=`${Tu}live`,ZC=[`☐ live`,`☑ live`],QC=`${Tu}done`,$C=`${Tu}cancel`,ew=`${Tu}rewind`,tw=`${Tu}changes`,nw=`(gt .${tw} 0)`,rw=`(or ${nw} (gt .${wC} 0))`,iw={variable:XC,key:XC,member:`open`};function aw(e){return`${Tu}configuring.p${e}`}function ow(e){return`and ${$c(rv)} (not ${$c(iw)}) (ne .${aw(e)} "true")`}function sw(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${X_} "${Xc(e)}")`).join(` `)} false }}`}}function cw(e,t,n){return`{{ if ${ow(e)} }}${t}{{ else }}${n}{{ end }}`}const lw=`{{ and ${$c(rv)} .preset.customized }}`,uw=Ou;function dw(e){return new Map([...lx(e),...pw(e)])}const fw=`${Tu}addable`;function pw(e){return new Map([[fw,{members:Object.keys(e.segments).filter(e=>!uw(e)),library:{groups:bu.map(e=>({id:e,label:xu[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function mw(e,t,n){return n.segments[e]={template:t,when:iv,bg:Ax},{kind:`segment`,name:e}}function hw(e,t,n){let r=`${Tu}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Aa}`}) (action "${r}" "✖") }}`}function gw(e){return`{{ if ${$c(rv)} }}${e}{{ end }}`}function _w(e,t){return e.reduce((e,t)=>`{{ if and ${$c(rv)} ${$c(t)} }}true{{ else }}${e}{{ end }}`,t)}function vw(e){return e.flatMap(e=>[...Ps(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function yw(e,t,n){return`${tv}${e}.${t}.${n}`}function bw(e,t,n,r){let i=As(n),a=`${Tu}${e.presetIdent}`,o=nv(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=S_(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:Kc},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:X_,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=yw(e.presetIdent,i,r),l=`${tv}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Js(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=vx(gx(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};let p=`${d}.list`;return e.artifacts.segments[d]={template:f.template},e.artifacts.segments[p]={template:f.list.template},Zc(d,f.list.ref,{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:p}]},`drop`)});return{term:`{{ action "${s}" "⚙️" }}`,ref:{variable:X_,key:X_,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const xw=`${Tu}label:`;function Sw(e){if(e.startsWith(xw)){let t=e.slice(xw.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function Cw(e,t,n,r){let{artifacts:i}=n,a=As(e),o=`${xw}${a}:${e.name}`;i.segments[o]={template:`{{ "${Xc(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=e.settings?.[Us];return{...Zc(o,r.ref,r.body,`drop`,_w([r.ref],`{{ ${ow(n.presetIdent)} }}`)),...s!==void 0&&{settings:{theme:s}},drafts:{[Us]:r.drafts[Us]}}}function ww(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${Tu}${i}.insert.${t}`,s=`${Tu}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:fw,anchor:n,relation:r};let c=b_(o),l=x_(s,o,void 0),u=w_(l),d=C_(l,c);return a.variables[l]=rl(l,Kc),a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=il(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${$c({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Aa}`}) $m }}{{ end }}`}}function Tw(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!uw(e.name)),i=e=>Tw(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Ns(o,i);if(uw(o.name)){n.push(s);continue}let c=As(o),l=a===r?[ww(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=ww(t,u,c,`after`),f=hw(t,u,c),p=t.segments[o.name],m=bw(t,u,o,Ws(p)),h=gw(f),g=gw(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>mw(e.host,e.template,t.artifacts)),{...Cw(o,p,t,m),lead:h,trail:g},{...s,when:cw(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},mw(d.host,d.template,t.artifacts)]};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[_]}:_)}return{...e,children:n,...e.when!==void 0&&{when:_w(vw(n),cw(t.presetIdent,`true`,e.when))}}}function Ew(e,t,n,r,i,a,o){let s=`${Tu}${t}.resetLayout`,c=`${Tu}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:lw},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},Dw(e,o)]}}function Dw(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),Dw(n,t)]}:{...e,children:[...e.children,t]}}function Ow(e,t,n,r,i,a){let{node:o}=P_(e,t),s={presetIdent:Su(t),rootKey:Cx(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=Tw(o,s);return n.variables[aw(s.presetIdent)]=sw(s.configured),Ew(c,s.presetIdent,s.rootKey,n,r,i,a)}function kw(e){let t={variables:{},actions:{},segments:{}},n=Ox(`${Tu}help`,Ix,[rv],t);t.variables[XC]=rl(XC,Kc),t.actions[XC]=il(XC,iw.member),t.segments[XC]={template:el(XC,...ZC),when:iv};let r={kind:`segment`,name:XC},i=n;t.variables[tw]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[QC]={do:[US,...$_]},t.segments[QC]={template:`{{ if ${rw} }}{{ action "${QC}" "✓ save" }}{{ else }}{{ action "${QC}" "✓ done" }}{{ end }}`,when:iv},t.actions[ew]={rewind:!0},t.actions[$C]={do:[ew,...$_]},t.segments[$C]={template:`{{ action "${$C}" "↩ cancel" }}`,when:`{{ and ${$c(rv)} ${nw} }}`};let a=[{kind:`segment`,name:QC},{kind:`segment`,name:$C}],o={...e.presets},s=[];for(let n of j_(e.presets)){let c=Ow(e,n,t,a,r,i);s.push(c),o[n]={...N_(e.presets,n),root:c}}let c=Jb(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}const Aw=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`doctor`,`ceiling`,`slash`,`do`];function jw(e){return e.ceiling===`set`?[`set`,e.to]:[`clear`]}function Mw(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function Nw(e,t){if(t===void 0)return{};if(!ic(t))return Q(e,`actions`,`actions must be an object, got ${ac(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=Pw(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Q(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function Pw(e,t,n){if(!ic(n))return Q(e,t,`${t} must be an action object, got ${ac(n)}`),null;if(`persistWhen`in n)return Q(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 r=Aw.filter(e=>e in n);return r.length===1?Fw[r[0]](e,t,n):(Q(e,t,`action must declare exactly one of: ${Aw.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const Fw={set:(e,t,n)=>pT(e,t,n,`set`,lT),persist:(e,t,n)=>pT(e,t,n,`persist`,uT),copy:Iw(`copy`),open:Iw(`open`),reset:Lw,undo:zw(`undo`),redo:zw(`redo`),back:zw(`back`),rewind:zw(`rewind`),save:zw(`save`),preset:Bw,doctor:Vw,ceiling:Hw,slash:Uw,do:Ww};function Iw(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=$s(t,n,r,e);return i===null?null:{[e]:i}}}function Lw(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=Gw(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 Rw={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 zw(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Q(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${Rw[e]}), got ${K(r[e])}`),null)}}function Bw(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Q(e,`${t}.preset`,`preset must be "save" or "delete", got ${K(r)}`),null;if(r===`save`)return{preset:`save`};let a=$s(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function Vw(e,t,n){let r=n.doctor,i=r===`run`?[`doctor`]:[`doctor`,`check`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${i.join(`, `)}`);if(r!==`run`&&r!==`fix`)return Q(e,`${t}.doctor`,`doctor must be "run" or "fix", got ${K(r)}`),null;if(r===`run`)return{doctor:`run`};let a=n.check;return typeof a!=`string`||Xx(a)===void 0?(Q(e,`${t}.check`,`doctor fix must name a check (have: ${Jx.map(e=>e.name).join(`, `)}), got ${K(a)}`),null):{doctor:`fix`,check:a}}function Hw(e,t,n){let r=n.ceiling,i=r===`clear`?[`ceiling`]:[`ceiling`,`to`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a ceiling action. Expected only: ${i.join(`, `)}`);if(r===`clear`)return{ceiling:`clear`};if(r!==`set`)return Q(e,`${t}.ceiling`,`ceiling must be "set" or "clear", got ${K(r)}`),null;let a=n.to;return typeof a!=`string`||a.trim()===``?(Q(e,`${t}.to`,`ceiling set needs \`to\`: a memento ceiling value such as "+100_000", "400000" or "off", got ${K(a)}`),null):{ceiling:`set`,to:a}}function Uw(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=lS(n.slash);return r.kind===`refused`?(Q(e,`${t}.slash`,r.reason),null):{slash:r.line}}function Ww(e,t,n){for(let r of Object.keys(n))r!==`do`&&Q(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===``)?(Q(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 ${K(r)}`),null):{do:r}}function Gw(e,t,n,r,i,a){let o=$s(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Q(e,s,i),null):o.includes(`/`)?(Q(e,s,a(o)),null):o}const Kw={set:`the SessionState key to write`,persist:`the config globals field to write`};function qw(e,t,n,r){let i=Kw[r],a=Gw(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 Jw(e){return e===`set`?`set-state`:`set-config`}const Yw={to:mT(`set`)},Xw={to:mT(`persist`)},Zw={from:hT(`set`)},Qw={from:hT(`persist`)},$w={min:bT(),max:bT(),by:bT()},eT={int:_T()},tT={cycle:gT(`set`)},nT={cycle:gT(`persist`)},rT={removeSegment:vT(`removeSegment`)},iT={insertSegment:vT(`insertSegment`),anchor:vT(`anchor`),relation:yT()},aT={insertSegmentFrom:hT(`persist`),anchor:vT(`anchor`),relation:yT()},oT={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},sT={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function cT(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>cc(e,t,n,r),c=Ec(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?gc(s,...n):s}}const lT=[cT(`set`,Yw),cT(`set`,Zw),cT(`set`,$w,[oT,sT]),cT(`set`,eT),cT(`set`,tT)],uT=[cT(`persist`,Xw),cT(`persist`,Qw),cT(`persist`,$w,[oT,sT]),cT(`persist`,nT),cT(`persist`,rT),cT(`persist`,iT,[],[`insertSegment`]),cT(`persist`,aT,[],[`insertSegmentFrom`])];function dT(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 fT(e){let t=dT(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 pT(e,t,n,r,i){let a=qw(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Q(e,t,`${fT(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)||Q(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 mT(e){let t=Jw(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>Gw(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 hT(e){let t=Jw(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===``){Q(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){Q(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===``)){Q(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){Q(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){Q(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Q(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${K(o)}`)}}}function gT(e){let t=Jw(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`)){Q(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${ac(o)}`);return}let c=o;if(c.length<2){Q(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){Q(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Q(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){Q(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function _T(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Q(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${K(r[n])}`);return}return!0}}}function vT(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=$s(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Q(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Q(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 yT(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Q(e,`${t}.${n}`,`relation must be "before" or "after", got ${K(i)}`);return}return i}}}function bT(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Q(e,`${t}.${n}`,`${n} must be an integer, got ${K(i)}`);return}return i}}}function xT(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const ST={noun:`style key`,fields:{hueShift:bc(),chromaScale:bc({min:0}),lightnessScale:bc(),lightnessShift:bc()}};function CT(e,t){if(!ic(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${ac(t)}`,line:G(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:G(e.source,[`styles`,r])});continue}if(mo(r)){e.issues.push({path:`styles.${r}`,message:xT(`styles.${r}`,r,`globals.endcaps`),line:G(e.source,[`styles`,r])});continue}let t=oc(e,ST,`styles.${r}`,i);t!==null&&(n[r]={...Bn,...t})}return n}const wT={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:gd(e,`${t}.${n}`,r[n])},globals:{required:!1,json:kl(),parse:(e,t,n,r)=>r[n]===void 0?void 0:Ol(e,`${t}.${n}`,r[n])}}};function TT(e,t){if(!ic(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${ac(t)}`,line:G(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:G(e.source,[`presets`,r])});continue}let t=oc(e,wT,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function ET(e,t){if(t===void 0)return{};if(!ic(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${ac(t)}`,line:G(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 ${K(i)}`,line:G(e.source,[`helpers`,r])});continue}n[r]=i}return n}const DT=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 OT(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 kT(e){let t=DT.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${OT(t)}`}function AT(e){let t=DT.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${OT(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}function jT(e,t){let n=new Map;for(let e of Object.keys(t)){let t=Su(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:G(e.source,[`presets`])})}function MT(e,t,n){let r=[[[`globals`],t.globals.style],[[`editGlobals`],t.editGlobals.style],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style])];for(let[n,i]of r){if(i===void 0||ao(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:mo(i)?xT(r,i,`${n.join(`.`)}.endcaps`):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:G(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:G(e.source,[`globals`,`preset`])}),jT(e,t.presets);let i=dw(t),a=ux(i);for(let[n,r]of Object.entries(t.actions)){let[t,o]=`from`in r?[`from`,r.from]:`insertSegmentFrom`in r?[`insertSegmentFrom`,r.insertSegmentFrom]:[null,null];if(t!==null&&typeof o==`string`&&!a.includes(o)){e.issues.push({path:`actions.${n}.${t}`,message:`actions.${n} ${t}: references ${px(o,i)}`,line:G(e.source,[`actions`,n,t])});continue}if(!(`set`in r))continue;Hb.has(r.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${r.set}", which has no session pick — globals.${r.set} is set in the config file only, so a click would change nothing; write it with { persist: "${r.set}", … } instead`,line:G(e.source,[`actions`,n,`set`])});let s=Kb.get(r.set);s!==void 0&&YT(e,n,r,s,i)}for(let[n,r]of Object.entries(t.actions))`do`in r&&r.do.forEach((i,a)=>{let o=Object.prototype.hasOwnProperty.call(t.actions,i)?t.actions[i]:void 0,s=o===void 0?`references unknown action "${i}"`:`do`in o?`"${i}" is itself a do action — list its members here instead`:r.do.indexOf(i)===a?a>0&&Mw(o)?`"${i}" 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:`"${i}" 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:G(e.source,[`actions`,n,`do`])})});for(let[n,r]of Object.entries(t.actions)){let i=`persist`in r?r.persist:`reset`in r?r.reset:null;if(i===null)continue;let a=`persist`in r?`persist`:`reset`,o=Tx(i);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a config globals field (have: ${Nl().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, or a "presets.<name>.root" target`,line:G(e.source,[`actions`,n,a])});continue}let s=NT.filter(e=>e in r);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){PT(e,t,n,a,i,o.preset,r);continue}if(o.scope===`preset-globals`&&!j_(t.presets).includes(o.preset)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" names preset "${o.preset}" which is not declared (have: ${j_(t.presets).join(`, `)})`,line:G(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}: "${i}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${Mu(o.segment)}`,line:G(e.source,[`actions`,n,a])});continue}`min`in r&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:G(e.source,[`actions`,n,a])})}}let o=Ov(t);for(let t of o.names)t!==`settings`&&!t.startsWith(FT)||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:G(e.source,[`variables`,t])});let s=(t,n,r)=>{IC(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${OS}" ${IC(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:r}),LC(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${OS}" under a \`when\` or inside a disclosure body — the menu is visible under every condition, so its placement may not be gated. Move it to an ungated position, or remove it to put the menu at its default position.`,line:r}),c(t)&&e.issues.push({path:n,message:`${n} sets "distribution" on a container inside a bar cell — everything inside a cell wears that cell's hue and tone, so it would place nothing. Set it on the row whose children are the cells (the horizontal container) or on the root, which places the rows.`,line:r});let i=new Map;for(let e of Ps(t)){if(e.kind!==`segment`)continue;let t=As(e);i.set(t,[...i.get(t)??[],e])}for(let[t,a]of i){if(a.length<2)continue;let o=a[1].name,s=Ms(o,new Set(i.keys()));e.issues.push({path:n,message:`${n} has ${a.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: "${o}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:r})}};function c(e,t=!1){return e.kind===`segment`?!1:t&&e.distribution!==void 0||e.children.some(n=>c(n,t||ks[e.direction]===`cell`))}let l=(n,r)=>{for(let[i,a]of zc(n,r)){let n=G(e.source,a.split(`.`));if(i.when!==void 0&&(qT(e,`${a}.when`,i.when,o,{line:n}),KT(e,`${a}.when`,i.when,n)),i.kind===`segment`){if(NC(i.name)){(i.id!==void 0||i.settings!==void 0)&&e.issues.push({path:a,message:`${r} gives the global settings menu anchor "${OS}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${OS}"`,line:n});continue}Object.prototype.hasOwnProperty.call(t.segments,i.name)||e.issues.push({path:a,message:`${r} entry "${i.name}" does not match any declared segment${Mu(i.name)}`,line:n}),UT(e,t,i,a,n)}}};n.root!==void 0&&l(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&l(t.root,`presets.${e}.root`);let u=new Map([[`root`,Lc(t.root)]]);for(let e of j_(t.presets)){let{node:n,path:r}=P_(t,e);u.set(r,n)}for(let[t,n]of u)s(n,t,G(e.source,t.split(`.`)));for(let[n,r]of Object.entries(t.variables)){WT(e,`variables.${n}`,r,o);let t=kT(n);t!==void 0&&e.issues.push({path:`variables.${n}`,message:t,line:G(e.source,[`variables`,n])})}for(let[n,r]of Object.entries(t.segments)){if(r.vars)for(let[t,i]of Object.entries(r.vars))WT(e,`segments.${n}.vars.${t}`,i,o,n);let i=Ws(r);LT(e,n,i);let a=IT(o,i);for(let o of[`template`,`bg`,`fg`,`when`]){let s=r[o];if(typeof s==`string`){qT(e,`segments.${n}.${o}`,s,a,{segCtx:n,settings:i});for(let{name:r,site:i,via:a}of Tv(s,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,r))continue;let s=i===`options`?` (in a picker, menu or carousel)`:``;if(a!==null){JT(e,a,`Template references unknown action "${r}"${s}`);continue}e.issues.push({path:`segments.${n}.${o}`,message:`${o} references unknown action "${r}"${s}`,line:G(e.source,[`segments`,n,o])})}}}}for(let[n,r]of Object.entries(t.variables))GT(e,`variables.${n}`,r,o);for(let[n,r]of Object.entries(t.segments))if(r.vars)for(let[t,i]of Object.entries(r.vars))GT(e,`segments.${n}.vars.${t}`,i,o,n)}const NT=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function PT(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=G(e.source,[`actions`,n,r]);if(!j_(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${j_(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(`, `)})${Mu(i)}`,line:c})},p=new Set(js(P_(t,a).node)),m=(r,i)=>{!ju.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${Mu(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 FT=`settings.`;function IT(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>FT+e)])}}function LT(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:G(e.source,[`segments`,t,`settings`,n])})},a=BT(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of Ks(n,zT(n)))i(e,`the defaults do not stand together: ${t}`)}function RT(e){return BT(e).length>0||Ks(e,zT(e)).length>0}function zT(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function BT(e){let t=t=>Gs(VT(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||Gs(VT(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${HT(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 VT(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function HT(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&Gs(n)!==void 0).map(([e])=>e)}function UT(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=Ws(a),s=`${r}: placement "${As(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(`, `)})`:qs(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Xa(a):``}, but it must be ${Xs(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])=>qs(o[e],t))||RT(o)))for(let{message:t}of Ks(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function WT(e,t,n,r,i){n.kind===`template`&&qT(e,`${t}.template`,n.template,r,{segCtx:i}),Vs(n)&&n.cache&&`key`in n.cache&&qT(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function GT(e,t,n,r,i){if(Vs(n)&&n.cache&&`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:G(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function KT(e,t,n,r){try{J_.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function qT(e,t,n,r,i){for(let[a,o]of xv(n,r.helpers)){if(Dv(a,r))continue;if(a.startsWith(FT)){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??G(e.source,t.split(`.`))});continue}if(o!==null){JT(e,o,`Template references unknown variable ".${a}"${AT(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&Dv(n,r)?` (segment-local vars are namespaced — write ".${n}")`:AT(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??G(e.source,t.split(`.`))})}}function JT(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:G(e.source,[`helpers`,t])})}function YT(e,t,n,r,i){let a=n.set,o=gl(zb[r].configKey),s=`${a} takes ${hx(o,i)}`;if(`min`in n&&(o===`bool`||`from`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:G(e.source,[`actions`,t,`min`])});return}let c=QT(n,i);if(c===ZT){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:G(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!mx(o,e.value,i));if(l.length!==0){if(a===zb.style.sessionKey&&c.every(e=>mo(e.value))){let r=zb.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:xT(`actions.${t}.to`,n.to,`set: "${r}", to`),line:G(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:G(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<=XT?r.join(`, `):`${r.slice(0,XT).join(`, `)} and ${r.length-XT} 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:G(e.source,[`actions`,t,n])})}}}const XT=3,ZT=Symbol(`any integer`);function QT(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?dx(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)}]:ZT}function $T(e,t){let{graph:n,nodeInfo:r}=eE(t),i=new Map,a=[];for(let e of n.keys())i.set(e,0);for(let e of n.keys())if(i.get(e)===0&&o(e))return;function o(t){i.set(t,1),a.push(t);for(let s of n.get(t)??[]){let t=i.get(s);if(t===1){let t=a.indexOf(s),n=[...a.slice(t),s],i=n[0],o=r.get(i);return e.issues.push({path:o?.declarationPath??`variables.${i}`,message:`Dependency cycle: ${n.join(` → `)}`,line:G(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function eE(e){let t=new Set(Object.keys(e.variables)),n=new Map;for(let t of Object.keys(e.variables))n.set(t,{declarationPath:`variables.${t}`,linePathParts:[`variables`,t]});for(let[r,i]of Object.entries(e.segments))if(i.vars)for(let e of Object.keys(i.vars)){let i=`${r}.${e}`;t.add(i),n.set(i,{declarationPath:`segments.${r}.vars.${e}`,linePathParts:[`segments`,r,`vars`,e]})}let r=new Map;for(let e of t)r.set(e,new Set);let i=(n,i)=>{for(let a of xv(i,e.helpers).keys()){if(t.has(a)){r.get(n).add(a);continue}let e=a.split(`.`)[0];e!==a&&t.has(e)&&r.get(n).add(e)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),Vs(n)&&(n.cache&&`key`in n.cache&&i(e,n.cache.key),n.cache&&`depends_on`in n.cache))for(let i of n.cache.depends_on)t.has(i)&&r.get(e).add(i)};for(let[t,n]of Object.entries(e.variables))a(t,n);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))a(`${t}.${e}`,r);return{graph:r,nodeInfo:n}}const tE=[`json5`,`json`];function nE(e){try{return r.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function rE(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?m.homedir()+e.slice(1):e}function iE(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?tE.map(t=>c.join(e,`.cc-candybar.${t}`)):[],...tE.map(e=>c.join(r,`.cc-candybar.${e}`)),...tE.map(e=>`${aE()}.${e}`)])]}function aE(){let e=process.env.XDG_CONFIG_HOME??c.join(m.homedir(),`.config`);return c.join(e,`cc-candybar`,`config`)}function oE(e,t,n){let r=[];for(let i of iE(e,t,n)){let e=nE(i);if(e===`present`)return{kind:`file`,path:i,unchecked:r};e!==`absent`&&r.push(e)}if(n===void 0)return{kind:`default`,unchecked:r};let[i]=r;return i===void 0?{kind:`missing`,path:n}:{kind:`unreadable`,...i}}function sE(e,t,n){let r=oE(e,t,n);return r.kind===`default`?`${aE()}.${tE[0]}`:r.path}function cE(e){return lE(e).join(`
163
+ `)||null}function lE(e){switch(e.kind){case`file`:case`default`: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 uE(e,t,n){let i=new Map;for(let a of iE(e,t,n)){if(nE(a)!==`present`)continue;let e=r.realpathSync(c.dirname(a));i.has(e)||i.set(e,a)}return[...i.values()].slice(1)}function dE(e,t){let n=iE(e,t).filter(e=>nE(e)===`present`),r=new Map;for(let e of n){let t=c.dirname(e),n=c.basename(e).replace(/\.(json5|json)$/,``),i=c.join(t,n);r.has(i)||r.set(i,[]),r.get(i).push(e)}let i=[...r.values()].filter(e=>e.length>1);return i.length===0?null:`config-extension collision: ${i.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function fE(e,t,n){return e===null?{...mE,config:Hc(mE.raw,t)}:pE(e,r.readFileSync(e,`utf-8`),t,n)}function pE(e,t,n,r){let i={source:t,..._E(e,t,r,Ku(n))};return{...i,config:Hc(i.raw,n)}}const mE={raw:{},source:``,warnings:[]};function hE({config:e,raw:t,source:n},r=`<config>`,i=new Set($a())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(MT(o,e,t),$T(o,e),a.length>0)throw new Cs(r,a);let s=q_(e,a);if(a.length>0)throw new Cs(r,a);return kw(YC(s))}function gE(e,t,n=new Set($a()),r=vE){return _E(e,t,n,r).raw}function _E(e,t,n,r){let i=yE(e,t),a=Es(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set($a()),groups:[]};if(!ic(i))throw new Cs(e,[{path:``,message:`Config root must be an object, got ${ac(i)}`}],o);let l=bE(c,i,r);if(s.length>0)throw new Cs(e,s,o);return{raw:l,warnings:o}}const vE=new Set;function yE(e,t){try{return rt.default.parse(t)}catch(t){let n=t;throw new Cs(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function bE(e,t,n){for(let n of Object.keys(t))xE.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...xE].join(`, `)}`,line:G(e.source,[n])});let r={};return t.globals!==void 0&&(r.globals=Dl(e,`globals`,t.globals)),t.variables!==void 0&&(r.variables=ql(e,`variables`,t.variables)),t.segments!==void 0&&(r.segments=qu(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.
164
164
  Replace: layout: [["seg1", "seg2"], ["seg3"]]
165
165
  With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
166
- Single-row example: root: { h: ["seg1", "seg2"] }`,line:G(e.source,[`layout`])}),t.root!==void 0&&(r.root=gd(e,`root`,t.root)),t.actions!==void 0&&(r.actions=Aw(e,t.actions)),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:G(e.source,[`looks`])}),t.styles!==void 0&&(r.styles=bT(e,t.styles)),t.presets!==void 0&&(r.presets=ST(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=Al(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=CT(e,t.helpers)),wd(e,r),G_(e,r),sv(e,r),Au(e,r,Eu,`the global settings menu`),r}const vE=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`presets`,`editGlobals`,`helpers`]);function yE(e){let t=TE(e.termCols),n=TE(e.termRows),r=EE(e.ssh),i=CE(e.tmux),a=SE(e.configEnv),o=xE(e.claudeConfigDir),s=bE(e.mementoEnv);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&&{mementoEnv:s}}}function bE(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Ze.filter(e=>t[e]!==void 0);return n.every(e=>xE(t[e])!==void 0)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function xE(e){return typeof e==`string`&&c.isAbsolute(e)?e:void 0}function SE(e){return typeof e==`string`&&e!==``?eE(e):void 0}function CE(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 wE=1e4;function TE(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>wE?wE:t}function EE(e){return typeof e==`boolean`?e:void 0}function DE(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var OE=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function kE(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function AE(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 OE(`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 OE(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function jE(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.removeAllListeners();try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n),c=AE(e=>o(()=>r(e)),e=>o(()=>i(e)));e.on(`data`,c),e.on(`error`,e=>o(()=>i(e))),e.on(`close`,()=>o(()=>i(Error(`socket closed before response`)))),e.write(kE(t))})}async function ME(e,t,n){let r=null;try{r=await LE(Le(),t.connectMs);let i=await jE(r,{v:3,...e},t.budgetMs);return FE(e.kind,i,n)}catch(e){return IE(e)}finally{r&&r.destroy()}}function NE(e,t){return typeof e==`string`?e:t}function PE(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function FE(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=NE(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:PE(r.daemonV)};case`TIMEOUT`:return{kind:`transient`,cause:`timeout`,message:i};case`BAD_REQUEST`:return{kind:`permanent`,cause:`bad_request`,message:i};case`RENDER_FAILED`:return{kind:`permanent`,cause:`render_failed`,message:i};default:return{kind:`permanent`,cause:`malformed_response`,message:`unknown error code: ${String(r.code)}`}}}function IE(e){if(e instanceof OE||e instanceof SyntaxError)return{kind:`permanent`,cause:`malformed_response`,message:e instanceof Error?e.message:String(e)};let t=e instanceof Error?e.message:String(e);return t===`CONNECT_TIMEOUT`||t===`TIMEOUT`?{kind:`transient`,cause:`timeout`,message:t}:t.includes(`ECONNREFUSED`)||t.includes(`ENOENT`)||t.includes(`ENOTSOCK`)?{kind:`transient`,cause:`unreachable`,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function LE(e,t){return new Promise((n,r)=>{let i=b.createConnection({path:e}),a=setTimeout(()=>{i.destroy(),r(Error(`CONNECT_TIMEOUT`))},t);i.once(`connect`,()=>{clearTimeout(a),n(i)}),i.once(`error`,e=>{clearTimeout(a),r(e)})})}function RE(e){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`malformed_response`:return`daemon error (${e.cause}): ${e.message}`}}const zE=`1.116.0`,BE={connectMs:50,budgetMs:150},VE={connectMs:50,budgetMs:200};function HE(e){let t=e.output;return typeof t==`string`?t:void 0}function UE(e,t,n,r){return ME({kind:`render`,hookData:e,args:t,cwd:n,...r},BE,HE)}function WE(e,t){return ME({kind:`click`,verb:e,value:t,clientVersion:zE},VE,HE)}function GE(e){let t=[];for(let n of e){let e=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(`
167
- `)}function KE(e,t){return e===`darwin`?[qE(`footprint`,[`-p`,String(t)]),qE(`vmmap`,[`--summary`,String(t)])]:e===`linux`?[JE(`/proc/self/smaps_rollup`),JE(`/proc/self/status`)]:[]}function qE(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=Ae({bin:e,args:[...t],timeoutMs:5e3,category:`limits.memory-report`});return n.ok?n.stdout.trim().length>0?{kind:`text`,text:n.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${n.reason}${n.error===void 0?``:`: ${n.error}`}${YE(n.stderr)}`}}}}function JE(e){return{name:e,read:()=>{try{let t=r.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}function YE(e){let t=e.split(`
168
- `).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const XE=`CC_CANDYBAR_RSS_LIMIT_MB`;function ZE(e){let t=e[XE];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${XE} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function QE(e){return ZE(e)*2}const $E=1024*1024;function eD(e){return ZE(e)*$E}const tD={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function nD(e,t,n){let{prefix:r,suffix:i}=tD[t];return c.join(e,`${r}${n}${i}`)}function rD(e){for(let t of Object.keys(tD)){let{prefix:n,suffix:r}=tD[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function iD(e){let t=e.rssLimitBytes??512*$E,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let{rss:i,heapTotal:a}=e.memoryBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t} (v8 heap ${a}); recording memory then shutting down`);let o=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return aD(e.log,`memory report`,()=>{let t=nD(e.snapshotDir,`memoryReport`,o);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),aD(e.log,`heap snapshot`,()=>{let t=nD(e.snapshotDir,`heapSnapshot`,o);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),aD(e.log,`artifact rotation`,()=>{sD(e.listArtifacts(),n,e.removeFile)}),e.shutdown(0),!0}function a(){let{rss:n,heapTotal:r}=e.memoryBytes();return n>t*.75?`rss ${n} approaching limit ${t} (v8 heap ${r})`:null}function o(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:o}}function aD(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function oD(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=rD(t);if(n===null)return t;let{prefix:r,suffix:i}=tD[n];return t.slice(r.length,t.length-i.length)}function sD(e,t,n){let r=new Map;for(let t of e){let e=oD(t),n=r.get(e);n===void 0?r.set(e,[t]):n.push(t)}let i=[...r.keys()].sort((e,t)=>t.localeCompare(e));for(let e of i.slice(t))for(let t of r.get(e)??[])try{n(t)}catch{}}function cD(e,t,n={}){let i=Ie();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:Z,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},captureMemoryReport:()=>GE(KE(process.platform,process.pid)),writeMemoryReport:(e,t)=>r.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>ne.writeHeapSnapshot(e),listArtifacts:()=>{try{return r.readdirSync(i).filter(e=>rD(e)!==null).map(e=>c.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function lD(e={}){if(TD()!==null)return;let n=e.spawn??ED,r=SD();if(r.kind===`contended`){let e=dD();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),uD(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),uD(n);return}try{uD(n)}finally{wD()}}function uD(e){vD()&&fD(e)}function dD(){try{let e=r.statSync(Ke());return Date.now()-e.mtimeMs}catch{return null}}function fD(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
169
- `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function pD(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function mD(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function hD(e){try{let t=r.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function gD(e,n){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function _D(){try{r.unlinkSync(Je())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function vD(){let e=qe(),n=Je(),r=hD(n),i=pD(yD(e),mD(r));return i.kind===`deny`?!1:(i.kind===`allow-future-garbage`&&t.stderr.write(`cc-candybar: spawn.cooldown mtime is ${i.futureMs}ms in the future — ignoring and spawning\n`),bD(e),gD(n,Math.min(r+1,5)),!0)}function yD(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function bD(e){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,`${t.pid} ${Date.now()}\n`,{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}let xD=null;function SD(){let e=Ke();for(let n=0;n<2;n++){try{let n=r.openSync(e,`wx`,384);try{r.writeSync(n,JSON.stringify({pid:t.pid,ts:Date.now()}))}catch{}return xD={fd:n,path:e},{kind:`held`}}catch(t){let n=t.code;if(n!==`EEXIST`)return{kind:`error`,reason:`openSync(${e}): ${n??t.message}`}}if(!CD(e))return{kind:`contended`};try{r.unlinkSync(e)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function CD(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function wD(){if(!xD)return;let{fd:e,path:t}=xD;xD=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function TD(){try{return r.mkdirSync(Ie(),{recursive:!0}),null}catch(e){return`mkdir ${Ie()}: ${e.message}`}}function ED(){let e=t.execPath,n=t.argv[1];return n?k({bin:e,args:[`--max-old-space-size=${QE(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const DD=`cc-candybar`,OD=`dispatch`,kD=`set-state`,AD=`step-state`,jD=`copy`,MD=`open-vscode`,ND=`toolbar-toggle`,PD=`show-config-error`,FD=`show-config-warning`,ID=`set-config`,LD=`step-config`,RD=`save`,zD=`save-preset`,BD=`delete-preset`,VD=`reset-config`,HD=`apply-layout-op`,UD=`undo`,WD=`redo`,GD=`back`,KD=`rewind`,qD=`apply-update`,JD=`doctor-run`,YD=`doctor-fix`,XD=`doctor-probe`,ZD=`ceiling`,QD=`slash`;function $D(e){return e.map(encodeURIComponent).join(`/`)}function eO(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function tO(e){return`${DD}://${OD}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${$D(e.args)}`)}`).join(`&`)}`}function nO(e){return new ie(e).getAll(`e`).map(oO)}const rO=new Set([kD,VD]);function iO(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&aO(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function aO(e,t){if(e.verb!==t.verb||!rO.has(e.verb))return;let[n,r]=[oO(e.value),oO(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function oO(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const sO=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function cO(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function lO(e){return sO.test(e)?e:cO(e)}const uO=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function dO(e){let t=uO.exec(e);return t?{kind:`ok`,value:[Number(t[1]),Number(t[2]),Number(t[3])]}:{kind:`failed`,reason:`"${e}" is not a release version (expected MAJOR.MINOR.PATCH)`}}function fO(e){return e.join(`.`)}function pO([e,t,n],[r,i,a]){return e-r||t-i||n-a}const mO=`@promptctl/cc-candybar`;async function hO(e,t,n){let r=`${n}/-/package/${encodeURIComponent(e)}/dist-tags`;try{let e=await t(r,{signal:AbortSignal.timeout(5e3)});if(!e.ok)return X(`registry responded ${e.status} for ${r}`);let n=await e.json();return typeof n.latest==`string`?dO(n.latest):Y}catch(e){return X(e instanceof Error?e.message:String(e))}}function gO(e,t){let n=dO(e);if(n.kind===`failed`)return{kind:`unchecked`,installed:e,reason:n.reason};switch(t.kind){case`failed`:return{kind:`unchecked`,installed:e,reason:t.reason};case`absent`:return{kind:`unchecked`,installed:e,reason:"the registry lists no `latest` dist-tag"};case`ok`:{let e=pO(n.value,t.value);return e<0?{kind:`stale`,installed:n.value,latest:t.value}:e>0?{kind:`ahead`,installed:n.value,latest:t.value}:{kind:`current`,installed:n.value}}}}function _O(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${fO(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${fO(t.installed)} is newer than the registry's latest release (${fO(t.latest)}): an unpublished build.\n`};case`stale`:{let n=fO(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${fO(t.installed)} was staged, but the latest release is ${n}.\n pnpm's release-age gate (minimumReleaseAge) and its dlx cache can both\n resolve \`@latest\` to an older release without saying so.\n To install ${n} now, name it explicitly:\n pnpm dlx ${e}@${n} install\n`}}case`unchecked`:return{stream:`stderr`,text:`⚠ Could not check for a cc-candybar release newer than ${t.installed} (${t.reason}); the registry check was skipped.\n`}}}const vO=`CCCandybarURLHandler`,yO=[],bO={"darwin-arm64":`@promptctl/cc-candybar-darwin-arm64`,"darwin-x64":`@promptctl/cc-candybar-darwin-x64`,"linux-x64":`@promptctl/cc-candybar-linux-x64`,"linux-arm64":`@promptctl/cc-candybar-linux-arm64`};function xO(e,t){return[e,...t].map(lO).join(` `)}function SO(){return c.join(m.homedir(),`Applications`,`${vO}.app`)}function CO(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function wO(){if(process.platform===`darwin`)return c.join(m.homedir(),`Library`,`Application Support`,`CCCandybar`);let e=process.env.XDG_DATA_HOME??c.join(m.homedir(),`.local`,`share`);return c.join(e,`cc-candybar`)}function TO(){return c.join(wO(),`bin`,`cc-candybar`)}function EO(){return c.join(wO(),`dist`,`index.mjs`)}function DO(e,t){return[`on open location L`,`\tdo shell script "'${e.replace(/"/g,`\\"`)}' '${t.replace(/"/g,`\\"`)}' url-handle " & quoted form of L`,`end open location`].join(`
170
- `)}function OO(e){let t=/do shell script "'([^']+)' '([^']+)' url-handle "/.exec(e);if(t===null)return null;let n=e=>e.replace(/\\"/g,`"`);return{node:n(t[1]),script:n(t[2])}}function kO(e){return c.join(e,`Contents`,`Resources`,`Scripts`,`main.scpt`)}function AO(e){if(!e)throw Error(`install: process.argv[1] not set`);return e.endsWith(`.mjs`)||e.endsWith(`.js`)?e:c.resolve(c.dirname(e),`..`,`dist`,`index.mjs`)}function jO(t){let n=bO[`${process.platform}-${process.arch}`];if(n){let r=e(t);try{return{kind:`native`,sourcePath:r.resolve(`${n}/bin/cc-candybar`)}}catch{}}return{kind:`node-shim`,sourcePath:c.resolve(c.dirname(t),`..`,`bin`,`cc-candybar`)}}function MO(e,t){c.resolve(e)!==c.resolve(t)&&r.copyFileSync(e,t)}function NO(e){let t=r.openSync(e,`r`);try{let n=Buffer.alloc(2),i=r.readSync(t,n,0,2,0);if(i<2)throw Error(`install: staged render entry at ${e} is truncated (${i} byte(s)). Re-run: pnpm dlx ${mO}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function PO(){let e=AO(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=jO(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(c.dirname(EO()),{recursive:!0}),r.mkdirSync(c.dirname(TO()),{recursive:!0}),MO(e,EO()),MO(t.sourcePath,TO()),r.chmodSync(TO(),493),r.rmSync(c.join(wO(),`url-handler.mjs`),{force:!0});let n=NO(TO());return process.stdout.write(`Staged cc-candybar v${zE} runtime at ${wO()}\n`+(n===`native`?` render entry: native binary (${process.platform}-${process.arch})\n`:` render entry: node shim (no native binary for ${process.platform}-${process.arch}; renders are correct but pay node startup)\n`)),{binPath:TO(),distPath:EO(),entryKind:n}}function FO(){return[{key:`CFBundleIdentifier`,xml:`<string>com.cccandybar.url-handler</string>`},{key:`CFBundleURLTypes`,xml:[`<array>`,` <dict>`,` <key>CFBundleURLName</key>`,` <string>Claude Powerline Click Action</string>`,` <key>CFBundleURLSchemes</key>`,` <array>`,` <string>${DD}</string>`,` </array>`,` </dict>`,`</array>`].join(`
171
- `)}]}function IO(e){let t=SO();r.mkdirSync(c.dirname(t),{recursive:!0}),r.existsSync(t)&&r.rmSync(t,{recursive:!0,force:!0}),process.stdout.write(`Building ${t}\n`);let n=Ae({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,DO(process.execPath,e)],category:`install.osacompile`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`osacompile failed (${n.reason})`);let i=c.join(t,`Contents`,`Info.plist`);for(let{key:e}of FO())Ae({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of FO()){let n=Ae({bin:`/usr/bin/plutil`,args:[`-insert`,e,`-xml`,t,i],category:`install.plutil`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`plutil -insert ${e} failed (${n.reason})`)}process.stdout.write(`Registering ${DD}:// with Launch Services\n`);let a=Ae({bin:`/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister`,args:[`-f`,t],category:`install.lsregister`});if(!a.ok)throw process.stderr.write(a.stderr),Error(`lsregister failed (${a.reason})`);process.stdout.write(`✓ ${vO}.app installed and registered.\n`),process.stdout.write(` Test: open '${DD}://hello-world' && pbpaste\n`)}function LO(){CO(),IO(PO().distPath)}function RO(e,t=DD){let n=`${t}://`;if(!e.startsWith(n))throw Error(`expected ${n} scheme, got: ${e}`);let r=e.slice(n.length),i=r.indexOf(`/`);return i===-1?{verb:jD,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function zO(e){e||(process.stderr.write(`url-handle: missing URL argument.
172
- `),process.exit(1));let t;try{t=RO(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await WE(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(lD(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(BO(n)+`
173
- `),process.exit(1)}function BO(e){switch(e.cause){case`version_mismatch`:return`url-handle: daemon rejected click (version mismatch: client v${e.clientV} ≠ daemon v${e.daemonV})`;case`bad_request`:return`url-handle: daemon rejected click (bad request: ${e.message})`;case`render_failed`:return`url-handle: daemon rejected click (handler failed: ${e.message})`;case`malformed_response`:return`url-handle: daemon rejected click (malformed response: ${e.message})`}}function VO(){return`✓ install complete.
166
+ Single-row example: root: { h: ["seg1", "seg2"] }`,line:G(e.source,[`layout`])}),t.root!==void 0&&(r.root=gd(e,`root`,t.root)),t.actions!==void 0&&(r.actions=Nw(e,t.actions)),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:G(e.source,[`looks`])}),t.styles!==void 0&&(r.styles=CT(e,t.styles)),t.presets!==void 0&&(r.presets=TT(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=Al(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=ET(e,t.helpers)),wd(e,r),G_(e,r),sv(e,r),Au(e,r,Eu,`the global settings menu`),r}const xE=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`presets`,`editGlobals`,`helpers`]);function SE(e){let t=OE(e.termCols),n=OE(e.termRows),r=kE(e.ssh),i=EE(e.tmux),a=TE(e.configEnv),o=wE(e.claudeConfigDir),s=CE(e.mementoEnv);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&&{mementoEnv:s}}}function CE(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Ze.filter(e=>t[e]!==void 0);return n.every(e=>wE(t[e])!==void 0)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function wE(e){return typeof e==`string`&&c.isAbsolute(e)?e:void 0}function TE(e){return typeof e==`string`&&e!==``?rE(e):void 0}function EE(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 DE=1e4;function OE(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>DE?DE:t}function kE(e){return typeof e==`boolean`?e:void 0}function AE(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var jE=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function ME(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function NE(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 jE(`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 jE(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function PE(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.removeAllListeners();try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n),c=NE(e=>o(()=>r(e)),e=>o(()=>i(e)));e.on(`data`,c),e.on(`error`,e=>o(()=>i(e))),e.on(`close`,()=>o(()=>i(Error(`socket closed before response`)))),e.write(ME(t))})}async function FE(e,t,n){let r=null;try{r=await BE(Le(),t.connectMs);let i=await PE(r,{v:3,...e},t.budgetMs);return RE(e.kind,i,n)}catch(e){return zE(e)}finally{r&&r.destroy()}}function IE(e,t){return typeof e==`string`?e:t}function LE(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function RE(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=IE(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:LE(r.daemonV)};case`TIMEOUT`:return{kind:`transient`,cause:`timeout`,message:i};case`BAD_REQUEST`:return{kind:`permanent`,cause:`bad_request`,message:i};case`RENDER_FAILED`:return{kind:`permanent`,cause:`render_failed`,message:i};default:return{kind:`permanent`,cause:`malformed_response`,message:`unknown error code: ${String(r.code)}`}}}function zE(e){if(e instanceof jE||e instanceof SyntaxError)return{kind:`permanent`,cause:`malformed_response`,message:e instanceof Error?e.message:String(e)};let t=e instanceof Error?e.message:String(e);return t===`CONNECT_TIMEOUT`||t===`TIMEOUT`?{kind:`transient`,cause:`timeout`,message:t}:t.includes(`ECONNREFUSED`)||t.includes(`ENOENT`)||t.includes(`ENOTSOCK`)?{kind:`transient`,cause:`unreachable`,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function BE(e,t){return new Promise((n,r)=>{let i=b.createConnection({path:e}),a=setTimeout(()=>{i.destroy(),r(Error(`CONNECT_TIMEOUT`))},t);i.once(`connect`,()=>{clearTimeout(a),n(i)}),i.once(`error`,e=>{clearTimeout(a),r(e)})})}function VE(e){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`malformed_response`:return`daemon error (${e.cause}): ${e.message}`}}const HE=`1.116.1`,UE={connectMs:50,budgetMs:150},WE={connectMs:50,budgetMs:200};function GE(e){let t=e.output;return typeof t==`string`?t:void 0}function KE(e,t,n,r){return FE({kind:`render`,hookData:e,args:t,cwd:n,...r},UE,GE)}function qE(e,t){return FE({kind:`click`,verb:e,value:t,clientVersion:HE},WE,GE)}function JE(e){let t=[];for(let n of e){let e=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(`
167
+ `)}function YE(e,t){return e===`darwin`?[XE(`footprint`,[`-p`,String(t)]),XE(`vmmap`,[`--summary`,String(t)])]:e===`linux`?[ZE(`/proc/self/smaps_rollup`),ZE(`/proc/self/status`)]:[]}function XE(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=Ae({bin:e,args:[...t],timeoutMs:5e3,category:`limits.memory-report`});return n.ok?n.stdout.trim().length>0?{kind:`text`,text:n.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${n.reason}${n.error===void 0?``:`: ${n.error}`}${QE(n.stderr)}`}}}}function ZE(e){return{name:e,read:()=>{try{let t=r.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}function QE(e){let t=e.split(`
168
+ `).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const $E=`CC_CANDYBAR_RSS_LIMIT_MB`;function eD(e){let t=e[$E];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${$E} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function tD(e){return eD(e)*2}const nD=1024*1024;function rD(e){return eD(e)*nD}const iD={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function aD(e,t,n){let{prefix:r,suffix:i}=iD[t];return c.join(e,`${r}${n}${i}`)}function oD(e){for(let t of Object.keys(iD)){let{prefix:n,suffix:r}=iD[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function sD(e){let t=e.rssLimitBytes??512*nD,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let{rss:i,heapTotal:a}=e.memoryBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t} (v8 heap ${a}); recording memory then shutting down`);let o=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return cD(e.log,`memory report`,()=>{let t=aD(e.snapshotDir,`memoryReport`,o);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),cD(e.log,`heap snapshot`,()=>{let t=aD(e.snapshotDir,`heapSnapshot`,o);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),cD(e.log,`artifact rotation`,()=>{uD(e.listArtifacts(),n,e.removeFile)}),e.shutdown(0),!0}function a(){let{rss:n,heapTotal:r}=e.memoryBytes();return n>t*.75?`rss ${n} approaching limit ${t} (v8 heap ${r})`:null}function o(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:o}}function cD(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function lD(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=oD(t);if(n===null)return t;let{prefix:r,suffix:i}=iD[n];return t.slice(r.length,t.length-i.length)}function uD(e,t,n){let r=new Map;for(let t of e){let e=lD(t),n=r.get(e);n===void 0?r.set(e,[t]):n.push(t)}let i=[...r.keys()].sort((e,t)=>t.localeCompare(e));for(let e of i.slice(t))for(let t of r.get(e)??[])try{n(t)}catch{}}function dD(e,t,n={}){let i=Ie();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:Z,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},captureMemoryReport:()=>JE(YE(process.platform,process.pid)),writeMemoryReport:(e,t)=>r.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>ne.writeHeapSnapshot(e),listArtifacts:()=>{try{return r.readdirSync(i).filter(e=>oD(e)!==null).map(e=>c.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function fD(e={}){if(OD()!==null)return;let n=e.spawn??kD,r=TD();if(r.kind===`contended`){let e=mD();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),pD(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),pD(n);return}try{pD(n)}finally{DD()}}function pD(e){xD()&&hD(e)}function mD(){try{let e=r.statSync(Ke());return Date.now()-e.mtimeMs}catch{return null}}function hD(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
169
+ `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function gD(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function _D(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function vD(e){try{let t=r.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function yD(e,n){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function bD(){try{r.unlinkSync(Je())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function xD(){let e=qe(),n=Je(),r=vD(n),i=gD(SD(e),_D(r));return i.kind===`deny`?!1:(i.kind===`allow-future-garbage`&&t.stderr.write(`cc-candybar: spawn.cooldown mtime is ${i.futureMs}ms in the future — ignoring and spawning\n`),CD(e),yD(n,Math.min(r+1,5)),!0)}function SD(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function CD(e){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,`${t.pid} ${Date.now()}\n`,{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}let wD=null;function TD(){let e=Ke();for(let n=0;n<2;n++){try{let n=r.openSync(e,`wx`,384);try{r.writeSync(n,JSON.stringify({pid:t.pid,ts:Date.now()}))}catch{}return wD={fd:n,path:e},{kind:`held`}}catch(t){let n=t.code;if(n!==`EEXIST`)return{kind:`error`,reason:`openSync(${e}): ${n??t.message}`}}if(!ED(e))return{kind:`contended`};try{r.unlinkSync(e)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function ED(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function DD(){if(!wD)return;let{fd:e,path:t}=wD;wD=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function OD(){try{return r.mkdirSync(Ie(),{recursive:!0}),null}catch(e){return`mkdir ${Ie()}: ${e.message}`}}function kD(){let e=t.execPath,n=t.argv[1];return n?k({bin:e,args:[`--max-old-space-size=${tD(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const AD=`cc-candybar`,jD=`dispatch`,MD=`set-state`,ND=`step-state`,PD=`copy`,FD=`open-vscode`,ID=`toolbar-toggle`,LD=`show-config-error`,RD=`show-config-warning`,zD=`set-config`,BD=`step-config`,VD=`save`,HD=`save-preset`,UD=`delete-preset`,WD=`reset-config`,GD=`apply-layout-op`,KD=`undo`,qD=`redo`,JD=`back`,YD=`rewind`,XD=`apply-update`,ZD=`doctor-run`,QD=`doctor-fix`,$D=`doctor-probe`,eO=`ceiling`,tO=`slash`;function nO(e){return e.map(encodeURIComponent).join(`/`)}function rO(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function iO(e){return`${AD}://${jD}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${nO(e.args)}`)}`).join(`&`)}`}function aO(e){return new ie(e).getAll(`e`).map(lO)}const oO=new Set([MD,WD]);function sO(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&cO(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function cO(e,t){if(e.verb!==t.verb||!oO.has(e.verb))return;let[n,r]=[lO(e.value),lO(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function lO(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const uO=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function dO(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function fO(e){return uO.test(e)?e:dO(e)}const pO=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function mO(e){let t=pO.exec(e);return t?{kind:`ok`,value:[Number(t[1]),Number(t[2]),Number(t[3])]}:{kind:`failed`,reason:`"${e}" is not a release version (expected MAJOR.MINOR.PATCH)`}}function hO(e){return e.join(`.`)}function gO([e,t,n],[r,i,a]){return e-r||t-i||n-a}const _O=`@promptctl/cc-candybar`;async function vO(e,t,n){let r=`${n}/-/package/${encodeURIComponent(e)}/dist-tags`;try{let e=await t(r,{signal:AbortSignal.timeout(5e3)});if(!e.ok)return X(`registry responded ${e.status} for ${r}`);let n=await e.json();return typeof n.latest==`string`?mO(n.latest):Y}catch(e){return X(e instanceof Error?e.message:String(e))}}function yO(e,t){let n=mO(e);if(n.kind===`failed`)return{kind:`unchecked`,installed:e,reason:n.reason};switch(t.kind){case`failed`:return{kind:`unchecked`,installed:e,reason:t.reason};case`absent`:return{kind:`unchecked`,installed:e,reason:"the registry lists no `latest` dist-tag"};case`ok`:{let e=gO(n.value,t.value);return e<0?{kind:`stale`,installed:n.value,latest:t.value}:e>0?{kind:`ahead`,installed:n.value,latest:t.value}:{kind:`current`,installed:n.value}}}}function bO(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${hO(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${hO(t.installed)} is newer than the registry's latest release (${hO(t.latest)}): an unpublished build.\n`};case`stale`:{let n=hO(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${hO(t.installed)} was staged, but the latest release is ${n}.\n pnpm's release-age gate (minimumReleaseAge) and its dlx cache can both\n resolve \`@latest\` to an older release without saying so.\n To install ${n} now, name it explicitly:\n pnpm dlx ${e}@${n} install\n`}}case`unchecked`:return{stream:`stderr`,text:`⚠ Could not check for a cc-candybar release newer than ${t.installed} (${t.reason}); the registry check was skipped.\n`}}}const xO=`CCCandybarURLHandler`,SO=[],CO={"darwin-arm64":`@promptctl/cc-candybar-darwin-arm64`,"darwin-x64":`@promptctl/cc-candybar-darwin-x64`,"linux-x64":`@promptctl/cc-candybar-linux-x64`,"linux-arm64":`@promptctl/cc-candybar-linux-arm64`};function wO(e,t){return[e,...t].map(fO).join(` `)}function TO(){return c.join(m.homedir(),`Applications`,`${xO}.app`)}function EO(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function DO(){if(process.platform===`darwin`)return c.join(m.homedir(),`Library`,`Application Support`,`CCCandybar`);let e=process.env.XDG_DATA_HOME??c.join(m.homedir(),`.local`,`share`);return c.join(e,`cc-candybar`)}function OO(){return c.join(DO(),`bin`,`cc-candybar`)}function kO(){return c.join(DO(),`dist`,`index.mjs`)}function AO(e,t){return[`on open location L`,`\tdo shell script "'${e.replace(/"/g,`\\"`)}' '${t.replace(/"/g,`\\"`)}' url-handle " & quoted form of L`,`end open location`].join(`
170
+ `)}function jO(e){let t=/do shell script "'([^']+)' '([^']+)' url-handle "/.exec(e);if(t===null)return null;let n=e=>e.replace(/\\"/g,`"`);return{node:n(t[1]),script:n(t[2])}}function MO(e){return c.join(e,`Contents`,`Resources`,`Scripts`,`main.scpt`)}function NO(e){if(!e)throw Error(`install: process.argv[1] not set`);return e.endsWith(`.mjs`)||e.endsWith(`.js`)?e:c.resolve(c.dirname(e),`..`,`dist`,`index.mjs`)}function PO(t){let n=CO[`${process.platform}-${process.arch}`];if(n){let r=e(t);try{return{kind:`native`,sourcePath:r.resolve(`${n}/bin/cc-candybar`)}}catch{}}return{kind:`node-shim`,sourcePath:c.resolve(c.dirname(t),`..`,`bin`,`cc-candybar`)}}function FO(e,t){c.resolve(e)!==c.resolve(t)&&r.copyFileSync(e,t)}function IO(e){let t=r.openSync(e,`r`);try{let n=Buffer.alloc(2),i=r.readSync(t,n,0,2,0);if(i<2)throw Error(`install: staged render entry at ${e} is truncated (${i} byte(s)). Re-run: pnpm dlx ${_O}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function LO(){let e=NO(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=PO(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(c.dirname(kO()),{recursive:!0}),r.mkdirSync(c.dirname(OO()),{recursive:!0}),FO(e,kO()),FO(t.sourcePath,OO()),r.chmodSync(OO(),493),r.rmSync(c.join(DO(),`url-handler.mjs`),{force:!0});let n=IO(OO());return process.stdout.write(`Staged cc-candybar v${HE} runtime at ${DO()}\n`+(n===`native`?` render entry: native binary (${process.platform}-${process.arch})\n`:` render entry: node shim (no native binary for ${process.platform}-${process.arch}; renders are correct but pay node startup)\n`)),{binPath:OO(),distPath:kO(),entryKind:n}}function RO(){return[{key:`CFBundleIdentifier`,xml:`<string>com.cccandybar.url-handler</string>`},{key:`CFBundleURLTypes`,xml:[`<array>`,` <dict>`,` <key>CFBundleURLName</key>`,` <string>Claude Powerline Click Action</string>`,` <key>CFBundleURLSchemes</key>`,` <array>`,` <string>${AD}</string>`,` </array>`,` </dict>`,`</array>`].join(`
171
+ `)}]}function zO(e){let t=TO();r.mkdirSync(c.dirname(t),{recursive:!0}),r.existsSync(t)&&r.rmSync(t,{recursive:!0,force:!0}),process.stdout.write(`Building ${t}\n`);let n=Ae({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,AO(process.execPath,e)],category:`install.osacompile`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`osacompile failed (${n.reason})`);let i=c.join(t,`Contents`,`Info.plist`);for(let{key:e}of RO())Ae({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of RO()){let n=Ae({bin:`/usr/bin/plutil`,args:[`-insert`,e,`-xml`,t,i],category:`install.plutil`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`plutil -insert ${e} failed (${n.reason})`)}process.stdout.write(`Registering ${AD}:// with Launch Services\n`);let a=Ae({bin:`/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister`,args:[`-f`,t],category:`install.lsregister`});if(!a.ok)throw process.stderr.write(a.stderr),Error(`lsregister failed (${a.reason})`);process.stdout.write(`✓ ${xO}.app installed and registered.\n`),process.stdout.write(` Test: open '${AD}://hello-world' && pbpaste\n`)}function BO(){EO(),zO(LO().distPath)}function VO(e,t=AD){let n=`${t}://`;if(!e.startsWith(n))throw Error(`expected ${n} scheme, got: ${e}`);let r=e.slice(n.length),i=r.indexOf(`/`);return i===-1?{verb:PD,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function HO(e){e||(process.stderr.write(`url-handle: missing URL argument.
172
+ `),process.exit(1));let t;try{t=VO(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await qE(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(fD(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(UO(n)+`
173
+ `),process.exit(1)}function UO(e){switch(e.cause){case`version_mismatch`:return`url-handle: daemon rejected click (version mismatch: client v${e.clientV} ≠ daemon v${e.daemonV})`;case`bad_request`:return`url-handle: daemon rejected click (bad request: ${e.message})`;case`render_failed`:return`url-handle: daemon rejected click (handler failed: ${e.message})`;case`malformed_response`:return`url-handle: daemon rejected click (malformed response: ${e.message})`}}function WO(){return`✓ install complete.
174
174
  Restart Claude Code to pick up the new statusline.
175
- Tip: every bar carries a settings menu — click it (${qc} by\n default) for quick actions, preset switching, edit mode, and clickable\n theme/style/variation/endcaps/wrap/padding controls.\n`}async function HO(e){let t=e.includes(`--force`),n=e.filter(e=>e!==`--force`),r=n.length>0?n:[...yO],i=PO();process.platform===`darwin`?IO(i.distPath):process.stdout.write(`Skipping URL handler (cmd-click verbs are macOS-only).
176
- `),UO(i.binPath,r,t),process.stdout.write(VO());let a=_O(mO,gO(zE,await hO(mO,fetch,`https://registry.npmjs.org`)));process[a.stream].write(a.text)}function UO(e,t,n,i){let a=i??mS(pS(fS(process.env,process.cwd())));r.mkdirSync(c.dirname(a),{recursive:!0});let o={};if(r.existsSync(a))try{o=JSON.parse(r.readFileSync(a,`utf-8`))}catch(e){throw Error(`Could not parse ${a}: ${e instanceof Error?e.message:String(e)}`)}let s=o.statusLine?.command,l=[e,lO(e),cO(e)],u=typeof s==`string`&&(s.startsWith(`pnpm dlx @promptctl/cc-candybar@`)||l.some(e=>s===e||s.startsWith(`${e} `)));if(s&&!u&&!n){process.stderr.write(`Skipping settings.json update: existing statusLine.command appears customized.\n Current: ${s}\n To overwrite, re-run with --force.\n`);return}o.statusLine={type:`command`,command:xO(e,t)},Me(a,JSON.stringify(o,null,2)),process.stdout.write(`Updated ${a}\n`)}function WO(e,t){return e.kind===`owned`?t(e.pid,e.startTime)?{kind:`attach-and-exit`,reason:`live owner pid=${e.pid} holds the socket`}:{kind:`reclaim`,reason:`owner pid=${e.pid} is gone or recycled`}:e.kind===`absent`?{kind:`reclaim`,reason:`no lease — stale socket, no live owner`}:{kind:`reclaim`,reason:`unreadable lease (${e.detail}) — cannot prove a live owner`}}function GO(e){let t;try{t=r.readFileSync(e,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`absent`}:{kind:`unreadable`,detail:`read failed: ${e.message}`}}let n;try{n=JSON.parse(t)}catch(e){return{kind:`unreadable`,detail:`bad JSON: ${e.message}`}}let i=n,a=i?.pid;if(typeof a!=`number`||!Number.isInteger(a)||a<=0)return{kind:`unreadable`,detail:`no valid pid (got ${JSON.stringify(a)})`};let o=i?.startTime;return o!=null&&typeof o!=`string`?{kind:`unreadable`,detail:`invalid startTime (got ${JSON.stringify(o)})`}:{kind:`owned`,pid:a,startTime:o??null}}function KO(e,n){let i=`${e}.${t.pid}.tmp`;try{return r.writeFileSync(i,JSON.stringify(n),{mode:384}),r.renameSync(i,e),null}catch(e){let t=e.message;try{r.unlinkSync(i)}catch(e){if(e.code!==`ENOENT`)return`${t}; also failed to remove temp ${i}: ${e.message}`}return t}}function qO(e,t){let n=GO(e);if(n.kind===`owned`&&n.pid===t)try{r.unlinkSync(e)}catch{}}function JO(e){try{let t=r.statSync(e);return{kind:`present`,identity:{dev:t.dev,ino:t.ino}}}catch(e){return e.code===`ENOENT`?{kind:`absent`}:{kind:`unreadable`,detail:e.message}}}function YO(e,t,n,r){let i=XO(e,t);return i===null?r.kind===`owned`?r.pid===n?{kind:`owned`}:{kind:`displaced`,reason:`lease reassigned (names pid=${r.pid}, we are pid=${n}) — a reclaimer overwrote it`}:{kind:`displaced`,reason:`lease not held (${r.kind}) — no longer the socket owner`}:{kind:`displaced`,reason:i}}function XO(e,t){return t.kind===`present`?t.identity.dev===e.dev&&t.identity.ino===e.ino?null:`socket replaced (bound dev=${e.dev} ino=${e.ino}, now dev=${t.identity.dev} ino=${t.identity.ino})`:t.kind===`absent`?`socket path gone (ENOENT) — unlinked by a reclaimer`:`socket path unreadable (${t.detail}) — cannot prove ownership`}function ZO(e){let t=!1;function n(){let n=YO(e.bound,e.readIdentity(),e.myPid,e.readLease());return n.kind===`displaced`&&!t&&(t=!0,e.log(`warn`,`ownership self-check: ${n.reason}; shutting down`),e.shutdown(0)),n}function r(t=e.intervalMs??5e3){let r=setInterval(()=>{n().kind===`displaced`&&clearInterval(r)},t);return r.unref(),{disarm:()=>clearInterval(r)}}return{check:n,arm:r}}function QO(e,t=Ae){let n=t({bin:`ps`,args:[`-o`,`lstart=`,`-p`,String(e)],category:`process-fingerprint`,timeoutMs:2e3,env:{...process.env,LC_ALL:`C`,TZ:`UTC`}});if(n.ok){let e=n.stdout.trim();return e.length>0?{kind:`start`,token:e}:{kind:`unavailable`,detail:`ps produced no start-time`}}return{kind:`unavailable`,detail:n.reason===`spawn-error`?n.error??`ps spawn failed`:`ps ${n.reason} (exit ${n.exitCode})`}}function $O(e,t,n){if(t===null)return n.pidAlive(e);let r=n.readStartTime(e);switch(r.kind){case`start`:return r.token===t;case`unavailable`:return n.pidAlive(e)}}function ek(e,t=QO){let n=t(e);return n.kind===`start`?n.token:null}const tk=`CC_CANDYBAR_PARENT_PID`;function nk(e){let t=e[tk];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${tk} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function rk(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor,n=setInterval(()=>{e.isAlive(t)||e.onOrphaned(`spawner pid ${t} gone`)},e.intervalMs??250);return n.unref(),{disarm:()=>clearInterval(n)}}function ik(e){try{return t.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function ak(){let e=Number(process.env.CC_CANDYBAR_DAEMON_CEILING??``);return Number.isInteger(e)&&e>0?e:16}function ok(e,t,n){return e?t>=n?{allow:!1,reason:`${t} live isolated daemons registered >= ceiling ${n}`}:{allow:!0,reason:`${t} live isolated daemons registered < ceiling ${n}`}:{allow:!0,reason:`canonical production socket — exempt (bind() already caps it to one)`}}function sk(e){try{return r.readdirSync(e).filter(e=>e.endsWith(`.json`)).map(t=>c.join(e,t))}catch{return[]}}function ck(e){let t;try{t=r.readFileSync(e,`utf8`)}catch{return null}try{let e=JSON.parse(t),n=e?.pid;return typeof n!=`number`||!Number.isInteger(n)||n<=0?null:{pid:n,startTime:typeof e?.startTime==`string`?e.startTime:null}}catch{return null}}function lk(e,t,n){let r=0;for(let i of e)t(i.identity.pid,i.identity.startTime)?r++:n(i.path);return r}function uk(e){if(!e.isolated)return{decision:ok(!1,0,e.ceiling),registryPath:null};e.ensureDirSafe(e.registryDir);let t=[];for(let n of e.listFiles(e.registryDir)){let r=e.readEntry(n);r!==null&&r.pid!==e.pid&&t.push({path:n,identity:r})}let n=ok(!0,lk(t,e.isSameLiveProcess,e.removeFile),e.ceiling);if(!n.allow)return{decision:n,registryPath:null};let r=c.join(e.registryDir,`pid-${e.pid}.json`);return e.writeEntry(r,{pid:e.pid,startTime:e.startTime}),{decision:n,registryPath:r}}function dk(e,t,n,r){let i=n(e);if(i!==null&&i.pid===t)try{r(e)}catch{}}function fk(e,t={}){return{isolated:!!process.env.CC_CANDYBAR_SOCKET,registryDir:Ge(),ceiling:ak(),pid:process.pid,startTime:e,isSameLiveProcess:(e,t)=>$O(e,t,{readStartTime:QO,pidAlive:ik}),listFiles:sk,readEntry:ck,removeFile:e=>{try{r.unlinkSync(e)}catch{}},writeEntry:(e,t)=>{let n=`${e}.${t.pid}.tmp`;try{r.writeFileSync(n,JSON.stringify(t),{mode:384}),r.renameSync(n,e)}catch(e){try{r.unlinkSync(n)}catch(e){e.code}throw e}},ensureDirSafe:process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR?ze:e=>{ze(c.dirname(e)),ze(e)},...t}}function pk(e){return e<32||e===127||e>=128&&e<=159}function mk(e){let t=``;for(let n of e)t+=pk(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function hk(e,t){let n=mk(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const gk=`\x1B[38;2;255;255;255m`,_k=`\x1B[48;2;200;40;40m`;function vk(e){let t=/;2;(\d+);(\d+);(\d+)m$/.exec(e);if(t===null)throw Error(`diagnostic-style: not a 24-bit SGR: ${e}`);return`#`+t.slice(1,4).map(e=>Number(e).toString(16).padStart(2,`0`)).join(``)}const yk={fg:vk(gk),bg:vk(_k)},bk={fg:vk(`\x1B[38;2;0;0;0m`),bg:vk(`\x1B[48;2;220;160;40m`)},xk={unicode:Bi,ascii:{glyph:`>`,divider:`|`,lead:`<`,tail:`>`}},Sk={unicode:{},ascii:{left:`(`,right:`)`}};function Ck(e,t,n){switch(e){case`capsule`:return new Ki(Sk[t]);case`plain`:return new qi(n===void 0?{}:{separator:n});case`powerline`:return new Ui(xk[t]);default:return e}}const wk=new Map;function Tk(e){let t=JSON.stringify([e.endcaps,e.charset,e.separator??null]),n=wk.get(t);if(n!==void 0)return n;let r=Ck(e.endcaps,e.charset,e.separator),i=e=>new W(`x`,{end:``,overflow:`ignore`,style:new V({bgcolor:e})}),a=e=>new W(Xi(new Mi(e,r),{colorSystem:null}).replace(/\n$/,``)).cellLength,o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return wk.set(t,s),s}function Ek(e){return Tk(e).chrome}function Dk(e){return Tk(e).seam}function Ok(e,t){if(e.length===0)return``;let n=Ck(t.endcaps,t.charset,t.separator),r=t.colorCompatibility,i=t.wrap&&Number.isFinite(t.width)?Xi(new na([...e],{joiner:n}),{width:t.width,colorSystem:r}):Xi(new Mi([...e],n),{colorSystem:r});if(!i.endsWith(`
177
- `))throw Error(`renderStripCells: rich-js strip output did not end its last line`);return i.slice(0,-1)}function kk(e){return Math.min(20,e??20)}const Ak={heading:`ERROR`,glyph:`⚠`,colors:yk},jk={heading:`WARNING`,glyph:`⚠`,colors:bk},Mk={heading:`UPDATE`,glyph:`⬆`,colors:bk};function Nk(e,t){return{text:mk(e),link:t}}function Pk(e,t,n){let[r,...i]=[Fk(e,Ak,PD),t,Fk(n,jk,FD)].flat();return r===void 0?null:{channels:[r,...i]}}function Fk(e,t,n){let r=tO([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>Nk(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function Ik(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
178
- `)}function Lk(e,t,n,r){if(t===null)return e;let i=Rk(r),a=t.channels.flatMap(e=>zk(e,i)),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[Bk(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
179
- `);return e?`${l}\n${e}`:l}function Rk(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function zk(e,t){let n=new V({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=Ht(Math.max(2,t.width-1)),i=(e,t)=>new W(`${e} `,{style:t,end:``,overflow:`ignore`});return e.lines.flatMap((a,o)=>Ok([i(o===0?e.severity.glyph:` `,n.withLink(a[0].link)),...a.flatMap(e=>{let t=n.withLink(e.link);return e.text.split(` `).flatMap(e=>Kt(e,r)).map(e=>i(e,t))})],t).split(`
180
- `))}function Bk(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new V({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new W(e,{style:t,end:``,overflow:`ignore`}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(E(a.path).href)):c(`full text unavailable: ${mk(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(mk(o),s.withLink(E(o).href))],d=[c(`↳ `,s),...l,...u.slice(0,-1)],f=d.reduce((e,t)=>e+t.cellLength,0),p=u.slice(-1).map(e=>e.truncate(Math.max(1,r.width-f),{mode:`middle`})),m=W.fromFragments([...d,...p]).truncate(r.width);return m.overflow=`ignore`,Ok([m],r)}const Vk=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Hk(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function Uk(e,t){return r.readdirSync(t).filter(Vk).sort().flatMap(n=>{let i=c.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?Uk(e,i):[[c.relative(e,i).split(c.sep).join(`/`),Hk(i,a)]]})}function Wk(e){let t=ae.createHash(`sha256`);for(let[n,r]of Uk(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const Gk=e=>e.slice(0,7);function Kk(e){return c.dirname(c.dirname(e))}function qk(){return{version:zE,digest:`9a98822c1a5e5e374bf3e2ca33787cb120cff2446f1aedad8b1561ec895514fd`}}function Jk(e){let t=JSON.parse(r.readFileSync(c.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${c.join(e,`package.json`)} has no version string`);return n}function Yk(e,t){try{let n=Kk(T(e)),i=c.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=Wk(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:Jk(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var $=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};function Xk(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function Zk(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 Qk(e,t,n){let r=Ms(e,new Set(n.map(js).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const $k=/^-?\d+$/;function eA(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 tA(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!$k.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 nA(e,t,n){return r=>r?$k.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 rA(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=>!$k.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 iA(e){return e===`config`?`set-config`:`set-state`}function aA(e,t,n){return t.kind===`int`?tA(`menu page "${e}"`):t.kind===`range`?nA(t.min,t.max,`${n} stepper "${e}"`):eA(t.allowed,`${n} "${e}"`,iA(n))}function oA(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:rA(e,n,t)}))}function sA(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 oA(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,aA(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 cA(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};sA(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=sA(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const lA=cA({},`config`,gA);function uA(e,t){return lA.register(e,t)}function dA(e){return lA.gateFor(e)}function fA(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:dx(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:[Xk({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Xk({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:dx(e.insertSegmentFrom,t).members.map(t=>Xk({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function pA(e,t){let n=Fl(e).get(t);return n===void 0?null:String(n)}function mA(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?Cx(n.persist):null;e?.scope===`preset-root`&&t.add(xx(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function hA(e){let t=new Map([...lx(e),...uw(e)]);return[...mA(e),...Object.values(e.actions).flatMap(e=>fA(e,t))]}function gA(e){return oA(hA(e),`config`)}const _A=dS(`commands.`),vA=wS(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),yA=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,bA=`{{ \$dir := .current_dir }}{{ if and (ne .home "") (or (eq .home .current_dir) (hasPrefix (printf "%s/" .home) .current_dir)) }}{{ \$dir = printf "~%s" (trimPrefix .home .current_dir) }}{{ else }}{{ if or (eq .project_dir .current_dir) (hasPrefix (printf "%s/" .project_dir) .current_dir) }}{{ $dir = ternary (${yA}) (basename .project_dir) (ne (${yA}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,xA=`{{ ${Ix} }}`,SA={min:0,max:100,step:5},CA={warnAt:{label:`warning at %`,domain:SA,default:50},errorAt:{label:`error at %`,domain:{...SA,atLeast:`warnAt`},default:80}};function wA(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:SA,default:80}}}const TA={globals:{palette:`tokyo-night`},variables:{..._A.variables,...Lb,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},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.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.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"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:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"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},"memento.ceiling":{kind:`input`,path:`memento.ceiling`,type:`number`,default:-1},"memento.off":{kind:`input`,path:`memento.off`,type:`boolean`,default:!1},"memento.session":{kind:`input`,path:`memento.session`,default:``},"memento.error":{kind:`input`,path:`memento.error`,default:``},"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 current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:bA},model:{group:`model-context`,description:`The active model's display name.`,template:`✱ {{ formatModelName .model.display_name }}`,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 eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}`,fg:xA,when:`{{ ne .git.branch "" }}`,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 ne .git.prUrl "" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (ne .git.prUrl "") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:eS(``).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:_A.template,when:_A.when},themeSwitcher:{group:`session-tools`,description:"`◀ <theme> ▶`: the theme the bar is wearing; ◀ and ▶ switch this session to the previous or next theme, wrapping at the ends.",template:`{{ carousel "stepTheme" 0 }}`},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:wA(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:wA(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:CA,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:CA,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) ${Aa} }}`,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 }}`},ceiling:{group:`model-context`,description:`The memento plugin's context ceiling for this session: − and + move it by 100K, ∞ lifts it, ↺ drops this session's own setting.`,template:`{{ if ne .memento.error "" }}⌈ ⚠ {{ .memento.error }} {{ action "ceiling.clear" "↺" }}{{ else }}⌈ {{ if .memento.off }}off{{ else }}{{ template "formatTokenCount" .memento.ceiling }} {{ action "ceiling.lower" "−" }} {{ action "ceiling.raise" "+" }} {{ action "ceiling.off" "∞" }}{{ end }}{{ if ne .memento.session "" }} {{ action "ceiling.clear" "↺" }}{{ end }}{{ end }}`,bg:`{{ if ne .memento.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .memento.ceiling 0) (ne .memento.error "") }}`},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:vA.template,bg:vA.bg,when:vA.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:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...eS(``).actions,..._A.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},"ceiling.raise":{ceiling:`set`,to:`+100_000`},"ceiling.lower":{ceiling:`set`,to:`-100_000`},"ceiling.off":{ceiling:`set`,to:`off`},"ceiling.clear":{ceiling:`clear`},...vA.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}},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:`ceiling`},{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:`ceiling`},{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:`ceiling`},{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:{gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Aa}) .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:`{{ if and .settings.age (gt .git.timeSinceCommit 0) }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:TS(`.`),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 .)) }}`}},EA=new Set([TA.globals.palette,...Object.values(TA.segments).map(e=>e.palette)].filter(e=>e!==void 0)),DA=Hc(pE(`<default>`,JSON.stringify(TA),EA),TA),OA=j_(DA.presets);function kA(e){return OA.includes(e)}function AA(e){if(!e)return 0;try{return o(e).mtimeMs}catch{return 0}}const jA=new class{slots;head=null;tail=null;constructor(e){this.slots=e}async run(e){await this.acquire();try{return await e()}finally{this.release()}}async acquire(){if(this.slots>0){this.slots--;return}await new Promise(e=>{let t={wake:e,next:null};this.tail?this.tail.next=t:this.head=t,this.tail=t})}release(){let e=this.head;if(!e){this.slots++;return}this.head=e.next,this.head||(this.tail=null),e.wake()}}(8);function MA(e){return((...t)=>jA.run(()=>e(...t)))}const NA=MA(C),PA=MA(S),FA=MA(w);async function IA(e,t){return jA.run(async()=>{let n=null;try{n=await x(e,`r`);let{size:r,mtimeMs:i,ino:a}=await n.stat(),o=t!==void 0&&(a!==t.ino||r<t.offset),s=o||t===void 0?0:t.offset;if(s>=r)return J({buf:Buffer.alloc(0),start:s,size:r,mtimeMs:i,ino:a,reset:o});let c=Buffer.alloc(r-s),l=0;for(;l<c.length;){let{bytesRead:e}=await n.read(c,l,c.length-l,s+l);if(e===0)break;l+=e}return J({buf:l===c.length?c:c.subarray(0,l),start:s,size:r,mtimeMs:i,ino:a,reset:o})}catch(t){return t.code===`ENOENT`?Y:X(`readAppended ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{O(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}async function LA(e,t){return jA.run(async()=>{let n=null;try{n=await x(e,`r`);let{size:r}=await n.stat(),i=Math.max(0,r-t),a=Buffer.alloc(r-i),o=0;for(;o<a.length;){let{bytesRead:e}=await n.read(a,o,a.length-o,i+o);if(e===0)break;o+=e}return J({buf:o===a.length?a:a.subarray(0,o),fromStart:i===0})}catch(t){return t.code===`ENOENT`?Y:X(`readTail ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{O(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}const RA=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function zA(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}async function BA(e){let t=await VA(e);return t.kind===`ok`?J(Math.floor((t.value+36e5)/1e3)):t}async function VA(e){for(let t of[65536,1048576]){let n=await LA(e,t);if(n.kind!==`ok`)return n;let r=HA(n.value.buf,n.value.fromStart);if(r!=null)return J(r);if(n.value.fromStart)return Y}return Y}function HA(e,t){let n=e.toString(`utf8`).split(`
181
- `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!RA.test(t))continue;let r=zA(t);if(r!=null)return r}return null}function UA(e,t){return{...e,claudeConfigDir:pS(t.claudeConfigDir),env:t.mementoEnv}}const WA=c.join(`lib`,`ceiling_config.py`),GA=c.join(`skills`,`ceiling`,`bin`,`ceiling`);function KA(e,t){let n=typeof e==`object`&&e?e.plugins:void 0;if(typeof n!=`object`||!n)throw Error(`${t} has no "plugins" object`);return Object.entries(n).filter(([e])=>e.split(`@`)[0]===`memento`).flatMap(([e,n])=>{if(!Array.isArray(n))throw Error(`${t}: "${e}" is not a list of installs`);return n.map(n=>{let{scope:r,installPath:i,projectPath:a}=n??{};if(typeof r!=`string`||typeof i!=`string`)throw Error(`${t}: an install of "${e}" has no scope/path`);return typeof a==`string`?{key:e,scope:r,installPath:i,projectPath:a}:{key:e,scope:r,installPath:i}})})}function qA(e,t){let n=!0;for(let i of e){if(!r.existsSync(i))continue;let e;try{e=JSON.parse(r.readFileSync(i,`utf8`))?.enabledPlugins?.[t]}catch(e){return X(`memento lookup: ${i}: ${e.message}`)}typeof e==`boolean`&&(n=e)}return J(n)}function JA(e,t){if(!r.existsSync(e))return Y;let n;try{n=KA(JSON.parse(r.readFileSync(e,`utf8`)),e)}catch(e){return X(`memento lookup: ${e.message}`)}let i=n.find(e=>e.projectPath===t)??n.find(e=>e.scope===`user`);if(i===void 0)return Y;let a=qA([c.join(c.dirname(c.dirname(e)),`settings.json`),c.join(t,`.claude`,`settings.json`),c.join(t,`.claude`,`settings.local.json`)],i.key);if(a.kind!==`ok`)return a;if(!a.value)return Y;let o=[WA,GA].filter(e=>!r.existsSync(c.join(i.installPath,e)));return o.length===0?J(i.installPath):X(`memento at ${i.installPath} has no ${o.join(` or `)} — upgrade the plugin`)}function YA(e,t=process.env){let n=new Set([`CLAUDE_PROJECT_DIR`,`CLAUDE_CODE_SESSION_ID`,...e.env===void 0?[]:Ze]);return{...Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e))),...e.env,CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir||e.cwd}}function XA(e){return e.stderr.trim()||e.error||`${e.reason}${e.exitCode===null?``:` (exit ${e.exitCode})`}`}function ZA(e){let t;try{t=JSON.parse(e)}catch{return X(`memento read: not JSON: ${e.trim()}`)}let{ceiling:n,session:r}=t??{},i=n===`off`||typeof n==`number`&&n>=0?n:void 0;return i!==void 0&&(r===null||typeof r==`string`)?J({ceiling:i,session:r}):X(`memento read: unexpected answer: ${e.trim()}`)}async function QA(e,t){let n=await ke({bin:`python3`,args:[`-c`,`
175
+ Tip: every bar carries a settings menu — click it (${qc} by\n default) for quick actions, preset switching, edit mode, and clickable\n theme/style/variation/endcaps/wrap/padding controls.\n`}async function GO(e){let t=e.includes(`--force`),n=e.filter(e=>e!==`--force`),r=n.length>0?n:[...SO],i=LO();process.platform===`darwin`?zO(i.distPath):process.stdout.write(`Skipping URL handler (cmd-click verbs are macOS-only).
176
+ `),KO(i.binPath,r,t),process.stdout.write(WO());let a=bO(_O,yO(HE,await vO(_O,fetch,`https://registry.npmjs.org`)));process[a.stream].write(a.text)}function KO(e,t,n,i){let a=i??gS(hS(mS(process.env,process.cwd())));r.mkdirSync(c.dirname(a),{recursive:!0});let o={};if(r.existsSync(a))try{o=JSON.parse(r.readFileSync(a,`utf-8`))}catch(e){throw Error(`Could not parse ${a}: ${e instanceof Error?e.message:String(e)}`)}let s=o.statusLine?.command,l=[e,fO(e),dO(e)],u=typeof s==`string`&&(s.startsWith(`pnpm dlx @promptctl/cc-candybar@`)||l.some(e=>s===e||s.startsWith(`${e} `)));if(s&&!u&&!n){process.stderr.write(`Skipping settings.json update: existing statusLine.command appears customized.\n Current: ${s}\n To overwrite, re-run with --force.\n`);return}o.statusLine={type:`command`,command:wO(e,t)},Me(a,JSON.stringify(o,null,2)),process.stdout.write(`Updated ${a}\n`)}function qO(e,t){return e.kind===`owned`?t(e.pid,e.startTime)?{kind:`attach-and-exit`,reason:`live owner pid=${e.pid} holds the socket`}:{kind:`reclaim`,reason:`owner pid=${e.pid} is gone or recycled`}:e.kind===`absent`?{kind:`reclaim`,reason:`no lease — stale socket, no live owner`}:{kind:`reclaim`,reason:`unreadable lease (${e.detail}) — cannot prove a live owner`}}function JO(e){let t;try{t=r.readFileSync(e,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`absent`}:{kind:`unreadable`,detail:`read failed: ${e.message}`}}let n;try{n=JSON.parse(t)}catch(e){return{kind:`unreadable`,detail:`bad JSON: ${e.message}`}}let i=n,a=i?.pid;if(typeof a!=`number`||!Number.isInteger(a)||a<=0)return{kind:`unreadable`,detail:`no valid pid (got ${JSON.stringify(a)})`};let o=i?.startTime;return o!=null&&typeof o!=`string`?{kind:`unreadable`,detail:`invalid startTime (got ${JSON.stringify(o)})`}:{kind:`owned`,pid:a,startTime:o??null}}function YO(e,n){let i=`${e}.${t.pid}.tmp`;try{return r.writeFileSync(i,JSON.stringify(n),{mode:384}),r.renameSync(i,e),null}catch(e){let t=e.message;try{r.unlinkSync(i)}catch(e){if(e.code!==`ENOENT`)return`${t}; also failed to remove temp ${i}: ${e.message}`}return t}}function XO(e,t){let n=JO(e);if(n.kind===`owned`&&n.pid===t)try{r.unlinkSync(e)}catch{}}function ZO(e){try{let t=r.statSync(e);return{kind:`present`,identity:{dev:t.dev,ino:t.ino}}}catch(e){return e.code===`ENOENT`?{kind:`absent`}:{kind:`unreadable`,detail:e.message}}}function QO(e,t,n,r){let i=$O(e,t);return i===null?r.kind===`owned`?r.pid===n?{kind:`owned`}:{kind:`displaced`,reason:`lease reassigned (names pid=${r.pid}, we are pid=${n}) — a reclaimer overwrote it`}:{kind:`displaced`,reason:`lease not held (${r.kind}) — no longer the socket owner`}:{kind:`displaced`,reason:i}}function $O(e,t){return t.kind===`present`?t.identity.dev===e.dev&&t.identity.ino===e.ino?null:`socket replaced (bound dev=${e.dev} ino=${e.ino}, now dev=${t.identity.dev} ino=${t.identity.ino})`:t.kind===`absent`?`socket path gone (ENOENT) — unlinked by a reclaimer`:`socket path unreadable (${t.detail}) — cannot prove ownership`}function ek(e){let t=!1;function n(){let n=QO(e.bound,e.readIdentity(),e.myPid,e.readLease());return n.kind===`displaced`&&!t&&(t=!0,e.log(`warn`,`ownership self-check: ${n.reason}; shutting down`),e.shutdown(0)),n}function r(t=e.intervalMs??5e3){let r=setInterval(()=>{n().kind===`displaced`&&clearInterval(r)},t);return r.unref(),{disarm:()=>clearInterval(r)}}return{check:n,arm:r}}function tk(e,t=Ae){let n=t({bin:`ps`,args:[`-o`,`lstart=`,`-p`,String(e)],category:`process-fingerprint`,timeoutMs:2e3,env:{...process.env,LC_ALL:`C`,TZ:`UTC`}});if(n.ok){let e=n.stdout.trim();return e.length>0?{kind:`start`,token:e}:{kind:`unavailable`,detail:`ps produced no start-time`}}return{kind:`unavailable`,detail:n.reason===`spawn-error`?n.error??`ps spawn failed`:`ps ${n.reason} (exit ${n.exitCode})`}}function nk(e,t,n){if(t===null)return n.pidAlive(e);let r=n.readStartTime(e);switch(r.kind){case`start`:return r.token===t;case`unavailable`:return n.pidAlive(e)}}function rk(e,t=tk){let n=t(e);return n.kind===`start`?n.token:null}const ik=`CC_CANDYBAR_PARENT_PID`;function ak(e){let t=e[ik];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${ik} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function ok(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor,n=setInterval(()=>{e.isAlive(t)||e.onOrphaned(`spawner pid ${t} gone`)},e.intervalMs??250);return n.unref(),{disarm:()=>clearInterval(n)}}function sk(e){try{return t.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function ck(){let e=Number(process.env.CC_CANDYBAR_DAEMON_CEILING??``);return Number.isInteger(e)&&e>0?e:16}function lk(e,t,n){return e?t>=n?{allow:!1,reason:`${t} live isolated daemons registered >= ceiling ${n}`}:{allow:!0,reason:`${t} live isolated daemons registered < ceiling ${n}`}:{allow:!0,reason:`canonical production socket — exempt (bind() already caps it to one)`}}function uk(e){try{return r.readdirSync(e).filter(e=>e.endsWith(`.json`)).map(t=>c.join(e,t))}catch{return[]}}function dk(e){let t;try{t=r.readFileSync(e,`utf8`)}catch{return null}try{let e=JSON.parse(t),n=e?.pid;return typeof n!=`number`||!Number.isInteger(n)||n<=0?null:{pid:n,startTime:typeof e?.startTime==`string`?e.startTime:null}}catch{return null}}function fk(e,t,n){let r=0;for(let i of e)t(i.identity.pid,i.identity.startTime)?r++:n(i.path);return r}function pk(e){if(!e.isolated)return{decision:lk(!1,0,e.ceiling),registryPath:null};e.ensureDirSafe(e.registryDir);let t=[];for(let n of e.listFiles(e.registryDir)){let r=e.readEntry(n);r!==null&&r.pid!==e.pid&&t.push({path:n,identity:r})}let n=lk(!0,fk(t,e.isSameLiveProcess,e.removeFile),e.ceiling);if(!n.allow)return{decision:n,registryPath:null};let r=c.join(e.registryDir,`pid-${e.pid}.json`);return e.writeEntry(r,{pid:e.pid,startTime:e.startTime}),{decision:n,registryPath:r}}function mk(e,t,n,r){let i=n(e);if(i!==null&&i.pid===t)try{r(e)}catch{}}function hk(e,t={}){return{isolated:!!process.env.CC_CANDYBAR_SOCKET,registryDir:Ge(),ceiling:ck(),pid:process.pid,startTime:e,isSameLiveProcess:(e,t)=>nk(e,t,{readStartTime:tk,pidAlive:sk}),listFiles:uk,readEntry:dk,removeFile:e=>{try{r.unlinkSync(e)}catch{}},writeEntry:(e,t)=>{let n=`${e}.${t.pid}.tmp`;try{r.writeFileSync(n,JSON.stringify(t),{mode:384}),r.renameSync(n,e)}catch(e){try{r.unlinkSync(n)}catch(e){e.code}throw e}},ensureDirSafe:process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR?ze:e=>{ze(c.dirname(e)),ze(e)},...t}}function gk(e){return e<32||e===127||e>=128&&e<=159}function _k(e){let t=``;for(let n of e)t+=gk(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function vk(e,t){let n=_k(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const yk=`\x1B[38;2;255;255;255m`,bk=`\x1B[48;2;200;40;40m`;function xk(e){let t=/;2;(\d+);(\d+);(\d+)m$/.exec(e);if(t===null)throw Error(`diagnostic-style: not a 24-bit SGR: ${e}`);return`#`+t.slice(1,4).map(e=>Number(e).toString(16).padStart(2,`0`)).join(``)}const Sk={fg:xk(yk),bg:xk(bk)},Ck={fg:xk(`\x1B[38;2;0;0;0m`),bg:xk(`\x1B[48;2;220;160;40m`)},wk={unicode:Bi,ascii:{glyph:`>`,divider:`|`,lead:`<`,tail:`>`}},Tk={unicode:{},ascii:{left:`(`,right:`)`}};function Ek(e,t,n){switch(e){case`capsule`:return new Ki(Tk[t]);case`plain`:return new qi(n===void 0?{}:{separator:n});case`powerline`:return new Ui(wk[t]);default:return e}}const Dk=new Map;function Ok(e){let t=JSON.stringify([e.endcaps,e.charset,e.separator??null]),n=Dk.get(t);if(n!==void 0)return n;let r=Ek(e.endcaps,e.charset,e.separator),i=e=>new W(`x`,{end:``,overflow:`ignore`,style:new V({bgcolor:e})}),a=e=>new W(Xi(new Mi(e,r),{colorSystem:null}).replace(/\n$/,``)).cellLength,o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return Dk.set(t,s),s}function kk(e){return Ok(e).chrome}function Ak(e){return Ok(e).seam}function jk(e,t){if(e.length===0)return``;let n=Ek(t.endcaps,t.charset,t.separator),r=t.colorCompatibility,i=t.wrap&&Number.isFinite(t.width)?Xi(new na([...e],{joiner:n}),{width:t.width,colorSystem:r}):Xi(new Mi([...e],n),{colorSystem:r});if(!i.endsWith(`
177
+ `))throw Error(`renderStripCells: rich-js strip output did not end its last line`);return i.slice(0,-1)}function Mk(e){return Math.min(20,e??20)}const Nk={heading:`ERROR`,glyph:`⚠`,colors:Sk},Pk={heading:`WARNING`,glyph:`⚠`,colors:Ck},Fk={heading:`UPDATE`,glyph:`⬆`,colors:Ck};function Ik(e,t){return{text:_k(e),link:t}}function Lk(e,t,n){let[r,...i]=[Rk(e,Nk,LD),t,Rk(n,Pk,RD)].flat();return r===void 0?null:{channels:[r,...i]}}function Rk(e,t,n){let r=iO([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>Ik(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function zk(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
178
+ `)}function Bk(e,t,n,r){if(t===null)return e;let i=Vk(r),a=t.channels.flatMap(e=>Hk(e,i)),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[Uk(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
179
+ `);return e?`${l}\n${e}`:l}function Vk(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function Hk(e,t){let n=new V({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=Ht(Math.max(2,t.width-1)),i=(e,t)=>new W(`${e} `,{style:t,end:``,overflow:`ignore`});return e.lines.flatMap((a,o)=>jk([i(o===0?e.severity.glyph:` `,n.withLink(a[0].link)),...a.flatMap(e=>{let t=n.withLink(e.link);return e.text.split(` `).flatMap(e=>Kt(e,r)).map(e=>i(e,t))})],t).split(`
180
+ `))}function Uk(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new V({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new W(e,{style:t,end:``,overflow:`ignore`}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(E(a.path).href)):c(`full text unavailable: ${_k(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(_k(o),s.withLink(E(o).href))],d=[c(`↳ `,s),...l,...u.slice(0,-1)],f=d.reduce((e,t)=>e+t.cellLength,0),p=u.slice(-1).map(e=>e.truncate(Math.max(1,r.width-f),{mode:`middle`})),m=W.fromFragments([...d,...p]).truncate(r.width);return m.overflow=`ignore`,jk([m],r)}const Wk=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Gk(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function Kk(e,t){return r.readdirSync(t).filter(Wk).sort().flatMap(n=>{let i=c.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?Kk(e,i):[[c.relative(e,i).split(c.sep).join(`/`),Gk(i,a)]]})}function qk(e){let t=ae.createHash(`sha256`);for(let[n,r]of Kk(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const Jk=e=>e.slice(0,7);function Yk(e){return c.dirname(c.dirname(e))}function Xk(){return{version:HE,digest:`6aab4cafab526bc9a995f62e645d81659bf0635a4bb0863a9785933e26e205bc`}}function Zk(e){let t=JSON.parse(r.readFileSync(c.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${c.join(e,`package.json`)} has no version string`);return n}function Qk(e,t){try{let n=Yk(T(e)),i=c.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=qk(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:Zk(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var $=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};function $k(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function eA(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 tA(e,t,n){let r=Ms(e,new Set(n.map(js).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const nA=/^-?\d+$/;function rA(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 iA(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!nA.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 aA(e,t,n){return r=>r?nA.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 oA(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=>!nA.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 sA(e){return e===`config`?`set-config`:`set-state`}function cA(e,t,n){return t.kind===`int`?iA(`menu page "${e}"`):t.kind===`range`?aA(t.min,t.max,`${n} stepper "${e}"`):rA(t.allowed,`${n} "${e}"`,sA(n))}function lA(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:oA(e,n,t)}))}function uA(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 lA(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,cA(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 dA(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};uA(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=uA(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const fA=dA({},`config`,yA);function pA(e,t){return fA.register(e,t)}function mA(e){return fA.gateFor(e)}function hA(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:dx(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:[$k({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[$k({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:dx(e.insertSegmentFrom,t).members.map(t=>$k({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function gA(e,t){let n=Fl(e).get(t);return n===void 0?null:String(n)}function _A(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?Tx(n.persist):null;e?.scope===`preset-root`&&t.add(Cx(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function vA(e){let t=dw(e);return[..._A(e),...Object.values(e.actions).flatMap(e=>hA(e,t))]}function yA(e){return lA(vA(e),`config`)}const bA=pS(`commands.`),xA=ES(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),SA=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,CA=`{{ \$dir := .current_dir }}{{ if and (ne .home "") (or (eq .home .current_dir) (hasPrefix (printf "%s/" .home) .current_dir)) }}{{ \$dir = printf "~%s" (trimPrefix .home .current_dir) }}{{ else }}{{ if or (eq .project_dir .current_dir) (hasPrefix (printf "%s/" .project_dir) .current_dir) }}{{ $dir = ternary (${SA}) (basename .project_dir) (ne (${SA}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,wA=`{{ ${Rx} }}`,TA={min:0,max:100,step:5},EA={warnAt:{label:`warning at %`,domain:TA,default:50},errorAt:{label:`error at %`,domain:{...TA,atLeast:`warnAt`},default:80}};function DA(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:TA,default:80}}}const OA={globals:{palette:`tokyo-night`},variables:{...bA.variables,...Lb,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},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.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.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"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:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"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},"memento.ceiling":{kind:`input`,path:`memento.ceiling`,type:`number`,default:-1},"memento.off":{kind:`input`,path:`memento.off`,type:`boolean`,default:!1},"memento.session":{kind:`input`,path:`memento.session`,default:``},"memento.error":{kind:`input`,path:`memento.error`,default:``},"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 current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:CA},model:{group:`model-context`,description:`The active model's display name.`,template:`✱ {{ formatModelName .model.display_name }}`,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 eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}`,fg:wA,when:`{{ ne .git.branch "" }}`,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 ne .git.prUrl "" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (ne .git.prUrl "") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:nS(``).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:bA.template,when:bA.when},themeSwitcher:{group:`session-tools`,description:"`◀ <theme> ▶`: the theme the bar is wearing; ◀ and ▶ switch this session to the previous or next theme, wrapping at the ends.",template:`{{ carousel "stepTheme" 0 }}`},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:DA(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:DA(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:EA,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:EA,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) ${Aa} }}`,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 }}`},ceiling:{group:`model-context`,description:`The memento plugin's context ceiling for this session: − and + move it by 100K, ∞ lifts it, ↺ drops this session's own setting.`,template:`{{ if ne .memento.error "" }}⌈ ⚠ {{ .memento.error }} {{ action "ceiling.clear" "↺" }}{{ else }}⌈ {{ if .memento.off }}off{{ else }}{{ template "formatTokenCount" .memento.ceiling }} {{ action "ceiling.lower" "−" }} {{ action "ceiling.raise" "+" }} {{ action "ceiling.off" "∞" }}{{ end }}{{ if ne .memento.session "" }} {{ action "ceiling.clear" "↺" }}{{ end }}{{ end }}`,bg:`{{ if ne .memento.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .memento.ceiling 0) (ne .memento.error "") }}`},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:xA.template,bg:xA.bg,when:xA.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:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...nS(``).actions,...bA.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},"ceiling.raise":{ceiling:`set`,to:`+100_000`},"ceiling.lower":{ceiling:`set`,to:`-100_000`},"ceiling.off":{ceiling:`set`,to:`off`},"ceiling.clear":{ceiling:`clear`},...xA.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}},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:`ceiling`},{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:`ceiling`},{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:`ceiling`},{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:{gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Aa}) .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:`{{ if and .settings.age (gt .git.timeSinceCommit 0) }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:DS(`.`),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 .)) }}`}},kA=new Set([OA.globals.palette,...Object.values(OA.segments).map(e=>e.palette)].filter(e=>e!==void 0)),AA=Hc(gE(`<default>`,JSON.stringify(OA),kA),OA),jA=j_(AA.presets);function MA(e){return jA.includes(e)}function NA(e){if(!e)return 0;try{return o(e).mtimeMs}catch{return 0}}const PA=new class{slots;head=null;tail=null;constructor(e){this.slots=e}async run(e){await this.acquire();try{return await e()}finally{this.release()}}async acquire(){if(this.slots>0){this.slots--;return}await new Promise(e=>{let t={wake:e,next:null};this.tail?this.tail.next=t:this.head=t,this.tail=t})}release(){let e=this.head;if(!e){this.slots++;return}this.head=e.next,this.head||(this.tail=null),e.wake()}}(8);function FA(e){return((...t)=>PA.run(()=>e(...t)))}const IA=FA(C),LA=FA(S),RA=FA(w);async function zA(e,t){return PA.run(async()=>{let n=null;try{n=await x(e,`r`);let{size:r,mtimeMs:i,ino:a}=await n.stat(),o=t!==void 0&&(a!==t.ino||r<t.offset),s=o||t===void 0?0:t.offset;if(s>=r)return J({buf:Buffer.alloc(0),start:s,size:r,mtimeMs:i,ino:a,reset:o});let c=Buffer.alloc(r-s),l=0;for(;l<c.length;){let{bytesRead:e}=await n.read(c,l,c.length-l,s+l);if(e===0)break;l+=e}return J({buf:l===c.length?c:c.subarray(0,l),start:s,size:r,mtimeMs:i,ino:a,reset:o})}catch(t){return t.code===`ENOENT`?Y:X(`readAppended ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{O(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}async function BA(e,t){return PA.run(async()=>{let n=null;try{n=await x(e,`r`);let{size:r}=await n.stat(),i=Math.max(0,r-t),a=Buffer.alloc(r-i),o=0;for(;o<a.length;){let{bytesRead:e}=await n.read(a,o,a.length-o,i+o);if(e===0)break;o+=e}return J({buf:o===a.length?a:a.subarray(0,o),fromStart:i===0})}catch(t){return t.code===`ENOENT`?Y:X(`readTail ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{O(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}const VA=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function HA(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}async function UA(e){let t=await WA(e);return t.kind===`ok`?J(Math.floor((t.value+36e5)/1e3)):t}async function WA(e){for(let t of[65536,1048576]){let n=await BA(e,t);if(n.kind!==`ok`)return n;let r=GA(n.value.buf,n.value.fromStart);if(r!=null)return J(r);if(n.value.fromStart)return Y}return Y}function GA(e,t){let n=e.toString(`utf8`).split(`
181
+ `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!VA.test(t))continue;let r=HA(t);if(r!=null)return r}return null}function KA(e,t){return{...e,claudeConfigDir:hS(t.claudeConfigDir),env:t.mementoEnv}}const qA=c.join(`lib`,`ceiling_config.py`),JA=c.join(`skills`,`ceiling`,`bin`,`ceiling`);function YA(e,t){let n=typeof e==`object`&&e?e.plugins:void 0;if(typeof n!=`object`||!n)throw Error(`${t} has no "plugins" object`);return Object.entries(n).filter(([e])=>e.split(`@`)[0]===`memento`).flatMap(([e,n])=>{if(!Array.isArray(n))throw Error(`${t}: "${e}" is not a list of installs`);return n.map(n=>{let{scope:r,installPath:i,projectPath:a}=n??{};if(typeof r!=`string`||typeof i!=`string`)throw Error(`${t}: an install of "${e}" has no scope/path`);return typeof a==`string`?{key:e,scope:r,installPath:i,projectPath:a}:{key:e,scope:r,installPath:i}})})}function XA(e,t){let n=!0;for(let i of e){if(!r.existsSync(i))continue;let e;try{e=JSON.parse(r.readFileSync(i,`utf8`))?.enabledPlugins?.[t]}catch(e){return X(`memento lookup: ${i}: ${e.message}`)}typeof e==`boolean`&&(n=e)}return J(n)}function ZA(e,t){if(!r.existsSync(e))return Y;let n;try{n=YA(JSON.parse(r.readFileSync(e,`utf8`)),e)}catch(e){return X(`memento lookup: ${e.message}`)}let i=n.find(e=>e.projectPath===t)??n.find(e=>e.scope===`user`);if(i===void 0)return Y;let a=XA([c.join(c.dirname(c.dirname(e)),`settings.json`),c.join(t,`.claude`,`settings.json`),c.join(t,`.claude`,`settings.local.json`)],i.key);if(a.kind!==`ok`)return a;if(!a.value)return Y;let o=[qA,JA].filter(e=>!r.existsSync(c.join(i.installPath,e)));return o.length===0?J(i.installPath):X(`memento at ${i.installPath} has no ${o.join(` or `)} — upgrade the plugin`)}function QA(e,t=process.env){let n=new Set([`CLAUDE_PROJECT_DIR`,`CLAUDE_CODE_SESSION_ID`,...e.env===void 0?[]:Ze]);return{...Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e))),...e.env,CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir||e.cwd}}function $A(e){return e.stderr.trim()||e.error||`${e.reason}${e.exitCode===null?``:` (exit ${e.exitCode})`}`}function ej(e){let t;try{t=JSON.parse(e)}catch{return X(`memento read: not JSON: ${e.trim()}`)}let{ceiling:n,session:r}=t??{},i=n===`off`||typeof n==`number`&&n>=0?n:void 0;return i!==void 0&&(r===null||typeof r==`string`)?J({ceiling:i,session:r}):X(`memento read: unexpected answer: ${e.trim()}`)}async function tj(e,t){let n=await ke({bin:`python3`,args:[`-c`,`
182
182
  import json, math, sys
183
183
  sys.path.insert(0, sys.argv[1])
184
184
  from ceiling_config import CONFIG_NAME, anchored, ceiling_in, in_force, session_directory
@@ -187,40 +187,40 @@ ceiling = in_force(directory, anchored(sys.argv[3]))
187
187
  layer = ceiling_in(directory / CONFIG_NAME)
188
188
  print(json.dumps({"ceiling": "off" if ceiling == math.inf else ceiling,
189
189
  "session": layer.text if layer else None}))
190
- `,c.join(e,`lib`),t.sessionId,t.cwd],env:YA(t),timeoutMs:3e3,category:`memento.read`});return n.ok?ZA(n.stdout):X(XA(n))}function $A(e,t,n){let r=Ae({bin:c.join(e,GA),args:n.kind===`set`?[`set`,`session`,n.to]:[`clear`,`session`],env:YA(t),timeoutMs:5e3,category:`memento.move`});if(!r.ok)throw Error(XA(r))}function ej(){return{locate:e=>JA(hS(e.claudeConfigDir),e.projectDir),read:QA,move:$A}}function tj(e,t,n){let r=n===void 0?``:`CLAUDE_CONFIG_DIR=${lO(n)} `,i=e.added_dirs.map(e=>` --add-dir ${lO(e)}`).join(``);return`cd ${lO(e.project_dir)} && ${r}claude --resume ${lO(t)}${i}`}function nj(e,t,n){let r=M_(t(`preset`),e.globals.preset,e.presets),i=F_(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{};return{preset:r,presetCustomized:n(r),theme:rx(a.palette,t(`theme`),i.palette),style:fo(a.style,t(`style`),i.style,e.styles),endcaps:ho(a.endcaps,t(`endcaps`),i.endcaps),variation:So(a.variation,t(`variation`),i.variation),separator:a.default_separator??i.default_separator,autoWrap:Ao(a.autoWrap,t(`autoWrap`),i.autoWrap),padding:Mo(a.padding,t(`padding`),i.padding),charset:a.charset??i.charset??`unicode`,updateNotice:jo(a.updateNotice,t(`updateNotice`),i.updateNotice),colorCompatibility:a.colorCompatibility??i.colorCompatibility??`truecolor`}}function rj(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,charset:e.charset,width:t}}function ij(e){return{theme:e.theme,style:e.style,preset:e.preset,variation:e.variation}}function aj(e){return{preset:{effective:e.preset,customized:e.presetCustomized,bundled:kA(e.preset)},endcaps:{effective:e.endcaps},variation:{effective:e.variation},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding},updateNotice:{effective:e.updateNotice}}}const oj=10*1e3;function sj(e,t,n,r){let i=n-(t*1e3-r);if(i<3e5||e<=0)return;let a=e/i,o=(100-e)/a;return Math.max(0,Math.round(o/6e4))}function cj(e,t){if(!(t<60))return e*3600/t}function lj(e,t,n,r){let i=r-t;if(i<50||i>oj)return;let a=n-e;if(!(a<=0))return a*1e3/i}function uj(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=lj(t.input,t.atMs,n.input,n.atMs),i=lj(t.output,t.atMs,n.output,n.atMs),a=lj(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function dj(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>oj)continue;let o=lj(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function fj(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function pj(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>fj(m.hostname())),i=n(`user`,()=>m.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function mj(e,t){let n=new Map;for(let[t,r]of Object.entries(e.variables))n.set(t,r);for(let[t,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))n.set(`${t}.${e}`,i);let r=[],i=new Set,a=t=>xv(t,e.helpers).keys(),o=F_(e,t);for(let e of io){let t=o[e];if(ao(t))for(let e of a(t))r.push(e)}for(let n of Ps(P_(e,t).node)){if(n.when)for(let e of a(n.when))r.push(e);if(n.kind!==`segment`)continue;let t=e.segments[n.name];if(t){for(let e of[t.template,t.when,t.bg,t.fg])if(e)for(let t of a(e))r.push(t)}}let s=new Set;for(;r.length>0;){let e=r.pop();for(let t of gj(n,e)){if(i.has(t))continue;i.add(t);let e=n.get(t);if(e){if(e.kind===`input`)s.add(e.path);else if(e.kind===`template`)for(let t of a(e.template))r.push(t)}}}return s}function hj(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=mj(e,n);return t.set(n,i),i}}function gj(e,t){let n=t;for(;n.length>0;){if(e.has(n))return[n];let t=n.lastIndexOf(`.`);if(t<0)break;n=n.slice(0,t)}let r=`${t}.`,i=[];for(let t of e.keys())t.startsWith(r)&&i.push(t);return i}function _j(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function vj(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...t(`git.upstream`)&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.timeSinceCommit`)&&{showTimeSinceCommit:!0},...(t(`git.prNumber`)||t(`git.prState`)||t(`git.prUrl`)||t(`git.prError`))&&{showPullRequest:!0}}}async function yj(e,t,n,r,i,a,{configPath:o,...s}){let c=e=>_j(r,e),l=(t.clock??(()=>new Date))().getTime(),u=a.tmux??null,d=(e,t,n)=>t?n().catch(t=>X(`${e}: ${String(t)}`)):Promise.resolve(Y),[f,p,m,h,g,_,v,y,b,x,S]=await Promise.all([d(`git`,c(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,vj(r),e.workspace?.project_dir)),d(`session`,c(`session.cost`)||c(`session.tokens`)||c(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),d(`today`,c(`today`),()=>t.usageStore.getTodayInfo(e,a.claudeConfigDir)),d(`context`,c(`context`)||c(`autocompact`),()=>t.contextProvider.getContextInfo(e)),d(`metrics`,c(`metrics`)||c(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),d(`activity`,c(`activity`),()=>t.activityProvider.getActivityInfo(e.session_id,e)),d(`tmux`,c(`tmux.session`),()=>u===null?Promise.resolve(Y):t.tmuxService.getSessionName(u)),d(`cache`,c(`cache`),()=>BA(e.transcript_path)),d(`speed`,c(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,l)),d(`memento`,c(`memento`),()=>t.mementoProvider.getCeiling(UA({sessionId:e.session_id,projectDir:e.workspace?.project_dir??``,cwd:n??e.workspace?.current_dir??``},a))),d(`autocompact`,c(`autocompact`),()=>Promise.resolve(t.autoCompact(mS(pS(a.claudeConfigDir)))))]),C=[],w=e=>{if(e.kind===`failed`){C.push(e.reason);return}return e.kind===`ok`?e.value:void 0},ee=Dj(f);C.push(...ee.failures);let te=pj(a);C.push(...te.failures);let ne=w(p),re=w(m),ie=w(h),T=w(g),E=w(_),ae=w(v),oe=w(y),se=Sj(x);x.kind===`failed`&&C.push(`memento: ${x.reason}`);let ce=bj(S,ie?.maxTokens);S.kind===`failed`&&C.push(`autocompact: ${S.reason}`);for(let e of C)t.log(`warn`,`provider fetch failed: ${e}`);let D=e.rate_limits?.five_hour,le=e.rate_limits?.seven_day,ue=D?sj(D.used_percentage,D.resets_at,18e6,l):void 0,de=le?sj(le.used_percentage,le.resets_at,6048e5,l):void 0,fe=ne?.session.cost,pe=T?.sessionDuration,me=c(`burn`)&&fe!=null&&pe!=null?cj(fe,pe):void 0,he=w(b),ge=he===void 0?void 0:uj(he),_e=he===void 0?void 0:dj(he),ve=ge!==void 0||_e!==void 0?{...ge,..._e!==void 0&&{history:_e}}:void 0,O=Ej(process.env.HOME??process.env.USERPROFILE),ye=e.workspace?{...e.workspace,current_dir:Ej(e.workspace.current_dir)??``,project_dir:Ej(e.workspace.project_dir)??``,added_dirs:(e.workspace.added_dirs??[]).map(e=>Ej(e)??e)}:e.workspace,be=ne===void 0?void 0:Tj({cost:ne.session.cost,tokens:ne.session.tokens}),xe=re===void 0?void 0:{cost:re.cost,tokens:re.tokens},Se=T===void 0?void 0:Tj({lastResponseTime:T.lastResponseTime,responseTime:T.responseTime,sessionDuration:T.sessionDuration,messageCount:T.messageCount,linesAdded:T.linesAdded,linesRemoved:T.linesRemoved}),Ce=E===void 0?void 0:Cj(E);return{...e,...ye!==void 0&&{workspace:ye},...O!==void 0&&{home:O},...ee.git!==void 0&&{git:ee.git},...u!==null&&{tmux:{pane:u.pane,...ae!==void 0&&{session:ae}}},host:te.host,...aj(i),history:t.history(e.session_id),navigation:{back:t.navigation(e.session_id)},...s,...o!==null&&{configPath:o},resumeCommand:tj(ye,e.session_id,a.claudeConfigDir),...be!==void 0&&{session:be},...xe!==void 0&&{today:xe},...me!==void 0&&{burn:{costPerHour:me}},...ve!==void 0&&{speed:ve},...c(`block`)&&D!==void 0&&{block:{nativeUtilization:D.used_percentage,resetsAt:D.resets_at,...ue!==void 0&&{etaMinutes:ue}}},...le!==void 0&&{weekly:{percentage:le.used_percentage,resetsAt:le.resets_at,...de!==void 0&&{etaMinutes:de}}},...oe!==void 0&&{cache:{expiresAt:oe}},...ie!==void 0&&{context:{totalTokens:ie.totalTokens,contextLeft:ie.contextLeftPercentage}},...Se!==void 0&&{metrics:Se},...Ce!==void 0&&{activity:Ce},...se!==void 0&&{memento:se},...ce!==void 0&&{autocompact:ce}}}function bj(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return CS(e.value,t)}}const xj=e=>e.trim().split(`
191
- `).at(-1).trim();function Sj(e){switch(e.kind){case`absent`:return;case`failed`:return{error:xj(e.reason)};case`ok`:{let{ceiling:t,session:n}=e.value;return{ceiling:t===`off`?0:t,off:t===`off`,session:n??``}}}}function Cj(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=wj(e.running),i=wj(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 wj(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function Tj(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function Ej(e){return e===void 0||e.length===0||c.sep!==`\\`?e:e.replace(/\\/g,`/`)}function Dj(e){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let t=e.value,n=[],r=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){n.push(`git.${e}: ${t.reason}`);return}return t.value}},i=r(`aheadBehind`,t.aheadBehind),a=r(`sha`,t.sha),o=r(`operation`,t.operation),s=r(`timeSinceCommit`,t.timeSinceCommit),c=r(`stash`,t.stashCount),l=r(`upstream`,t.upstream),u=r(`repoName`,t.repoName),d=r(`repoUrl`,t.repoUrl),f=t.pullRequest,p={};return f?.kind===`ok`?(p.prNumber=f.value.number,p.prState=f.value.state,p.prUrl=f.value.url):f?.kind===`failed`&&(n.push(`git.pr: ${f.reason}`),p.prError=f.reason),{git:{branch:t.branch,status:t.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...t.workingTree!==void 0&&{staged:t.workingTree.staged,unstaged:t.workingTree.unstaged,untracked:t.workingTree.untracked,conflicts:t.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{timeSinceCommit:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{repoName:u},...d!==void 0&&{repoUrl:d},...p},failures:n}}const Oj={theme:e=>e.theme.kind===`decided`?e.theme.name:null,preset:e=>e.preset,style:e=>e.style.kind===`decided`?e.style.name:null,endcaps:e=>e.endcaps,variation:e=>e.variation,autoWrap:e=>e.autoWrap?Co:wo,padding:e=>String(e.padding),updateNotice:e=>e.updateNotice?Co:wo},kj=Object.entries(zb),Aj=new Set(Bb.map(e=>e.sessionKey)),jj=()=>!1;function Mj(e,t){return nj(e,e=>Aj.has(e)?t(e):null,jj)}function Nj(e,t,n,r){return e.flatMap(([e,i])=>{let a=Oj[e](t);return a===null||a===Oj[e](n(e))?[]:[{...i,value:a,target:r(i)}]})}function Pj(e,t,n){return Oj[n](Mj(e,t))}function Fj(e,t){let n=Mj(e,t),r=nj(e,()=>null,jj),i=nj(e,e=>e===zb.preset.sessionKey?n.preset:null,jj);return Nj(kj,n,e=>e===`preset`?r:i,t=>Ij(e,n.preset,t.configKey))}function Ij(e,t,n){return n in(N_(e.presets,t).globals??{})?Sx(t,n):n}function Lj(e,t,n){let r=M_(t(zb.preset.sessionKey),e.globals.preset,e.presets),i=Cx(n);return{key:i?.scope===`globals`?Ij(e,r,i.field):n,globals:F_(e,r)}}function Rj(e,t){let{preset:n}=Mj(e,t);return Vj(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:Ys(a,s);return c===void 0||Js(c)===Js(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function zj(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return j_(e.presets).flatMap(n=>{let i=Vj(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 Ks(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:Ys(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const Bj=new WeakMap;function Vj(e,t){let n=Bj.get(e)??new Map;Bj.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...Ps(P_(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Ws(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 Hj(e,t){let n=Mj(e,t),r=nj(e,e=>e===zb.preset.sessionKey?n.preset:null,jj);return{from:n.preset,globals:N_(e.presets,n.preset).globals??{},picks:Nj(kj.filter(([e])=>e!==`preset`),n,()=>r,e=>e.configKey),placements:Rj(e,t)}}function Uj(e){return{sessionKeys:Bb.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...Tl(e)?OA.map(t=>Sx(t,e)):[]]}}function Wj(e){return new Set(Bb.map(e=>e.configKey).filter(t=>Uj(t).fileKeys.some(t=>qj(e,Kj(t)))))}function Gj(e,t,n){let r=Fj(e,n),i=new Set(r.map(e=>e.configKey)),a=Gb(e=>i.has(zb[e].configKey)||t.has(zb[e].configKey));return{unsaved:r.length+Rj(e,n).length,resettable:a}}function Kj(e){let t=Cx(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return wx(t)}function qj(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&qj(e[n],r)}const Jj=$a(),Yj=new Set(Jj),Xj=new Set(po),Zj=e=>e?Yj.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${Jj.join(`, `)})`}:{ok:!1,reason:`theme name is required`},Qj=e=>e?Xj.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${po.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},$j=new Set([`1`,`true`]),eM=new Set([`0`,`false`]),tM={endcaps:Qj,theme:Zj,"toolbar-expanded":e=>$j.has(e)?{ok:!0,value:`1`}:eM.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},nM=cA(tM,`state`,lM);function rM(e,t){return nM.register(e,t)}function iM(e){return nM.gateFor(e)}function aM(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:dx(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 oM(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(tM,e.key))}function sM(e,t,n){let r=Kb.get(n);if(r!==void 0)return Pj(e,t,r);let i=Object.values(e.variables).find(e=>e.kind===`state`&&e.key===n);return i?.kind===`state`?i.default??null:null}function cM(e){let t=lx(e);return oM(Object.values(e.actions).flatMap(e=>aM(e,t)))}function lM(e){return oA(cM(e))}const uM=`update.dismissed`,dM=`updateNotice`,fM=zb.updateNotice.sessionKey;function pM(e){return e.kind===`source`?e.newer.digest:fO(e.newer)}const mM=e=>`${e.version} [${Gk(e.digest)}]`;function hM(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:mM(e.newer),running:mM(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:fO(e.newer),running:fO(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${mO}@${fO(e.newer)}`,`install`]}}}}const gM={kind:`idle`},_M={kind:`running`};function vM(e,t,n){if(e===null)return[];let r=pM(e);if(!n.enabled||n.dismissed===r)return[];let i=hM(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
192
- `),c=tO([{verb:FD,args:[s]}]),l=t.kind===`running`?Nk(`[${i.busy}]`,c):Nk(`[${i.act}]`,tO([{verb:qD,args:[n.sessionId]}]));return[{severity:Mk,message:s,lines:[[Nk(a,c),l,Nk(`[dismiss]`,tO([{verb:kD,args:[n.sessionId,uM,r]}])),Nk(`[disable]`,tO([{verb:ID,args:[n.sessionId,dM,`false`]},{verb:kD,args:[n.sessionId,fM,`false`]}]))],...o.map(e=>[Nk(e,c)])]}]}function yM(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function bM(e){switch(e.kind){case`current`:return[`info`,`build: current ${mM(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${mM(e.source)}, running ${mM(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function xM(e){switch(e.kind){case`current`:return[`info`,`release: current ${fO(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${fO(e.latest)}, running ${fO(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${fO(e.installed)}, latest ${fO(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function SM(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const CM=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function wM(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=CM(e.stderr)??e.error??CM(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function TM(){let e=[uA(dM,[`false`]),rM(fM,[`false`]),rM(uM,[])];return()=>e.forEach(e=>e())}function EM(e){let{entryUrl:t,intervalMs:n,releaseIntervalMs:r,registryUrl:i,fetchImpl:a,onApplied:o,log:s}=e,c={kind:`unchecked`,reason:`not sampled yet`},l=null,u=gM,d=null,f=SM(s),p=SM(s),m=()=>yM(c,l);function h(){let e=m(),t=e===null?null:pM(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:rM(uM,[t])})}function g(){c=Yk(t,qk),f(bM(c)),h()}async function _(){l=gO(zE,await hO(mO,a,i)),p(xM(l)),h()}return{arm(){TM(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>vM(m(),u,e),act(){let e=m();if(e===null)throw new $(`apply-update: nothing newer is known to apply`);let t=hM(e);if(u.kind===`running`)throw new $(`apply-update: already ${t.busy}`);u=_M,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),ke({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=gM,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=wM(n);u={kind:`failed`,identity:pM(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}var DM=class{static CACHE_DIR=Fe();static USAGE_CACHE_DIR=c.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=c.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=c.join(this.LOCKS_DIR,e);if(!r.existsSync(t))return!1;try{let n=r.readFileSync(t,`utf-8`),i=parseInt(n.trim(),10);if(isNaN(i))return O(`Invalid PID in lock file ${e}, removing stale lock`),r.unlinkSync(t),!1;try{return process.kill(i,0),!0}catch(n){return n.code===`ESRCH`?(O(`Removing stale lock file ${e} for dead process ${i}`),r.unlinkSync(t),!1):(O(`Error checking process ${i} for lock ${e}:`,n),!0)}}catch(t){return O(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=c.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await r.promises.writeFile(n,a,{flag:`wx`}),O(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await D(50);else throw e}return O(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=c.join(this.LOCKS_DIR,e);try{await r.promises.unlink(t),O(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&O(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([r.promises.mkdir(this.CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){O(`Failed to create cache directories:`,e)}}static createProjectHash(e){return oe(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=c.join(this.USAGE_CACHE_DIR,`${e}.json`),i=`${e}.usage.lock`;for(let a=0;a<3;a++){if(this.isLocked(i)){O(`Cache for ${e} is locked, waiting...`),await D(75);continue}try{let i=await r.promises.readFile(n,`utf-8`),a=JSON.parse(i);return!t||a.timestamp>=t?(O(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(a.data)):(O(`${e} cache outdated: cache=${a.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return O(`No shared ${e} usage cache found`),null;O(`Attempt ${a+1} failed to read ${e} cache: ${t.message}. Retrying...`),await D(75)}}return O(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let i=`${e}.usage.lock`;if(!await this.acquireLock(i)){O(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=c.join(this.USAGE_CACHE_DIR,`${e}.json`),a=JSON.stringify({data:t,timestamp:n||Date.now()});await r.promises.writeFile(i,a,`utf-8`),O(`[CACHE-SET] ${e} disk cache stored`)}catch(t){O(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(i)}}};const OM={"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 kM=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await DM.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await DM.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new re(this.GITHUB_PRICING_URL),n=ce({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){O(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let r=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){O(`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)?(O(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),O(`Pricing last updated: ${n?.updated||`unknown`}`),e(i)):(O(`Invalid pricing data structure`),e(null))}catch(t){O(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{O(`Response error:`,t),e(null)})});n.on(`error`,t=>{O(`Request error:`,t),e(null)}),n.on(`timeout`,()=>{O(`Request timeout`),n.destroy(),e(null)}),n.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return O(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return O(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,O(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),O(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,O(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(O(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(OM).length} models`),this.executionCache=OM,O(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(OM).length} models`),OM)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return O(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),O(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const AM=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function jM(e){if(typeof e==`string`)return AM.exec(e)?.[1]}function MM(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 NM(e){let t=e.message?.content,n=e.type===`user`,r=[],i=[],a,o;if(typeof t==`string`)o=t;else if(Array.isArray(t))for(let e of t){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=MM(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}case`text`:o??=t.text;break;default:break}}let s=n?jM(o):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&s===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...s!==void 0&&{command:s}}}function PM(e){if(e!==void 0)return[e];let t=h();return[f(t,`.config`,`claude`),f(t,`.claude`)].filter(e=>a(e))}async function FM(e){let t=[];for(let n of e){let e=f(n,`projects`);if(a(e))try{let n=await NA(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=f(e,r.name);t.push(n)}}catch(t){O(`Failed to read projects directory ${e}:`,t)}}return t}async function IM(e,t,n){let r=[],i=f(t,e,`subagents`);try{let t=(await NA(i)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let a of t){let t=f(i,a);if(n?.has(t)){r.push(t);continue}try{let n=(await PA(t,`utf-8`)).split(`
193
- `)[0];n&&JSON.parse(n).sessionId===e&&r.push(t)}catch{O(`Failed to check agent file ${t}`)}}}catch(e){O(`Failed to read subagents directory ${i}:`,e)}return r}function LM(e){let t=e.type||e.message?.role||e.message?.type,n=e.type===`user`&&e.message?.firstContentType===`tool_result`;return t===`user`&&!n}const RM=new Map;async function zM(e){try{let t=await FA(e),n=t.size,r=RM.get(e);if(r&&r.mtime===t.mtimeMs&&r.size===n)return O(`[parse-cache] hit ${e}`),RM.delete(e),RM.set(e,r),r.entries;let i;return n>1048576?(O(`Using streaming parser for large file ${e} (${Math.round(n/1024)}KB)`),i=await WM(e)):i=await HM(e),O(`Parsed ${i.length} entries from ${e}`),n>5242880?i:(RM.delete(e),RM.size>=16&&RM.delete(RM.keys().next().value),RM.set(e,{mtime:t.mtimeMs,size:n,entries:i}),i)}catch(t){if(t.code===`ENOENT`)return O(`Transcript not present yet: ${e}`),[];throw t}}function BM(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=t?.content,i=Array.isArray(r)&&typeof r[0]==`object`&&r[0]?r[0]:void 0;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,firstContentType:typeof i?.type==`string`?i.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,activity:NM(e),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 VM(e){let t=[];for(let n of e.split(`
194
- `))if(n.trim())try{let e=BM(JSON.parse(n));e&&t.push(e)}catch(e){O(`Failed to parse JSONL line: ${e}`);continue}return t}async function HM(e){return VM(await PA(e,`utf-8`))}async function UM(e,t){let n=await IA(e,t===void 0?void 0:{offset:t.offset,ino:t.ino});if(n.kind!==`ok`)return n;let{buf:r,start:i,mtimeMs:a,ino:o,reset:s}=n.value,c=r.lastIndexOf(10);return J(c<0?{entries:[],cursor:{offset:i,mtimeMs:a,ino:o},reset:s}:{entries:VM(r.subarray(0,c+1).toString(`utf-8`)),cursor:{offset:i+c+1,mtimeMs:a,ino:o},reset:s})}async function WM(e){return new Promise((t,n)=>{let r=[],a=i(e,{encoding:`utf8`}),o=le({input:a,crlfDelay:1/0});o.on(`line`,e=>{let t=e.trim();if(t)try{let e=BM(JSON.parse(t));e&&r.push(e)}catch(e){O(`Failed to parse JSONL line: ${e}`)}}),o.on(`close`,()=>{t(r)}),o.on(`error`,t=>{O(`Streaming parser error for ${e}:`,t),n(t)}),a.on(`error`,t=>{O(`File stream error for ${e}:`,t),n(t)})})}var GM=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}};function KM(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const qM=new Map,JM={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},YM={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function XM(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function ZM(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function QM(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}async function $M(e,t,n,r){let i=XM(new Date(ZM())),a=e&&!t?e:void 0,o=a?.entries??0,s=a?.cost??0,c=a?{...a.breakdown}:QM(),l=new Map;if(a)for(let[e,t]of a.days)e>=i&&l.set(e,{...t});for(let e of n){let t=e.message?.usage;if(!t)continue;o++;let n=e.costUSD??await kM.calculateCostForEntry(e.raw);s+=n,c.input+=t.input_tokens||0,c.output+=t.output_tokens||0,c.cacheCreation+=t.cache_creation_input_tokens||0,c.cacheRead+=t.cache_read_input_tokens||0;let r=XM(new Date(e.timestamp));if(r<i)continue;let a=l.get(r)??{...JM};a.cost+=n,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0,l.set(r,a)}return{cursor:r,entries:o,cost:s,breakdown:c,days:l}}function eN(e){let t=0,n=0,r=QM(),i=new Map;for(let 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)??{...JM};n.cost+=t.cost,n.input+=t.input,n.output+=t.output,n.cacheCreation+=t.cacheCreation,n.cacheRead+=t.cacheRead,i.set(e,n)}}if(t===0)return{sessionInfo:YM,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}async function tN(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))}var nN=class{entries=new Map;flight=new GM;seeded=new Map;seededDay=``;speedRings=new Map;speedFlight=new GM;maxEntries;staleAgeMs;log;hits=0;misses=0;sweeps=0;seeds=0;sweepTimer=null;constructor(e={}){this.log=e.logger??ib,this.maxEntries=e.maxEntries??256,this.staleAgeMs=e.staleAgeMs??864e5;let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,sweeps:this.sweeps,seeds:this.seeds}}async getUsageInfo(e,t){let n=await this.ingest(e,t?.transcript_path);if(n.kind===`failed`)return n;let r=n.kind===`ok`?n.value.sessionInfo:YM,i=t?.cost?.total_cost_usd??null;return J({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e,t){let n=XM(new Date),r=PM(t);try{await this.ensureSeeded(n,r)}catch(e){return X(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let i=await this.ingest(e?.session_id??``,e?.transcript_path);if(i.kind===`failed`)return i;let a=r.map(e=>f(e,`projects`)+p),o={...JM},s=!1;for(let[t,r]of this.entries){let i=r.transcriptPath??``,c=t===e?.session_id||a.some(e=>i.startsWith(e))?r.days:qM;s||=c.has(n);let l=c.get(n)??JM;o.cost+=l.cost,o.input+=l.input,o.output+=l.output,o.cacheCreation+=l.cacheCreation,o.cacheRead+=l.cacheRead}return s?J({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:n}):Y}async observeSpeed(e,t,n){let r=AA(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,r);if(i.kind===`failed`)return i;let a=KM(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),o=this.speedRings.get(e)??[],s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);return o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift(),this.speedRings.set(e,o),J({...s!==void 0&&{prev:s},cur:a,samples:[...o]})})}async ingest(e,t,n){if(!e)return Y;let r=n??AA(t),i=this.entries.get(e);if(i&&r!==0&&i.transcriptMtime===r)return i.lastSeenAt=Date.now(),this.entries.delete(e),this.entries.set(e,i),this.hits++,J(i);if(!t)return i?J(i):Y;this.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,()=>this.refold(e,t,this.entries.get(e)))}catch(t){return X(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}if(a.kind!==`ok`)return a;let o={files:a.value.files,sessionInfo:a.value.sessionInfo,days:a.value.days,transcriptMtime:a.value.mainMtime,transcriptPath:t,lastSeenAt:Date.now()};return this.entries.delete(e),this.entries.set(e,o),this.evictIfNeeded(),J(o)}async refold(e,t,n){let r=await IM(e,u(t),n===void 0?void 0:new Set(n.files.keys())),i=new Map,a=0;for(let e of[t,...r]){let r=n?.files.get(e),o=await UM(e,r?.cursor);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{entries:s,cursor:c,reset:l}=o.value;i.set(e,await $M(r,l,s,c)),e===t&&(a=c.mtimeMs)}return J({files:i,...eN(i),mainMtime:a})}ensureSeeded(e,t){this.seededDay!==e&&(this.seeded.clear(),this.seededDay=e);let n=t.join(`\0`),r=this.seeded.get(n);if(r)return r;let i=this.seed(t);return this.seeded.set(n,i),i.catch(()=>{this.seeded.get(n)===i&&this.seeded.delete(n)}),i}async seed(e){let t=ZM(),n=await FM(e),r=[];for(let e of n){let n;try{n=await NA(e)}catch{continue}for(let i of n){if(!i.endsWith(`.jsonl`))continue;let n=f(e,i),a;try{a=(await FA(n)).mtimeMs}catch{continue}a<t||r.push({sessionId:i.slice(0,-6),path:n,mtime:a})}}await tN(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,e.mtime);t.kind===`failed`&&this.log(`warn`,`usageStore seed: ${t.reason}`)}),this.seeds++,this.log(`info`,`usageStore seed sessions=${r.length} dirs=${e.join(`,`)}`)}sweepStale(){let e=Date.now(),t=0;for(let[n,r]of this.entries)e-r.lastSeenAt>this.staleAgeMs&&(this.entries.delete(n),this.speedRings.delete(n),t++);return t>0&&(this.sweeps++,this.log(`info`,`usageStore sweep dropped=${t}`)),t}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e),this.speedRings.delete(e),this.log(`info`,`usageStore evict ${e}`)}}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.entries.clear(),this.seeded.clear(),this.speedRings.clear()}},rN=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return O(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);O(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t){try{O(`Calculating context tokens from transcript: ${e}`);let n=await zM(e);if(n.length===0)return O(`No entries in transcript`),Y;let r=null;for(let e=n.length-1;e>=0;e--){let t=n[e];if(t&&t.message?.usage?.input_tokens&&t.isSidechain!==!0){r=t,O(`Context segment: Found most recent entry at ${t.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let e=r.message.usage,n=(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0);return O(`Most recent main chain context: ${n} tokens (limit: ${t})`),J({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return O(`No main chain entries with usage data found`),Y}catch(e){return X(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return J(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}},iN=class{states=new Map;constructor(e,t,n=256){this.empty=e,this.step=t,this.maxSessions=n}async read(e,t){let n=this.states.get(e),r=AA(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await UM(t,n?.cursor);if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:n?.value??this.empty};let{entries:a,cursor:o,reset:s}=i.value,c=s||n===void 0?this.empty:n.value;for(let e of a)c=this.step(c,e);for(this.touch(e,{cursor:o,value:c});this.states.size>this.maxSessions;){let e=this.states.keys().next().value;if(e===void 0)break;this.states.delete(e)}return{kind:`ok`,value:c}}touch(e,t){this.states.delete(e),this.states.set(e,t)}};const aN={messageCount:0,recent:[]};function oN(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +!!LM(t),recent:n.length>20?n.slice(-20):n}}function sN(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(LM(r))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 cN=class{fold=new iN(aN,oN);async getMetricsInfo(e,t){if(O(`Getting metrics from hook data for session: ${e}`),!t.cost)return Y;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?X(`metrics (${e}): ${n.reason}`):J({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:sN(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const lN={command:null,todos:[],pending:[],done:[]};function uN(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 dN(e,t){if(t.isSidechain)return e;let n=LM(t)?{...e,command:t.activity?.command??null,pending:[],done:[]}:e,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=uN(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 fN(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>uN(e,t.name),[]),done:e.done}}var pN=class{fold=new iN(lN,dN);async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?X(`activity (${e}): ${n.reason}`):J(fN(n.value))}};function mN(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function hN(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function gN(e,t,n,r){return hN(Ae(mN(e,t,n,r)),n)}async function _N(e,t,n){return hN(await ke(mN(e,t,n)),n)}const vN=e=>`${e.socket}\n${e.pane}`;var yN=class{names=new Map;asking=new GM;constructor(e=Date.now){this.now=e}getSessionName(e){let t=vN(e),n=this.names.get(t);if(n&&this.now()-n.at<3e4)return Promise.resolve(n.outcome);let r=this.asking.run(t,()=>this.ask(t,e));return n?Promise.resolve(n.outcome):r}async ask(e,t){O(`Getting tmux session name for pane ${t.pane} on ${t.socket}`);let n=await _N(t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]),r=n.kind===`ok`?n.stdout.trim():``,i=n.kind===`ok`?r?J(r):Y:X(n.reason);for(this.names.delete(e),this.names.set(e,{outcome:i,at:this.now()});this.names.size>64;)this.names.delete(this.names.keys().next().value);return i}};const bN=e=>JSON.stringify([e.sessionId,e.projectDir,e.cwd,e.claudeConfigDir,e.env===void 0?null:Ze.map(t=>e.env?.[t]??null)]);var xN=class{readings=new Map;inFlight=new Map;constructor(e,t=Date.now){this.edge=e,this.now=t}getCeiling(e){let t=bN(e),n=this.readings.get(t);if(n&&this.now()-n.at<1e4)return Promise.resolve(n.outcome);let r=this.inFlight.get(t)??this.fetch(t,e);return n?Promise.resolve(n.outcome):r}fetch(e,t){let n=this.edge.locate(t),r=(n.kind===`ok`?this.edge.read(n.value,t):Promise.resolve(n)).then(t=>{if(this.inFlight.get(e)!==r)return t;for(this.readings.delete(e),this.readings.set(e,{outcome:t,at:this.now()});this.readings.size>64;)this.readings.delete(this.readings.keys().next().value);return t}).finally(()=>{this.inFlight.get(e)===r&&this.inFlight.delete(e)});return this.inFlight.set(e,r),r}move(e,t){let n=this.edge.locate(e);if(n.kind!==`ok`)throw Error(n.kind===`failed`?n.reason:`memento is not installed or not enabled for this project`);let r=bN(e);try{this.edge.move(n.value,e,t)}finally{this.readings.delete(r),this.inFlight.delete(r),this.fetch(r,e)}}};function SN(e){return{gitProvider:new pb({watchers:e.watchers,logger:e.logger}),usageStore:new nN({logger:e.logger}),contextProvider:new rN,metricsProvider:new cN,activityProvider:new pN,tmuxService:new yN,mementoProvider:new xN(ej()),autoCompact:SS,log:e.logger}}function CN(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function wN(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function TN(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function EN({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function DN(e){let t=EN(e);if(t.length===1)return e.text;let n=wN(t);return n.style=e.text.style,n}function ON(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,lead:s=[],trail:c=[]}=t;if(e.length===0)return[];let l=wN(e,a).pad(o),u=new W(` `.repeat(o)),d={...s.length>0&&{lead:wN([u,...s],a)},...c.length>0&&{trail:wN([...c,u],a)}};if(n===`auto`)return[{text:l,...d}];let f={justify:r,truncate:i};return n===`fill`?[{text:l,fill:f,...d}]:(TN(l,n,f),[{text:l,...d}])}const kN=RegExp(`\\x1b\\[[0-9;]*m|${xi.source}`,`g`);function AN(e){return M(e.replace(kN,``))}function jN(e,t){let n=e.map(DN),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=Ok(n,t).split(`
195
- `);if(i.length>1)return n;let a=Math.max(0,t.width-AN(i[0]??``)),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:i},a)=>{let c=o+(a===r.length-1?s:0),{text:l}=e[t];TN(l,l.cellLength+c,i),n[t]=DN(e[t])}),n}function MN(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=NN(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(FN(a.style).link){i();let e=NN([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function NN(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>PN(e,t)):e,r=W.fromFragments(n);return r.end=``,r.overflow=`ignore`,n.length===1?r.style=n[0].style:t!==void 0&&!t.isNull&&(r.style=t),r}function PN(e,t){let n=e.copy();return n.style=t.add(FN(e.style)),n}function FN(e){return e instanceof V?e:V.parse(e)}function IN(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,LN(e,t,o,n,r,i));return i}function LN(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=dx(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,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=Ub.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=dx(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,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=dx(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:BN(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:BN(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)return n.doctor===`run`?{kind:`doctor-run`}:{kind:`doctor-fix`,check:n.check};if(`ceiling`in n)return{kind:`ceiling`,args:Ow(n)};if(`slash`in n)return{kind:`slash`,line:n.slash};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:BN(e,n.name,t)};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 RN(e){return e.kind===`do`?RN(e.head):e}function zN(e){switch(RN(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`doctor-run`:case`doctor-fix`:case`ceiling`:case`slash`:case`do`:return!1}}function BN(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function VN(e,t){return e.has(t)?Fv(e.read(t)):``}function HN(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function UN(e,t,n,r){let i=new W(e,{style:V.combine([r,new V({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function WN(e,t){return Math.max(e.members.indexOf(VN(t,e.stateVar)),0)}function GN(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=VN(r,e.stateVar);return{effects:[{verb:kD,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=VN(r,e.stateVar);return{effects:[{verb:kD,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=VN(r,e.stateVar);return{effects:[{verb:kD,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(WN(e,r)+1)%e.members.length];return{effects:[{verb:kD,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:AD,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:jD,args:[HN(e.text,Dy(r))]}],active:!1};case`open`:return{effects:[{verb:MD,args:[HN(e.target,Dy(r))]}],active:!1};case`persist-literal`:{let t=VN(r,e.stateVar);return{effects:[{verb:ID,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=VN(r,e.stateVar);return{effects:[{verb:ID,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(WN(e,r)+1)%e.members.length];return{effects:[{verb:ID,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:LD,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:VD,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:UD,args:[i]}],active:!1};case`redo`:return{effects:[{verb:WD,args:[i]}],active:!1};case`back`:return{effects:[{verb:GD,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:KD,args:[i]}],active:!1};case`save`:return{effects:[{verb:RD,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:zD,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:BD,args:[i,HN(e.name,Dy(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:JD,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:YD,args:[i,e.check]}],active:!1};case`ceiling`:return{effects:[{verb:ZD,args:[i,...e.args]}],active:!1};case`slash`:return{effects:[{verb:QD,args:[i,e.line]}],active:!1};case`layout-op`:return{effects:[{verb:HD,args:[i,e.key,Xk(e.op)]}],active:!1};case`do`:{let a=GN(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>GN(e,t,void 0,r,i).effects)],active:a.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:HD,args:[i,e.key,Xk(r)]}],active:!1}}}}function KN(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:Yc(`action "${e}"`,n,t.members.length,WN(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]}}function qN(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=n.store,{display:a,boundValue:o}=KN(e,RN(r),t,i),{effects:s,active:c}=GN(r,a,o,i,VN(i,`session.id`));return UN(a,tO(s),c)}function JN(e){return{action:{fn:(t,...n)=>qN(t,n,e),argTypes:[`string`,`string`],arity:{kind:`variadic`},returnType:`T`}}}function YN(e,t){return UN(`✕`,tO([{verb:kD,args:[VN(e,`session.id`),t,Kc]}]),!1)}function XN(e,t,n){return new V({bgcolor:L.fromRgba(t),color:L.fromRgba(ja(e,t,n))})}function ZN(e,t,n){return new V({color:L.fromRgba(cr(xa(e,`warning`),t,Aa,n))})}function QN(e,t,n){return V.combine([XN(e,t,n),ZN(e,t,n)])}function $N(e,t,n){return XN(e.palette,Wa(e.palette,e.disclosure,[t],n),n)}function eP(e,t,n,r,i,a){return r===void 0?n=>$N(e,{...n,distribution:t},i):(e,t)=>tP(r(t,n),a,i)}function tP(e,t,n){return new V({bgcolor:L.fromRgba(t),color:L.fromRgba(cr(xa(e,`primary`),t,4.5,n))})}function nP(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=>rP(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function rP(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function iP(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function aP(e){return{current:null,drawnAt:e}}function oP(e,t,n,r,i,a){let o={segName:t,placementId:n,palette:r,disclosure:i,tint:a,bg:void 0,drops:[]};return e.current=o,o}function sP(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function cP(e){return new W(e).cellLength}function lP(e){return Math.max(1,e.width-e.chromeCols-2*e.padding)}function uP(e){return Math.max(1,lP(e)-(cP(`✕`)+2*e.padding+e.seamCols))}function dP(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 fP(e,t,n){let r=cP(`←`)+1+cP(`→`)+1,i=dP(e,t,n);return(i.length>1?dP(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function pP(e,t){let n=[];for(let t of e)n.length>0&&n.push(new W(` `)),n.push(t);let r=W.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function mP(e,t,n,r){let i=e.compiled.get(t);if(!i||i.kind!==n)throw Error(`picker references action "${t}" which must be ${r}, got ${i?`a ${i.kind} action`:`no such action`}`);return i}function hP(e,t,n){let r=e.compiled.get(t),i=r&&RN(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 gP(e,t,n,r,i,a,o){let s=hP(i,e,`picker`),c=i.compiled.get(e),l=i.store,u=VN(l,`session.id`),d=`stateVar`in s?VN(l,s.stateVar):void 0,f=r?n.kind===`led`?uP(i):lP(i):1/0,p=n.kind===`led`?0:cP(`✕`)+1,m=s.library&&{groups:s.library.groups,entries:s.options.map(s.library.entry)},h=m===void 0?fP(s.options.map(cP),f,p):nP(m.entries,m.groups,r),g=parseInt(VN(l,t.stateVar),10),_=Number.isInteger(g)?Math.max(0,Math.min(g,h.length-1)):0,v=h[_]??[],y=e=>tO([{verb:kD,args:[u,t.key,String(e)]}]),b=n.kind===`led`?[]:[{verb:kD,args:[u,...n.writes.flatMap(([e,t])=>[e,t])]}],x=n.kind===`own`&&n.onPick?b:[],S=e=>tO([...GN(c,e,e,l,u).effects,...x]),C=(e,t)=>{let n=s.options[e];return UN(t,S(n),n===d,a({index:e,count:s.options.length},n))},w=n.kind===`led`?[]:[UN(`✕`,tO(b),!1,o)];_>0&&w.push(UN(`←`,y(_-1),!1));let ee=_<h.length-1?[UN(`→`,y(_+1),!1)]:[];if(m===void 0){let e=v.flatMap(e=>e.indices);return[pP([...w,...e.map(e=>C(e,s.options[e])),...ee],r)]}let te=new V({bold:!0}),ne=h.length>1?` ${_+1}/${h.length}`:``,re=v.length===1?[new W(`${v[0].label}${ne}`,{style:te})]:[],ie=[pP([...w,...re,...ee],r)];for(let e of v){v.length>1&&ie.push(pP([new W(e.label,{style:te})],r));let t=Math.max(...e.indices.map(e=>cP(s.options[e])));for(let n of e.indices){let e=s.options[n],i=m.entries[n].description,a=i===void 0?void 0:mk(i),o=` `.repeat(t-cP(e)+2),c=a===void 0?e:`${e}${o}${a}`;ie.push(pP([C(n,iP(c,f))],r))}}return ie}function _P(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{xy(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=mP(e,r,`set-int`,`an int action ({ set, int: true })`);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=hP(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=sP(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]=gP(n,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,eP(u,ma(void 0),e,l.paletteOf,t.drawnAt(),u.bg),ZN(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function vP(e,t,n,r,i){let a=Math.min(Math.floor((t-1)/2),i),o=n,s=0;for(;s<a;){let t=o+cP(e(-(s+1)))+1+cP(e(s+1))+1;if(t>r)break;o=t,s+=1}return s}function yP(e,t,n,r,i,a){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 o=n.store;if(!o.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 s=n.compiled.get(e),c=VN(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return pP([],!0);let d=VN(o,t.stateVar),f=Math.max(l.indexOf(d),0),p=e=>((f+e)%u+u)%u,m=e=>l[p(e)],h=new Map,g=e=>{let t=h.get(e);if(t!==void 0)return t;let n=tO(GN(s,m(e),m(e),o,c).effects);return h.set(e,n),n},_=e=>UN(m(e),g(e),m(e)===d,r({index:p(e),count:u},m(e))),v=a===void 0?_(0):UN(m(0),tO(GN(n.compiled.get(a),m(0),void 0,o,c).effects),!1),y=vP(m,u,cP(`◀`)+1+v.cellLength+1+cP(`▶`),uP(n),i),b=e=>Array.from({length:y},(t,n)=>_(e*(n+1)));return pP([...b(-1).reverse(),UN(`◀`,g(-1),!1),v,UN(`▶`,g(1),!1),...b(1)],!0)}function bP(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(xy(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&zN(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=hP(e,n,`carousel`),l=sP(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return yP(n,c,e,eP(l,ma(void 0),e,c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}const xP=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function SP(e,t,n){let r=La(e,{hue:sa,depth:0},n);return[ca(t.hues).map((t,n)=>({text:xP[n%xP.length],colour:Sa(e,t)})),[{text:`▾ open`,colour:r.state},{text:`menu`,colour:r.plane}],[{text:`warn`,colour:xa(e,`warning`)},{text:`error`,colour:xa(e,`error`)}]]}function CP(e,t,n,r){let i=SP(e,t,n).flatMap((t,r)=>t.map(({text:t,colour:i},a)=>({gap:r>0&&a===0?` `:``,cell:new W(` ${t} `,{style:XN(e,i,n)})}))),a=[],o=0;for(let{gap:e,cell:t}of i){if(o+=e.length+t.cellLength,o>r)break;e!==``&&a.push(new W(e)),a.push(t)}let s=W.fromFragments(a);return s.overflow=`ignore`,s.end=``,s}function wP(e,t){return{themePreview:{fn:()=>CP(e.palette,e.variation,t.drawnAt(),uP(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}const TP=e=>e.slice(e.lastIndexOf(`.`)+1),EP=(e,t)=>{let n=new W(TP(e));return n.truncate(t,{marker:`…`}),n.plain};function DP(e,t){let n=e.map(e=>e.map(({name:e})=>cP(TP(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 OP(e,t,n,r){let i=DP(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new W(` ${EP(s,i)} `,{style:XN(l,Ja(l,{kind:`bar`,variation:t,address:c},n).tint,n)});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
196
- `),...e]));return o.overflow=`ignore`,o.end=``,o}function kP(e,t){return{layoutPreview:{fn:()=>OP(e.layout(),e.variation,t.drawnAt(),uP(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function AP(e,t,n,r){let i=sP(r.activeSegment,`{{ menu }}`),a=r.action,o=x_(i.placementId,e,n.key),s=w_(o),c=b_(e),l=VN(a.store,o)===c,u=VN(a.store,`session.id`),d=l?Kc:c,f=UN(Yc(`{{ menu "${e}" }}`,t,2,+!!l),tO([{verb:kD,args:[u,o,d,s,`0`]}]),!1);return i.drops.push(...l?(()=>{let t=r.activeSegment.drawnAt(),c=La(i.palette,i.disclosure,t).plane;return gP(e,{key:s,stateVar:s},{kind:`own`,writes:[[o,Kc],[s,`0`]],onPick:n.closeOnPick},n.paged,a,eP(i,n.distribution,a,hP(a,e,`menu`).paletteOf,t,c),ZN(i.palette,c,t))})():[]),f}const jP=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function MP(e,t){let n=t[t.length-1],r=jP(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:O_(r??{})}}function NP(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=MP(t,n);return AP(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function PP(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=FP(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 W(t?i:a,{style:l===void 0?void 0:new V({color:l})}))}let l=W.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function FP(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 IP(e){let t={fn:(()=>{let t=sP(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:(()=>sP(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r=sy(()=>sP(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),i={fn:((e,t,n,i,a,o,...s)=>{let c=o===void 0?void 0:[o,...LP(s)];return PP({value:e,max:t,width:n,filled:i,empty:a,colourAt:c===void 0?void 0:e=>String(r.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...r,bgOf:t,tint:n,gauge:i}}function LP(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function RP(e){let t=[],n=[];for(let r of e){if(!r.contains(`
190
+ `,c.join(e,`lib`),t.sessionId,t.cwd],env:QA(t),timeoutMs:3e3,category:`memento.read`});return n.ok?ej(n.stdout):X($A(n))}function nj(e,t,n){let r=Ae({bin:c.join(e,JA),args:n.kind===`set`?[`set`,`session`,n.to]:[`clear`,`session`],env:QA(t),timeoutMs:5e3,category:`memento.move`});if(!r.ok)throw Error($A(r))}function rj(){return{locate:e=>ZA(_S(e.claudeConfigDir),e.projectDir),read:tj,move:nj}}function ij(e,t,n){let r=n===void 0?``:`CLAUDE_CONFIG_DIR=${fO(n)} `,i=e.added_dirs.map(e=>` --add-dir ${fO(e)}`).join(``);return`cd ${fO(e.project_dir)} && ${r}claude --resume ${fO(t)}${i}`}function aj(e,t,n){let r=M_(t(`preset`),e.globals.preset,e.presets),i=F_(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{};return{preset:r,presetCustomized:n(r),theme:rx(a.palette,t(`theme`),i.palette),style:fo(a.style,t(`style`),i.style,e.styles),endcaps:ho(a.endcaps,t(`endcaps`),i.endcaps),variation:So(a.variation,t(`variation`),i.variation),separator:a.default_separator??i.default_separator,autoWrap:Ao(a.autoWrap,t(`autoWrap`),i.autoWrap),padding:Mo(a.padding,t(`padding`),i.padding),charset:a.charset??i.charset??`unicode`,updateNotice:jo(a.updateNotice,t(`updateNotice`),i.updateNotice),colorCompatibility:a.colorCompatibility??i.colorCompatibility??`truecolor`}}function oj(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,charset:e.charset,width:t}}function sj(e){return{theme:e.theme,style:e.style,preset:e.preset,variation:e.variation}}function cj(e){return{preset:{effective:e.preset,customized:e.presetCustomized,bundled:MA(e.preset)},endcaps:{effective:e.endcaps},variation:{effective:e.variation},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding},updateNotice:{effective:e.updateNotice}}}const lj=10*1e3;function uj(e,t,n,r){let i=n-(t*1e3-r);if(i<3e5||e<=0)return;let a=e/i,o=(100-e)/a;return Math.max(0,Math.round(o/6e4))}function dj(e,t){if(!(t<60))return e*3600/t}function fj(e,t,n,r){let i=r-t;if(i<50||i>lj)return;let a=n-e;if(!(a<=0))return a*1e3/i}function pj(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=fj(t.input,t.atMs,n.input,n.atMs),i=fj(t.output,t.atMs,n.output,n.atMs),a=fj(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function mj(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>lj)continue;let o=fj(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function hj(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function gj(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>hj(m.hostname())),i=n(`user`,()=>m.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function _j(e,t){let n=new Map;for(let[t,r]of Object.entries(e.variables))n.set(t,r);for(let[t,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))n.set(`${t}.${e}`,i);let r=[],i=new Set,a=t=>xv(t,e.helpers).keys(),o=F_(e,t);for(let e of io){let t=o[e];if(ao(t))for(let e of a(t))r.push(e)}for(let n of Ps(P_(e,t).node)){if(n.when)for(let e of a(n.when))r.push(e);if(n.kind!==`segment`)continue;let t=e.segments[n.name];if(t){for(let e of[t.template,t.when,t.bg,t.fg])if(e)for(let t of a(e))r.push(t)}}let s=new Set;for(;r.length>0;){let e=r.pop();for(let t of yj(n,e)){if(i.has(t))continue;i.add(t);let e=n.get(t);if(e){if(e.kind===`input`)s.add(e.path);else if(e.kind===`template`)for(let t of a(e.template))r.push(t)}}}return s}function vj(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=_j(e,n);return t.set(n,i),i}}function yj(e,t){let n=t;for(;n.length>0;){if(e.has(n))return[n];let t=n.lastIndexOf(`.`);if(t<0)break;n=n.slice(0,t)}let r=`${t}.`,i=[];for(let t of e.keys())t.startsWith(r)&&i.push(t);return i}function bj(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function xj(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...t(`git.upstream`)&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.timeSinceCommit`)&&{showTimeSinceCommit:!0},...(t(`git.prNumber`)||t(`git.prState`)||t(`git.prUrl`)||t(`git.prError`))&&{showPullRequest:!0}}}async function Sj(e,t,n,r,i,a,{configPath:o,...s}){let c=e=>bj(r,e),l=(t.clock??(()=>new Date))().getTime(),u=a.tmux??null,d=(e,t,n)=>t?n().catch(t=>X(`${e}: ${String(t)}`)):Promise.resolve(Y),[f,p,m,h,g,_,v,y,b,x,S]=await Promise.all([d(`git`,c(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,xj(r),e.workspace?.project_dir)),d(`session`,c(`session.cost`)||c(`session.tokens`)||c(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),d(`today`,c(`today`),()=>t.usageStore.getTodayInfo(e,a.claudeConfigDir)),d(`context`,c(`context`)||c(`autocompact`),()=>t.contextProvider.getContextInfo(e)),d(`metrics`,c(`metrics`)||c(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),d(`activity`,c(`activity`),()=>t.activityProvider.getActivityInfo(e.session_id,e)),d(`tmux`,c(`tmux.session`),()=>u===null?Promise.resolve(Y):t.tmuxService.getSessionName(u)),d(`cache`,c(`cache`),()=>UA(e.transcript_path)),d(`speed`,c(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,l)),d(`memento`,c(`memento`),()=>t.mementoProvider.getCeiling(KA({sessionId:e.session_id,projectDir:e.workspace?.project_dir??``,cwd:n??e.workspace?.current_dir??``},a))),d(`autocompact`,c(`autocompact`),()=>Promise.resolve(t.autoCompact(gS(hS(a.claudeConfigDir)))))]),C=[],w=e=>{if(e.kind===`failed`){C.push(e.reason);return}return e.kind===`ok`?e.value:void 0},ee=Aj(f);C.push(...ee.failures);let te=gj(a);C.push(...te.failures);let ne=w(p),re=w(m),ie=w(h),T=w(g),E=w(_),ae=w(v),oe=w(y),se=Tj(x);x.kind===`failed`&&C.push(`memento: ${x.reason}`);let ce=Cj(S,ie?.maxTokens);S.kind===`failed`&&C.push(`autocompact: ${S.reason}`);for(let e of C)t.log(`warn`,`provider fetch failed: ${e}`);let D=e.rate_limits?.five_hour,le=e.rate_limits?.seven_day,ue=D?uj(D.used_percentage,D.resets_at,18e6,l):void 0,de=le?uj(le.used_percentage,le.resets_at,6048e5,l):void 0,fe=ne?.session.cost,pe=T?.sessionDuration,me=c(`burn`)&&fe!=null&&pe!=null?dj(fe,pe):void 0,he=w(b),ge=he===void 0?void 0:pj(he),_e=he===void 0?void 0:mj(he),ve=ge!==void 0||_e!==void 0?{...ge,..._e!==void 0&&{history:_e}}:void 0,O=kj(process.env.HOME??process.env.USERPROFILE),ye=e.workspace?{...e.workspace,current_dir:kj(e.workspace.current_dir)??``,project_dir:kj(e.workspace.project_dir)??``,added_dirs:(e.workspace.added_dirs??[]).map(e=>kj(e)??e)}:e.workspace,be=ne===void 0?void 0:Oj({cost:ne.session.cost,tokens:ne.session.tokens}),xe=re===void 0?void 0:{cost:re.cost,tokens:re.tokens},Se=T===void 0?void 0:Oj({lastResponseTime:T.lastResponseTime,responseTime:T.responseTime,sessionDuration:T.sessionDuration,messageCount:T.messageCount,linesAdded:T.linesAdded,linesRemoved:T.linesRemoved}),Ce=E===void 0?void 0:Ej(E);return{...e,...ye!==void 0&&{workspace:ye},...O!==void 0&&{home:O},...ee.git!==void 0&&{git:ee.git},...u!==null&&{tmux:{pane:u.pane,...ae!==void 0&&{session:ae}}},host:te.host,...cj(i),history:t.history(e.session_id),navigation:{back:t.navigation(e.session_id)},...s,...o!==null&&{configPath:o},resumeCommand:ij(ye,e.session_id,a.claudeConfigDir),...be!==void 0&&{session:be},...xe!==void 0&&{today:xe},...me!==void 0&&{burn:{costPerHour:me}},...ve!==void 0&&{speed:ve},...c(`block`)&&D!==void 0&&{block:{nativeUtilization:D.used_percentage,resetsAt:D.resets_at,...ue!==void 0&&{etaMinutes:ue}}},...le!==void 0&&{weekly:{percentage:le.used_percentage,resetsAt:le.resets_at,...de!==void 0&&{etaMinutes:de}}},...oe!==void 0&&{cache:{expiresAt:oe}},...ie!==void 0&&{context:{totalTokens:ie.totalTokens,contextLeft:ie.contextLeftPercentage}},...Se!==void 0&&{metrics:Se},...Ce!==void 0&&{activity:Ce},...se!==void 0&&{memento:se},...ce!==void 0&&{autocompact:ce}}}function Cj(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return TS(e.value,t)}}const wj=e=>e.trim().split(`
191
+ `).at(-1).trim();function Tj(e){switch(e.kind){case`absent`:return;case`failed`:return{error:wj(e.reason)};case`ok`:{let{ceiling:t,session:n}=e.value;return{ceiling:t===`off`?0:t,off:t===`off`,session:n??``}}}}function Ej(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=Dj(e.running),i=Dj(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 Dj(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function Oj(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 kj(e){return e===void 0||e.length===0||c.sep!==`\\`?e:e.replace(/\\/g,`/`)}function Aj(e){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let t=e.value,n=[],r=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){n.push(`git.${e}: ${t.reason}`);return}return t.value}},i=r(`aheadBehind`,t.aheadBehind),a=r(`sha`,t.sha),o=r(`operation`,t.operation),s=r(`timeSinceCommit`,t.timeSinceCommit),c=r(`stash`,t.stashCount),l=r(`upstream`,t.upstream),u=r(`repoName`,t.repoName),d=r(`repoUrl`,t.repoUrl),f=t.pullRequest,p={};return f?.kind===`ok`?(p.prNumber=f.value.number,p.prState=f.value.state,p.prUrl=f.value.url):f?.kind===`failed`&&(n.push(`git.pr: ${f.reason}`),p.prError=f.reason),{git:{branch:t.branch,status:t.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...t.workingTree!==void 0&&{staged:t.workingTree.staged,unstaged:t.workingTree.unstaged,untracked:t.workingTree.untracked,conflicts:t.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{timeSinceCommit:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{repoName:u},...d!==void 0&&{repoUrl:d},...p},failures:n}}const jj={theme:e=>e.theme.kind===`decided`?e.theme.name:null,preset:e=>e.preset,style:e=>e.style.kind===`decided`?e.style.name:null,endcaps:e=>e.endcaps,variation:e=>e.variation,autoWrap:e=>e.autoWrap?Co:wo,padding:e=>String(e.padding),updateNotice:e=>e.updateNotice?Co:wo},Mj=Object.entries(zb),Nj=new Set(Bb.map(e=>e.sessionKey)),Pj=()=>!1;function Fj(e,t){return aj(e,e=>Nj.has(e)?t(e):null,Pj)}function Ij(e,t,n,r){return e.flatMap(([e,i])=>{let a=jj[e](t);return a===null||a===jj[e](n(e))?[]:[{...i,value:a,target:r(i)}]})}function Lj(e,t,n){return jj[n](Fj(e,t))}function Rj(e,t){let n=Fj(e,t),r=aj(e,()=>null,Pj),i=aj(e,e=>e===zb.preset.sessionKey?n.preset:null,Pj);return Ij(Mj,n,e=>e===`preset`?r:i,t=>zj(e,n.preset,t.configKey))}function zj(e,t,n){return n in(N_(e.presets,t).globals??{})?wx(t,n):n}function Bj(e,t,n){let r=M_(t(zb.preset.sessionKey),e.globals.preset,e.presets),i=Tx(n);return{key:i?.scope===`globals`?zj(e,r,i.field):n,globals:F_(e,r)}}function Vj(e,t){let{preset:n}=Fj(e,t);return Wj(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:Ys(a,s);return c===void 0||Js(c)===Js(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function Hj(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return j_(e.presets).flatMap(n=>{let i=Wj(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 Ks(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:Ys(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const Uj=new WeakMap;function Wj(e,t){let n=Uj.get(e)??new Map;Uj.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...Ps(P_(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Ws(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 Gj(e,t){let n=Fj(e,t),r=aj(e,e=>e===zb.preset.sessionKey?n.preset:null,Pj);return{from:n.preset,globals:N_(e.presets,n.preset).globals??{},picks:Ij(Mj.filter(([e])=>e!==`preset`),n,()=>r,e=>e.configKey),placements:Vj(e,t)}}function Kj(e){return{sessionKeys:Bb.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...Tl(e)?jA.map(t=>wx(t,e)):[]]}}function qj(e){return new Set(Bb.map(e=>e.configKey).filter(t=>Kj(t).fileKeys.some(t=>Xj(e,Yj(t)))))}function Jj(e,t,n){let r=Rj(e,n),i=new Set(r.map(e=>e.configKey)),a=Gb(e=>i.has(zb[e].configKey)||t.has(zb[e].configKey));return{unsaved:r.length+Vj(e,n).length,resettable:a}}function Yj(e){let t=Tx(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return Ex(t)}function Xj(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&Xj(e[n],r)}const Zj=$a(),Qj=new Set(Zj),$j=new Set(po),eM=e=>e?Qj.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${Zj.join(`, `)})`}:{ok:!1,reason:`theme name is required`},tM=e=>e?$j.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${po.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},nM=new Set([`1`,`true`]),rM=new Set([`0`,`false`]),iM={endcaps:tM,theme:eM,"toolbar-expanded":e=>nM.has(e)?{ok:!0,value:`1`}:rM.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},aM=dA(iM,`state`,fM);function oM(e,t){return aM.register(e,t)}function sM(e){return aM.gateFor(e)}function cM(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:dx(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 lM(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(iM,e.key))}function uM(e,t,n){let r=Kb.get(n);if(r!==void 0)return Lj(e,t,r);let i=Object.values(e.variables).find(e=>e.kind===`state`&&e.key===n);return i?.kind===`state`?i.default??null:null}function dM(e){let t=dw(e);return lM(Object.values(e.actions).flatMap(e=>cM(e,t)))}function fM(e){return lA(dM(e))}const pM=`update.dismissed`,mM=`updateNotice`,hM=zb.updateNotice.sessionKey;function gM(e){return e.kind===`source`?e.newer.digest:hO(e.newer)}const _M=e=>`${e.version} [${Jk(e.digest)}]`;function vM(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:_M(e.newer),running:_M(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:hO(e.newer),running:hO(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${_O}@${hO(e.newer)}`,`install`]}}}}const yM={kind:`idle`},bM={kind:`running`};function xM(e,t,n){if(e===null)return[];let r=gM(e);if(!n.enabled||n.dismissed===r)return[];let i=vM(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
192
+ `),c=iO([{verb:RD,args:[s]}]),l=t.kind===`running`?Ik(`[${i.busy}]`,c):Ik(`[${i.act}]`,iO([{verb:XD,args:[n.sessionId]}]));return[{severity:Fk,message:s,lines:[[Ik(a,c),l,Ik(`[dismiss]`,iO([{verb:MD,args:[n.sessionId,pM,r]}])),Ik(`[disable]`,iO([{verb:zD,args:[n.sessionId,mM,`false`]},{verb:MD,args:[n.sessionId,hM,`false`]}]))],...o.map(e=>[Ik(e,c)])]}]}function SM(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function CM(e){switch(e.kind){case`current`:return[`info`,`build: current ${_M(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${_M(e.source)}, running ${_M(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function wM(e){switch(e.kind){case`current`:return[`info`,`release: current ${hO(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${hO(e.latest)}, running ${hO(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${hO(e.installed)}, latest ${hO(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function TM(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const EM=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function DM(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=EM(e.stderr)??e.error??EM(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function OM(){let e=[pA(mM,[`false`]),oM(hM,[`false`]),oM(pM,[])];return()=>e.forEach(e=>e())}function kM(e){let{entryUrl:t,intervalMs:n,releaseIntervalMs:r,registryUrl:i,fetchImpl:a,onApplied:o,log:s}=e,c={kind:`unchecked`,reason:`not sampled yet`},l=null,u=yM,d=null,f=TM(s),p=TM(s),m=()=>SM(c,l);function h(){let e=m(),t=e===null?null:gM(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:oM(pM,[t])})}function g(){c=Qk(t,Xk),f(CM(c)),h()}async function _(){l=yO(HE,await vO(_O,a,i)),p(wM(l)),h()}return{arm(){OM(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>xM(m(),u,e),act(){let e=m();if(e===null)throw new $(`apply-update: nothing newer is known to apply`);let t=vM(e);if(u.kind===`running`)throw new $(`apply-update: already ${t.busy}`);u=bM,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),ke({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=yM,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=DM(n);u={kind:`failed`,identity:gM(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}var AM=class{static CACHE_DIR=Fe();static USAGE_CACHE_DIR=c.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=c.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=c.join(this.LOCKS_DIR,e);if(!r.existsSync(t))return!1;try{let n=r.readFileSync(t,`utf-8`),i=parseInt(n.trim(),10);if(isNaN(i))return O(`Invalid PID in lock file ${e}, removing stale lock`),r.unlinkSync(t),!1;try{return process.kill(i,0),!0}catch(n){return n.code===`ESRCH`?(O(`Removing stale lock file ${e} for dead process ${i}`),r.unlinkSync(t),!1):(O(`Error checking process ${i} for lock ${e}:`,n),!0)}}catch(t){return O(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=c.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await r.promises.writeFile(n,a,{flag:`wx`}),O(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await D(50);else throw e}return O(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=c.join(this.LOCKS_DIR,e);try{await r.promises.unlink(t),O(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&O(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([r.promises.mkdir(this.CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){O(`Failed to create cache directories:`,e)}}static createProjectHash(e){return oe(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=c.join(this.USAGE_CACHE_DIR,`${e}.json`),i=`${e}.usage.lock`;for(let a=0;a<3;a++){if(this.isLocked(i)){O(`Cache for ${e} is locked, waiting...`),await D(75);continue}try{let i=await r.promises.readFile(n,`utf-8`),a=JSON.parse(i);return!t||a.timestamp>=t?(O(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(a.data)):(O(`${e} cache outdated: cache=${a.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return O(`No shared ${e} usage cache found`),null;O(`Attempt ${a+1} failed to read ${e} cache: ${t.message}. Retrying...`),await D(75)}}return O(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let i=`${e}.usage.lock`;if(!await this.acquireLock(i)){O(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=c.join(this.USAGE_CACHE_DIR,`${e}.json`),a=JSON.stringify({data:t,timestamp:n||Date.now()});await r.promises.writeFile(i,a,`utf-8`),O(`[CACHE-SET] ${e} disk cache stored`)}catch(t){O(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(i)}}};const jM={"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 MM=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await AM.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await AM.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new re(this.GITHUB_PRICING_URL),n=ce({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){O(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let r=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){O(`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)?(O(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),O(`Pricing last updated: ${n?.updated||`unknown`}`),e(i)):(O(`Invalid pricing data structure`),e(null))}catch(t){O(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{O(`Response error:`,t),e(null)})});n.on(`error`,t=>{O(`Request error:`,t),e(null)}),n.on(`timeout`,()=>{O(`Request timeout`),n.destroy(),e(null)}),n.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return O(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return O(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,O(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),O(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,O(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(O(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(jM).length} models`),this.executionCache=jM,O(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(jM).length} models`),jM)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return O(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),O(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const NM=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function PM(e){if(typeof e==`string`)return NM.exec(e)?.[1]}function FM(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 IM(e){let t=e.message?.content,n=e.type===`user`,r=[],i=[],a,o;if(typeof t==`string`)o=t;else if(Array.isArray(t))for(let e of t){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=FM(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}case`text`:o??=t.text;break;default:break}}let s=n?PM(o):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&s===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...s!==void 0&&{command:s}}}function LM(e){if(e!==void 0)return[e];let t=h();return[f(t,`.config`,`claude`),f(t,`.claude`)].filter(e=>a(e))}async function RM(e){let t=[];for(let n of e){let e=f(n,`projects`);if(a(e))try{let n=await IA(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=f(e,r.name);t.push(n)}}catch(t){O(`Failed to read projects directory ${e}:`,t)}}return t}async function zM(e,t,n){let r=[],i=f(t,e,`subagents`);try{let t=(await IA(i)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let a of t){let t=f(i,a);if(n?.has(t)){r.push(t);continue}try{let n=(await LA(t,`utf-8`)).split(`
193
+ `)[0];n&&JSON.parse(n).sessionId===e&&r.push(t)}catch{O(`Failed to check agent file ${t}`)}}}catch(e){O(`Failed to read subagents directory ${i}:`,e)}return r}function BM(e){let t=e.type||e.message?.role||e.message?.type,n=e.type===`user`&&e.message?.firstContentType===`tool_result`;return t===`user`&&!n}const VM=new Map;async function HM(e){try{let t=await RA(e),n=t.size,r=VM.get(e);if(r&&r.mtime===t.mtimeMs&&r.size===n)return O(`[parse-cache] hit ${e}`),VM.delete(e),VM.set(e,r),r.entries;let i;return n>1048576?(O(`Using streaming parser for large file ${e} (${Math.round(n/1024)}KB)`),i=await qM(e)):i=await GM(e),O(`Parsed ${i.length} entries from ${e}`),n>5242880?i:(VM.delete(e),VM.size>=16&&VM.delete(VM.keys().next().value),VM.set(e,{mtime:t.mtimeMs,size:n,entries:i}),i)}catch(t){if(t.code===`ENOENT`)return O(`Transcript not present yet: ${e}`),[];throw t}}function UM(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=t?.content,i=Array.isArray(r)&&typeof r[0]==`object`&&r[0]?r[0]:void 0;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,firstContentType:typeof i?.type==`string`?i.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,activity:IM(e),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 WM(e){let t=[];for(let n of e.split(`
194
+ `))if(n.trim())try{let e=UM(JSON.parse(n));e&&t.push(e)}catch(e){O(`Failed to parse JSONL line: ${e}`);continue}return t}async function GM(e){return WM(await LA(e,`utf-8`))}async function KM(e,t){let n=await zA(e,t===void 0?void 0:{offset:t.offset,ino:t.ino});if(n.kind!==`ok`)return n;let{buf:r,start:i,mtimeMs:a,ino:o,reset:s}=n.value,c=r.lastIndexOf(10);return J(c<0?{entries:[],cursor:{offset:i,mtimeMs:a,ino:o},reset:s}:{entries:WM(r.subarray(0,c+1).toString(`utf-8`)),cursor:{offset:i+c+1,mtimeMs:a,ino:o},reset:s})}async function qM(e){return new Promise((t,n)=>{let r=[],a=i(e,{encoding:`utf8`}),o=le({input:a,crlfDelay:1/0});o.on(`line`,e=>{let t=e.trim();if(t)try{let e=UM(JSON.parse(t));e&&r.push(e)}catch(e){O(`Failed to parse JSONL line: ${e}`)}}),o.on(`close`,()=>{t(r)}),o.on(`error`,t=>{O(`Streaming parser error for ${e}:`,t),n(t)}),a.on(`error`,t=>{O(`File stream error for ${e}:`,t),n(t)})})}var JM=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}};function YM(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const XM=new Map,ZM={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},QM={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function $M(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function eN(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function tN(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}async function nN(e,t,n,r){let i=$M(new Date(eN())),a=e&&!t?e:void 0,o=a?.entries??0,s=a?.cost??0,c=a?{...a.breakdown}:tN(),l=new Map;if(a)for(let[e,t]of a.days)e>=i&&l.set(e,{...t});for(let e of n){let t=e.message?.usage;if(!t)continue;o++;let n=e.costUSD??await MM.calculateCostForEntry(e.raw);s+=n,c.input+=t.input_tokens||0,c.output+=t.output_tokens||0,c.cacheCreation+=t.cache_creation_input_tokens||0,c.cacheRead+=t.cache_read_input_tokens||0;let r=$M(new Date(e.timestamp));if(r<i)continue;let a=l.get(r)??{...ZM};a.cost+=n,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0,l.set(r,a)}return{cursor:r,entries:o,cost:s,breakdown:c,days:l}}function rN(e){let t=0,n=0,r=tN(),i=new Map;for(let 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)??{...ZM};n.cost+=t.cost,n.input+=t.input,n.output+=t.output,n.cacheCreation+=t.cacheCreation,n.cacheRead+=t.cacheRead,i.set(e,n)}}if(t===0)return{sessionInfo:QM,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}async function iN(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))}var aN=class{entries=new Map;flight=new JM;seeded=new Map;seededDay=``;speedRings=new Map;speedFlight=new JM;maxEntries;staleAgeMs;log;hits=0;misses=0;sweeps=0;seeds=0;sweepTimer=null;constructor(e={}){this.log=e.logger??ib,this.maxEntries=e.maxEntries??256,this.staleAgeMs=e.staleAgeMs??864e5;let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,sweeps:this.sweeps,seeds:this.seeds}}async getUsageInfo(e,t){let n=await this.ingest(e,t?.transcript_path);if(n.kind===`failed`)return n;let r=n.kind===`ok`?n.value.sessionInfo:QM,i=t?.cost?.total_cost_usd??null;return J({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e,t){let n=$M(new Date),r=LM(t);try{await this.ensureSeeded(n,r)}catch(e){return X(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let i=await this.ingest(e?.session_id??``,e?.transcript_path);if(i.kind===`failed`)return i;let a=r.map(e=>f(e,`projects`)+p),o={...ZM},s=!1;for(let[t,r]of this.entries){let i=r.transcriptPath??``,c=t===e?.session_id||a.some(e=>i.startsWith(e))?r.days:XM;s||=c.has(n);let l=c.get(n)??ZM;o.cost+=l.cost,o.input+=l.input,o.output+=l.output,o.cacheCreation+=l.cacheCreation,o.cacheRead+=l.cacheRead}return s?J({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:n}):Y}async observeSpeed(e,t,n){let r=NA(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,r);if(i.kind===`failed`)return i;let a=YM(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),o=this.speedRings.get(e)??[],s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);return o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift(),this.speedRings.set(e,o),J({...s!==void 0&&{prev:s},cur:a,samples:[...o]})})}async ingest(e,t,n){if(!e)return Y;let r=n??NA(t),i=this.entries.get(e);if(i&&r!==0&&i.transcriptMtime===r)return i.lastSeenAt=Date.now(),this.entries.delete(e),this.entries.set(e,i),this.hits++,J(i);if(!t)return i?J(i):Y;this.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,()=>this.refold(e,t,this.entries.get(e)))}catch(t){return X(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}if(a.kind!==`ok`)return a;let o={files:a.value.files,sessionInfo:a.value.sessionInfo,days:a.value.days,transcriptMtime:a.value.mainMtime,transcriptPath:t,lastSeenAt:Date.now()};return this.entries.delete(e),this.entries.set(e,o),this.evictIfNeeded(),J(o)}async refold(e,t,n){let r=await zM(e,u(t),n===void 0?void 0:new Set(n.files.keys())),i=new Map,a=0;for(let e of[t,...r]){let r=n?.files.get(e),o=await KM(e,r?.cursor);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{entries:s,cursor:c,reset:l}=o.value;i.set(e,await nN(r,l,s,c)),e===t&&(a=c.mtimeMs)}return J({files:i,...rN(i),mainMtime:a})}ensureSeeded(e,t){this.seededDay!==e&&(this.seeded.clear(),this.seededDay=e);let n=t.join(`\0`),r=this.seeded.get(n);if(r)return r;let i=this.seed(t);return this.seeded.set(n,i),i.catch(()=>{this.seeded.get(n)===i&&this.seeded.delete(n)}),i}async seed(e){let t=eN(),n=await RM(e),r=[];for(let e of n){let n;try{n=await IA(e)}catch{continue}for(let i of n){if(!i.endsWith(`.jsonl`))continue;let n=f(e,i),a;try{a=(await RA(n)).mtimeMs}catch{continue}a<t||r.push({sessionId:i.slice(0,-6),path:n,mtime:a})}}await iN(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,e.mtime);t.kind===`failed`&&this.log(`warn`,`usageStore seed: ${t.reason}`)}),this.seeds++,this.log(`info`,`usageStore seed sessions=${r.length} dirs=${e.join(`,`)}`)}sweepStale(){let e=Date.now(),t=0;for(let[n,r]of this.entries)e-r.lastSeenAt>this.staleAgeMs&&(this.entries.delete(n),this.speedRings.delete(n),t++);return t>0&&(this.sweeps++,this.log(`info`,`usageStore sweep dropped=${t}`)),t}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e),this.speedRings.delete(e),this.log(`info`,`usageStore evict ${e}`)}}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.entries.clear(),this.seeded.clear(),this.speedRings.clear()}},oN=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return O(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);O(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t){try{O(`Calculating context tokens from transcript: ${e}`);let n=await HM(e);if(n.length===0)return O(`No entries in transcript`),Y;let r=null;for(let e=n.length-1;e>=0;e--){let t=n[e];if(t&&t.message?.usage?.input_tokens&&t.isSidechain!==!0){r=t,O(`Context segment: Found most recent entry at ${t.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let e=r.message.usage,n=(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0);return O(`Most recent main chain context: ${n} tokens (limit: ${t})`),J({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return O(`No main chain entries with usage data found`),Y}catch(e){return X(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return J(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}},sN=class{states=new Map;constructor(e,t,n=256){this.empty=e,this.step=t,this.maxSessions=n}async read(e,t){let n=this.states.get(e),r=NA(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await KM(t,n?.cursor);if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:n?.value??this.empty};let{entries:a,cursor:o,reset:s}=i.value,c=s||n===void 0?this.empty:n.value;for(let e of a)c=this.step(c,e);for(this.touch(e,{cursor:o,value:c});this.states.size>this.maxSessions;){let e=this.states.keys().next().value;if(e===void 0)break;this.states.delete(e)}return{kind:`ok`,value:c}}touch(e,t){this.states.delete(e),this.states.set(e,t)}};const cN={messageCount:0,recent:[]};function lN(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +!!BM(t),recent:n.length>20?n.slice(-20):n}}function uN(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(BM(r))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 dN=class{fold=new sN(cN,lN);async getMetricsInfo(e,t){if(O(`Getting metrics from hook data for session: ${e}`),!t.cost)return Y;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?X(`metrics (${e}): ${n.reason}`):J({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:uN(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const fN={command:null,todos:[],pending:[],done:[]};function pN(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 mN(e,t){if(t.isSidechain)return e;let n=BM(t)?{...e,command:t.activity?.command??null,pending:[],done:[]}:e,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=pN(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 hN(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>pN(e,t.name),[]),done:e.done}}var gN=class{fold=new sN(fN,mN);async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?X(`activity (${e}): ${n.reason}`):J(hN(n.value))}};function _N(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function vN(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function yN(e,t,n,r){return vN(Ae(_N(e,t,n,r)),n)}async function bN(e,t,n){return vN(await ke(_N(e,t,n)),n)}const xN=e=>`${e.socket}\n${e.pane}`;var SN=class{names=new Map;asking=new JM;constructor(e=Date.now){this.now=e}getSessionName(e){let t=xN(e),n=this.names.get(t);if(n&&this.now()-n.at<3e4)return Promise.resolve(n.outcome);let r=this.asking.run(t,()=>this.ask(t,e));return n?Promise.resolve(n.outcome):r}async ask(e,t){O(`Getting tmux session name for pane ${t.pane} on ${t.socket}`);let n=await bN(t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]),r=n.kind===`ok`?n.stdout.trim():``,i=n.kind===`ok`?r?J(r):Y:X(n.reason);for(this.names.delete(e),this.names.set(e,{outcome:i,at:this.now()});this.names.size>64;)this.names.delete(this.names.keys().next().value);return i}};const CN=e=>JSON.stringify([e.sessionId,e.projectDir,e.cwd,e.claudeConfigDir,e.env===void 0?null:Ze.map(t=>e.env?.[t]??null)]);var wN=class{readings=new Map;inFlight=new Map;constructor(e,t=Date.now){this.edge=e,this.now=t}getCeiling(e){let t=CN(e),n=this.readings.get(t);if(n&&this.now()-n.at<1e4)return Promise.resolve(n.outcome);let r=this.inFlight.get(t)??this.fetch(t,e);return n?Promise.resolve(n.outcome):r}fetch(e,t){let n=this.edge.locate(t),r=(n.kind===`ok`?this.edge.read(n.value,t):Promise.resolve(n)).then(t=>{if(this.inFlight.get(e)!==r)return t;for(this.readings.delete(e),this.readings.set(e,{outcome:t,at:this.now()});this.readings.size>64;)this.readings.delete(this.readings.keys().next().value);return t}).finally(()=>{this.inFlight.get(e)===r&&this.inFlight.delete(e)});return this.inFlight.set(e,r),r}move(e,t){let n=this.edge.locate(e);if(n.kind!==`ok`)throw Error(n.kind===`failed`?n.reason:`memento is not installed or not enabled for this project`);let r=CN(e);try{this.edge.move(n.value,e,t)}finally{this.readings.delete(r),this.inFlight.delete(r),this.fetch(r,e)}}};function TN(e){return{gitProvider:new pb({watchers:e.watchers,logger:e.logger}),usageStore:new aN({logger:e.logger}),contextProvider:new oN,metricsProvider:new dN,activityProvider:new gN,tmuxService:new SN,mementoProvider:new wN(rj()),autoCompact:wS,log:e.logger}}function EN(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function DN(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function ON(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function kN({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function AN(e){let t=kN(e);if(t.length===1)return e.text;let n=DN(t);return n.style=e.text.style,n}function jN(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,lead:s=[],trail:c=[]}=t;if(e.length===0)return[];let l=DN(e,a).pad(o),u=new W(` `.repeat(o)),d={...s.length>0&&{lead:DN([u,...s],a)},...c.length>0&&{trail:DN([...c,u],a)}};if(n===`auto`)return[{text:l,...d}];let f={justify:r,truncate:i};return n===`fill`?[{text:l,fill:f,...d}]:(ON(l,n,f),[{text:l,...d}])}const MN=RegExp(`\\x1b\\[[0-9;]*m|${xi.source}`,`g`);function NN(e){return M(e.replace(MN,``))}function PN(e,t){let n=e.map(AN),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=jk(n,t).split(`
195
+ `);if(i.length>1)return n;let a=Math.max(0,t.width-NN(i[0]??``)),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:i},a)=>{let c=o+(a===r.length-1?s:0),{text:l}=e[t];ON(l,l.cellLength+c,i),n[t]=AN(e[t])}),n}function FN(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=IN(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(RN(a.style).link){i();let e=IN([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function IN(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>LN(e,t)):e,r=W.fromFragments(n);return r.end=``,r.overflow=`ignore`,n.length===1?r.style=n[0].style:t!==void 0&&!t.isNull&&(r.style=t),r}function LN(e,t){let n=e.copy();return n.style=t.add(RN(e.style)),n}function RN(e){return e instanceof V?e:V.parse(e)}function zN(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,BN(e,t,o,n,r,i));return i}function BN(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=dx(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,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=Ub.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=dx(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,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=dx(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:UN(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:UN(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)return n.doctor===`run`?{kind:`doctor-run`}:{kind:`doctor-fix`,check:n.check};if(`ceiling`in n)return{kind:`ceiling`,args:jw(n)};if(`slash`in n)return{kind:`slash`,line:n.slash};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:UN(e,n.name,t)};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 VN(e){return e.kind===`do`?VN(e.head):e}function HN(e){switch(VN(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`doctor-run`:case`doctor-fix`:case`ceiling`:case`slash`:case`do`:return!1}}function UN(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function WN(e,t){return e.has(t)?Fv(e.read(t)):``}function GN(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function KN(e,t,n,r){let i=new W(e,{style:V.combine([r,new V({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function qN(e,t){return Math.max(e.members.indexOf(WN(t,e.stateVar)),0)}function JN(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=WN(r,e.stateVar);return{effects:[{verb:MD,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=WN(r,e.stateVar);return{effects:[{verb:MD,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=WN(r,e.stateVar);return{effects:[{verb:MD,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(qN(e,r)+1)%e.members.length];return{effects:[{verb:MD,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:ND,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:PD,args:[GN(e.text,Dy(r))]}],active:!1};case`open`:return{effects:[{verb:FD,args:[GN(e.target,Dy(r))]}],active:!1};case`persist-literal`:{let t=WN(r,e.stateVar);return{effects:[{verb:zD,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=WN(r,e.stateVar);return{effects:[{verb:zD,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(qN(e,r)+1)%e.members.length];return{effects:[{verb:zD,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:BD,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:WD,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:KD,args:[i]}],active:!1};case`redo`:return{effects:[{verb:qD,args:[i]}],active:!1};case`back`:return{effects:[{verb:JD,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:YD,args:[i]}],active:!1};case`save`:return{effects:[{verb:VD,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:HD,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:UD,args:[i,GN(e.name,Dy(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:ZD,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:QD,args:[i,e.check]}],active:!1};case`ceiling`:return{effects:[{verb:eO,args:[i,...e.args]}],active:!1};case`slash`:return{effects:[{verb:tO,args:[i,e.line]}],active:!1};case`layout-op`:return{effects:[{verb:GD,args:[i,e.key,$k(e.op)]}],active:!1};case`do`:{let a=JN(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>JN(e,t,void 0,r,i).effects)],active:a.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:GD,args:[i,e.key,$k(r)]}],active:!1}}}}function YN(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:Yc(`action "${e}"`,n,t.members.length,qN(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]}}function XN(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=n.store,{display:a,boundValue:o}=YN(e,VN(r),t,i),{effects:s,active:c}=JN(r,a,o,i,WN(i,`session.id`));return KN(a,iO(s),c)}function ZN(e){return{action:{fn:(t,...n)=>XN(t,n,e),argTypes:[`string`,`string`],arity:{kind:`variadic`},returnType:`T`}}}function QN(e,t){return KN(`✕`,iO([{verb:MD,args:[WN(e,`session.id`),t,Kc]}]),!1)}function $N(e,t,n){return new V({bgcolor:L.fromRgba(t),color:L.fromRgba(ja(e,t,n))})}function eP(e,t,n){return new V({color:L.fromRgba(cr(xa(e,`warning`),t,Aa,n))})}function tP(e,t,n){return V.combine([$N(e,t,n),eP(e,t,n)])}function nP(e,t,n){return $N(e.palette,Wa(e.palette,e.disclosure,[t],n),n)}function rP(e,t,n,r,i,a){return r===void 0?n=>nP(e,{...n,distribution:t},i):(e,t)=>iP(r(t,n),a,i)}function iP(e,t,n){return new V({bgcolor:L.fromRgba(t),color:L.fromRgba(cr(xa(e,`primary`),t,4.5,n))})}function aP(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=>oP(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function oP(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function sP(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function cP(e){return{current:null,drawnAt:e}}function lP(e,t,n,r,i,a){let o={segName:t,placementId:n,palette:r,disclosure:i,tint:a,bg:void 0,drops:[]};return e.current=o,o}function uP(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function dP(e){return new W(e).cellLength}function fP(e){return Math.max(1,e.width-e.chromeCols-2*e.padding)}function pP(e){return Math.max(1,fP(e)-(dP(`✕`)+2*e.padding+e.seamCols))}function mP(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 hP(e,t,n){let r=dP(`←`)+1+dP(`→`)+1,i=mP(e,t,n);return(i.length>1?mP(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function gP(e,t){let n=[];for(let t of e)n.length>0&&n.push(new W(` `)),n.push(t);let r=W.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function _P(e,t,n,r){let i=e.compiled.get(t);if(!i||i.kind!==n)throw Error(`picker references action "${t}" which must be ${r}, got ${i?`a ${i.kind} action`:`no such action`}`);return i}function vP(e,t,n){let r=e.compiled.get(t),i=r&&VN(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 yP(e,t,n,r,i,a,o){let s=vP(i,e,`picker`),c=i.compiled.get(e),l=i.store,u=WN(l,`session.id`),d=`stateVar`in s?WN(l,s.stateVar):void 0,f=r?n.kind===`led`?pP(i):fP(i):1/0,p=n.kind===`led`?0:dP(`✕`)+1,m=s.library&&{groups:s.library.groups,entries:s.options.map(s.library.entry)},h=m===void 0?hP(s.options.map(dP),f,p):aP(m.entries,m.groups,r),g=parseInt(WN(l,t.stateVar),10),_=Number.isInteger(g)?Math.max(0,Math.min(g,h.length-1)):0,v=h[_]??[],y=e=>iO([{verb:MD,args:[u,t.key,String(e)]}]),b=n.kind===`led`?[]:[{verb:MD,args:[u,...n.writes.flatMap(([e,t])=>[e,t])]}],x=n.kind===`own`&&n.onPick?b:[],S=e=>iO([...JN(c,e,e,l,u).effects,...x]),C=(e,t)=>{let n=s.options[e];return KN(t,S(n),n===d,a({index:e,count:s.options.length},n))},w=n.kind===`led`?[]:[KN(`✕`,iO(b),!1,o)];_>0&&w.push(KN(`←`,y(_-1),!1));let ee=_<h.length-1?[KN(`→`,y(_+1),!1)]:[];if(m===void 0){let e=v.flatMap(e=>e.indices);return[gP([...w,...e.map(e=>C(e,s.options[e])),...ee],r)]}let te=new V({bold:!0}),ne=h.length>1?` ${_+1}/${h.length}`:``,re=v.length===1?[new W(`${v[0].label}${ne}`,{style:te})]:[],ie=[gP([...w,...re,...ee],r)];for(let e of v){v.length>1&&ie.push(gP([new W(e.label,{style:te})],r));let t=Math.max(...e.indices.map(e=>dP(s.options[e])));for(let n of e.indices){let e=s.options[n],i=m.entries[n].description,a=i===void 0?void 0:_k(i),o=` `.repeat(t-dP(e)+2),c=a===void 0?e:`${e}${o}${a}`;ie.push(gP([C(n,sP(c,f))],r))}}return ie}function bP(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{xy(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=_P(e,r,`set-int`,`an int action ({ set, int: true })`);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=vP(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=uP(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]=yP(n,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,rP(u,ma(void 0),e,l.paletteOf,t.drawnAt(),u.bg),eP(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function xP(e,t,n,r,i){let a=Math.min(Math.floor((t-1)/2),i),o=n,s=0;for(;s<a;){let t=o+dP(e(-(s+1)))+1+dP(e(s+1))+1;if(t>r)break;o=t,s+=1}return s}function SP(e,t,n,r,i,a){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 o=n.store;if(!o.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 s=n.compiled.get(e),c=WN(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return gP([],!0);let d=WN(o,t.stateVar),f=Math.max(l.indexOf(d),0),p=e=>((f+e)%u+u)%u,m=e=>l[p(e)],h=new Map,g=e=>{let t=h.get(e);if(t!==void 0)return t;let n=iO(JN(s,m(e),m(e),o,c).effects);return h.set(e,n),n},_=e=>KN(m(e),g(e),m(e)===d,r({index:p(e),count:u},m(e))),v=a===void 0?_(0):KN(m(0),iO(JN(n.compiled.get(a),m(0),void 0,o,c).effects),!1),y=xP(m,u,dP(`◀`)+1+v.cellLength+1+dP(`▶`),pP(n),i),b=e=>Array.from({length:y},(t,n)=>_(e*(n+1)));return gP([...b(-1).reverse(),KN(`◀`,g(-1),!1),v,KN(`▶`,g(1),!1),...b(1)],!0)}function CP(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(xy(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&HN(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=vP(e,n,`carousel`),l=uP(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return SP(n,c,e,rP(l,ma(void 0),e,c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}const wP=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function TP(e,t,n){let r=La(e,{hue:sa,depth:0},n);return[ca(t.hues).map((t,n)=>({text:wP[n%wP.length],colour:Sa(e,t)})),[{text:`▾ open`,colour:r.state},{text:`menu`,colour:r.plane}],[{text:`warn`,colour:xa(e,`warning`)},{text:`error`,colour:xa(e,`error`)}]]}function EP(e,t,n,r){let i=TP(e,t,n).flatMap((t,r)=>t.map(({text:t,colour:i},a)=>({gap:r>0&&a===0?` `:``,cell:new W(` ${t} `,{style:$N(e,i,n)})}))),a=[],o=0;for(let{gap:e,cell:t}of i){if(o+=e.length+t.cellLength,o>r)break;e!==``&&a.push(new W(e)),a.push(t)}let s=W.fromFragments(a);return s.overflow=`ignore`,s.end=``,s}function DP(e,t){return{themePreview:{fn:()=>EP(e.palette,e.variation,t.drawnAt(),pP(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}const OP=e=>e.slice(e.lastIndexOf(`.`)+1),kP=(e,t)=>{let n=new W(OP(e));return n.truncate(t,{marker:`…`}),n.plain};function AP(e,t){let n=e.map(e=>e.map(({name:e})=>dP(OP(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 jP(e,t,n,r){let i=AP(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new W(` ${kP(s,i)} `,{style:$N(l,Ja(l,{kind:`bar`,variation:t,address:c},n).tint,n)});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
196
+ `),...e]));return o.overflow=`ignore`,o.end=``,o}function MP(e,t){return{layoutPreview:{fn:()=>jP(e.layout(),e.variation,t.drawnAt(),pP(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function NP(e,t,n,r){let i=uP(r.activeSegment,`{{ menu }}`),a=r.action,o=x_(i.placementId,e,n.key),s=w_(o),c=b_(e),l=WN(a.store,o)===c,u=WN(a.store,`session.id`),d=l?Kc:c,f=KN(Yc(`{{ menu "${e}" }}`,t,2,+!!l),iO([{verb:MD,args:[u,o,d,s,`0`]}]),!1);return i.drops.push(...l?(()=>{let t=r.activeSegment.drawnAt(),c=La(i.palette,i.disclosure,t).plane;return yP(e,{key:s,stateVar:s},{kind:`own`,writes:[[o,Kc],[s,`0`]],onPick:n.closeOnPick},n.paged,a,rP(i,n.distribution,a,vP(a,e,`menu`).paletteOf,t,c),eP(i.palette,c,t))})():[]),f}const PP=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function FP(e,t){let n=t[t.length-1],r=PP(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:O_(r??{})}}function IP(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=FP(t,n);return NP(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function LP(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=RP(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 W(t?i:a,{style:l===void 0?void 0:new V({color:l})}))}let l=W.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function RP(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 zP(e){let t={fn:(()=>{let t=uP(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:(()=>uP(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r=sy(()=>uP(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),i={fn:((e,t,n,i,a,o,...s)=>{let c=o===void 0?void 0:[o,...BP(s)];return LP({value:e,max:t,width:n,filled:i,empty:a,colourAt:c===void 0?void 0:e=>String(r.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...r,bgOf:t,tint:n,gauge:i}}function BP(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function VP(e){let t=[],n=[];for(let r of e){if(!r.contains(`
197
197
  `)){n.push(r);continue}let e=r.split(`
198
- `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function zP(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,...BP(e,r)]}function BP(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 VP(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:zP(e.direction,e.children.map((t,i)=>n(t,[...r,HP(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function HP(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:ks[e.direction]}}const UP={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:ma(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,Fs(t.path,n)))}},render(e,t){return zP(e.direction,e.children.map((n,r)=>t.renderChild(n,t.visible,HP(e,r))))}},WP={drop:e=>e.place,above:()=>`above`},GP={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},KP={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:As(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Qc(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Is(t.path)),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){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(!t.visible)return[];let a=ky(t.scope,e.settings);try{if(!CN(i.when,a))return[];let n=Qb(e.settings.theme,t.palette),o=e.opens!==void 0&&CN(e.opens.open,t.scope),{styles:s,fragments:c,lead:l,trail:u,drops:d,open:f}=t.evaluateSegment(e,a,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,lead:e.lead,trail:e.trail},o),p=f?s.trigger:s.closed,m={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:p,padding:t.padding},h=e.opens,g=h===void 0?[]:t.renderBody(h.body,o,s.disclosure).map(e=>({...e,place:WP[h.placement](e)})),_=RP(MN(c,p)).map((e,t)=>({cells:ON(e,{...m,lead:t===0?MN(l,p):[],trail:t===0?MN(u,p):[]}),band:`own`,place:`flow`})),v=d.map(e=>({cells:ON(MN([e],s.band),{...m,baseStyle:s.band}),band:`deeper`,place:`flow`})),y=(e,t,n)=>ON(MN([e],t),{...m,width:`auto`,baseStyle:t,padding:n}),b=g.findIndex(e=>e.band===`own`),{lead:x,stays:S}=h!==void 0&&b!==-1?GP[h.placement](_,()=>y(t.closeDisclosure(h.key),s.close,t.padding)):{lead:[],stays:_},C=x.flatMap(e=>y(new W(` `.repeat(EN(e).reduce((e,t)=>e+t.cellLength,0))),s.trigger,0)),w=(e,t)=>e.band===`own`?t===b?x:C:[],ee=g.map((e,t)=>({cells:[...w(e,t),...e.cells],band:`deeper`,place:e.place})),te=[...S,...v];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...te.flatMap(e=>e.cells),...g.flatMap(w)].flatMap(EN)),[...te,...ee]}catch(n){let r=n.message??String(n);t.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:ON([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,lead:qP(e.lead,e,a,t),trail:qP(e.trail,e,a,t)}),band:`own`,place:`flow`}]}}};function qP(e,t,n,r){if(e===void 0)return[];try{return r.evaluateSegment(t,n,r.palette,r.region,{bg:void 0,fg:void 0,body:e,lead:void 0,trail:void 0},!1).fragments}catch(e){return r.onSegmentError?.(t.id,e.message??String(e)),[]}}const JP={container:UP,segment:KP};function YP(e){return JP[e]}function XP(e){if(`ttl`in e)return{kind:`ttl`,durationMs:yb(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 ZP(e,t){switch(zs(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,regex:new RegExp(e.regex),default:t};case`text`:return{kind:`text`,default:t}}}function QP(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:XP(n.cache),parse:ZP(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:XP(n.cache),parse:ZP(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,ttlMs:n.cache?yb(n.cache.ttl):void 0,varDefault:n.default});break;case`git`:e.declareGit(t,{field:n.field,cwd:r,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function $P(e,t){let n=$d.EMPTY;for(let[r,i]of Object.entries(t))try{n=e.parse(`{{ define "${r}" }}${i}{{ end }}`,n).defines()}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}return n}const eF=e=>So(void 0,null,e.globals.variation);function tF(e,t,n){let r=n.cwd,i=ax(e.globals.palette),a={store:t.variableStore,compiled:new Map,chromeCols:Ek({endcaps:`powerline`,charset:_o}),width:80,basePalette:i,palette:i,variation:oa[eF(e)],padding:1,seamCols:Dk({endcaps:`powerline`,charset:_o}),layout:()=>[]},o=aP(t.drawnAt),s={action:a,activeSegment:o},c=Object.keys(e.styles),l=j_(e.presets),u=new Map([...lx(e),...uw(e)]),d=Ey({...JN(a),..._P(a,o),...bP(a,o),...wP(a,o),...kP(a,o),...NP(s),...IP(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},n.clock,t.drawnAt),f=$P(d,e.helpers),p=e=>d.parse(e,f),m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let n=p(e);return m.set(e,n),n},g=new Map;for(let[t,n]of Wb)n in e.variables&&g.set(t,n);for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&!g.has(n.key)&&g.set(n.key,t);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&!g.has(r.key)&&g.set(r.key,`${t}.${e}`);a.compiled=IN(p,e.actions,g,u);let _=[];for(let[n,i]of Object.entries(e.variables))try{QP(t,n,i,r)}catch(e){_.push(`Variable "${n}": ${e.message??String(e)}`)}for(let[n,i]of Object.entries(e.segments))if(i.vars)for(let[e,a]of Object.entries(i.vars))try{QP(t,`${n}.${e}`,a,r)}catch(t){_.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let v=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=p)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};v[t]={when:n.when===void 0?void 0:e(n.when,`when`,h),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let y=(e,t,n)=>{try{return h(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},b=t.variableStore,x=t=>{let n=Ws(e.segments[t.name]),r=Object.create(null);for(let[e,i]of Object.entries(n)){let n=t.settings?.[e]??i.default,a=t.drafts?.[e];Object.defineProperty(r,e,{enumerable:!0,get:a===void 0?()=>n:()=>Ys(i,String(b.read(a.variable)))??n})}return Object.freeze(r)},S=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:y(e.when,t,`when`),parse:(e,n)=>y(e,t,n),compileChild:S,placementSettings:x};return YP(e.kind).compile(e,n)},C=new Map;for(let t of l){let{node:n,path:r}=P_(e,t);C.set(t,S(n,r))}let w=new Map(io.map(e=>[e,new Map])),ee=[[`globals`,e.globals],...Object.entries(e.presets).map(([e,t])=>[`presets.${e}.globals`,t.globals??{}])];for(let[e,t]of ee)for(let n of io){let r=t[n];if(!ao(r))continue;let i=`${e}.${n}`,a=w.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:nF(p,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:v,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:w,loadWarnings:_}}function nF(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function rF(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 render but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r}function iF(e,t){return e.template.evaluate(t).map(e=>e.plain).join(``)}function aF(e,t){return e.kind===`decided`?e.name:t}function oF(e,t,n,r,i,a,o,s){let{perSegmentSink:c,onSegmentError:l,onRenderWarning:u}=o??{};r.drawAt(yo(a.colorCompatibility));let{preset:d=k_}=s??{},f=F_(e,d),p=oa[s?.variation??So(void 0,null,f.variation)];t.menuRuntime.action.variation=p;let m=s?.style??uo(`none`,e.styles),h=s?.theme??rx(void 0,null,f.palette),g=(e,t)=>({...i,term:{cols:a.width},theme:{effective:e},style:{effective:t}});r.applyInput(g(aF(h,Za),aF(m,co))),t.menuRuntime.action.chromeCols=Ek(a),t.menuRuntime.action.padding=a.padding,t.menuRuntime.action.width=a.width,t.menuRuntime.action.seamCols=Dk(a);let _=Dy(n),v=so(h,e=>{let n=rF(t,`palette`,e);return nx(iF(n,_),n.where,e=>u?.(e))}),y=so(m,n=>uo(iF(rF(t,`style`,n),_),e.styles));(v!==h||y!==m)&&r.applyInput(g(v.name,y.name));let b=v.value;t.menuRuntime.action.basePalette=b;let x=ex(b,y.value);t.menuRuntime.action.palette=x,c?.clear();let S=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},C=(e,n,i,a,o,s)=>{try{let c=r.drawnAt(),{tint:l,disclosure:u}=Ja(i,a,c),d=oP(t.activeSegment,e.name,e.id,i,u,l),f=Ax(d,c,o.bg,o.fg,n),p=()=>La(i,u,c).state;s&&(d.bg=p());let m=o.body.evaluate(n),h=d.drops.length>0||s;h&&(d.bg=p());let g=o.lead?.evaluate(n)??[],_=o.trail?.evaluate(n)??[];return{styles:{closed:f,get trigger(){return XN(i,p(),c)},get band(){return XN(i,La(i,u,c).plane,c)},get close(){return QN(i,p(),c)},disclosure:u},fragments:m,lead:g,trail:_,drops:d.drops,open:h}}finally{t.activeSegment.current=null}},w=(e,t,r)=>{let i=t&&CN(e.when,_),o={scope:_,palette:x,visible:i,padding:a.padding,region:r,perSegmentSink:c,onSegmentError:l,evaluateSegment:C,lookupSegment:S,renderChild:(e,t,n)=>w(e,t,Ka(r,n)),renderBody:(e,t,n)=>w(e,i&&t,qa(n)),closeDisclosure:e=>YN(n,e)};return YP(e.kind).render(e,o)},ee=t.roots.get(d);if(ee===void 0)throw Error(`Preset "${d}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${k_}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let te=e=>{if(!CN(e.when,_))return!1;if(e.kind===`container`)return!0;if(yw(e.name)===void 0)return!1;try{return CN(t.segments[e.name].when,ky(_,e.settings))}catch{return!0}};return t.menuRuntime.action.layout=()=>VP(ee,te).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=yw(e);return r===void 0?[]:[{name:r,address:t,palette:Qb(n.theme,x)}]})),w(ee,!0,Ga(p)).map(e=>Ok(jN(e.cells,a),a)).join(`
199
- `)}function*sF(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*cF(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);for(let t of j_(e.presets)){for(let n of Ps(P_(e,t).node))n.when!==void 0&&(yield n.when);let n=F_(e,t);for(let e of io){let t=n[e];ao(t)&&(yield t)}}for(let[,t]of sF(e))t.kind===`template`&&(yield t.template),Vs(t)&&t.cache&&`key`in t.cache&&(yield t.cache.key);for(let t of Object.values(e.actions))`copy`in t&&(yield t.copy),`open`in t&&(yield t.open),`preset`in t&&t.preset===`delete`&&(yield t.name)}function lF(e,t){return e===t||t.startsWith(`${e}.`)||e.startsWith(`${t}.`)}function uF(e,t){let n=new Set,r=new Set,i=new Set;for(let e of cF(t)){for(let r of xv(e,t.helpers).keys())n.add(r);for(let{name:n}of Tv(e,t.helpers))r.add(n);for(let n of Ev(e,t.helpers))i.add(n)}for(let[,e]of sF(t))if(Vs(e)&&e.cache&&`depends_on`in e.cache)for(let t of e.cache.depends_on)n.add(t);let a=new Set(r);for(let e of r){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)a.add(e)}let o=new Set,s=new Set;for(let e of a){let n=t.actions[e];if(n!==void 0&&(`set`in n&&o.add(n.set),`insertSegment`in n&&s.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)s.add(e)}for(let e of j_(t.presets))for(let n of Ps(P_(t,e).node))n.kind===`segment`&&s.add(n.name);let c=(e,t)=>[...n].some(t=>lF(t,e))||t.kind===`state`&&o.has(t.key),l=e=>[...e].filter(e=>!Ou(e)),u=(e,t,n)=>l(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),d=new Map(sF(e));return[...u(`variable`,d.keys(),e=>c(e,d.get(e))),...u(`action`,Object.keys(e.actions??{}),e=>a.has(e)),...u(`helper`,Object.keys(e.helpers??{}),e=>i.has(e)),...u(`segment`,Object.keys(e.segments??{}),e=>s.has(e))]}var dF=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,_F(e,t,n,`initial value`),this.cell=Mv.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){_F(this.name,this.type,e,`set value`),!Object.is(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}},fF=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,Mv.computed)(()=>{let e=n();return _F(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},pF=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=Mv.observable.box(gF(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=gF(e);hF(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function mF(e){return JSON.stringify(e)}function hF(e,t){return mF(e)===mF(t)}function gF(e){return e.kind===`ok`?{kind:`ok`,value:Nv(e.value)}:e}function _F(e,t,n,r){let i=Pv(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var vF=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new dF(e,t,n))}defineDocument(e,t){this.assertNotDefined(e),this.nodes.set(e,new pF(e,t))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new fF(e,t,()=>n(r)))}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()}setDocument(e,t){let n=this.requireNode(e);if(n.kind!==`document`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,Mv.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireNode(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,Mv.runInAction)(()=>n.set(t))}runInAction(e){(0,Mv.runInAction)(e)}has(e){return this.nodes.has(e)}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`)return mF(t.read());try{return String(t.read())}catch(e){return`failed:${e instanceof Error?e.message:String(e)}`}}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.nodes.keys()]}requireNode(e){let t=this.nodes.get(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}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}assertNotDefined(e){if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`)}};function yF(e,t,n){return e+`\0`+t+`\0`+(n??``)}function bF(e,t){return new Set(j_(e.presets).filter(n=>P_(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function xF(e){let t=c.basename(e),n=c.dirname(e);for(;!r.existsSync(n);)t=c.basename(n),n=c.dirname(n);return{dir:n,name:t}}function SF(e,t){let n=new Map;for(let t of tE(e.projectDir,e.cwd,e.configFile)){let{dir:e,name:r}=xF(t);n.has(e)||n.set(e,new Set),n.get(e).add(r)}return{files:t===null?[]:[t],dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({path:e,filenames:[...t].sort()}))}}function CF(e){return e.filter(Boolean).join(`
200
- `)||null}function wF(e,t,n,r){let i=lE(t,DA),{config:a,raw:o}=i;n.push(...i.warnings);let s=fE(i,t??`<default>`),c=new vF,l=new Ib(c,s.globals.default_empty_value??``,r.gitService,r.sessionState),u;try{u=tF(s,l,{cwd:e}),n.push(...u.loadWarnings),iM(s),dA(s)}catch(e){throw l.dispose(),e}return{config:s,store:c,registry:l,compiled:u,neededInputPaths:hj(s),lastRenderCellsBySegment:new Map,authoredRoots:bF(a,o),fileHeldSettings:Wj(o),unused:uF(o,a)}}function TF(e,t,n,r){let i=rE(e,t,n),a=i.kind===`file`?i.path:null,o=[cE(e,t),aE(i)],s;try{s=wF(t,a,o,r)}catch(e){return e instanceof Cs&&o.push(...e.warnings),{resolvedPath:a,warning:CF(o),state:null,error:e instanceof Cs||e instanceof Error?e.message:String(e)}}return{resolvedPath:a,warning:CF(o),state:s,error:null}}var EF=class{entries=new Map;deps;maxEntries;observers;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}getOrCreate(e,t,n){let r=yF(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=TF(e,t,n,this.deps),o={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:a.error,lastWarning:a.warning,state:a.state??wF(t,null,[],this.deps),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;n.state.registry.dispose(),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a.resolvedPath),this.observers.onReload?.(o),o}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=TF(e.projectDir,e.cwd,e.configFile,this.deps);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(e.state.registry.dispose(),e.state=t.state),this.refreshWatcher(e,t.resolvedPath),this.observers.onReload?.(e)}refreshWatcher(e,t){e.configFilePath=t;let n=SF(e,t),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){Z(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const DF=16384;var OF=class{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;watchersOpened=0;watchersClosed=0;watchersEvicted=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<DF){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%DF}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:zE,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,renderCache:{size:e.renderCacheSize},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes}}};function kF(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),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 AF={load:()=>({}),save:()=>{},flush:()=>{}};function jF(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var MF=class{sessions;storage;atom=(0,Mv.createAtom)(`SessionState`);constructor(e=AF,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=jF(this.storage.load()),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.get(t)??null):null}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,Mv.runInAction)(()=>{let n=this.sessions.get(e)??new Map;for(let{key:e,value:r}of t)n.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,Mv.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.delete(t),n.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,Mv.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()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,n]of this.sessions)e[t]=Object.fromEntries(n);return e}};function NF(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e)){if(typeof t!=`object`||!t||Array.isArray(t))return!1;for(let e of Object.values(t))if(typeof e!=`string`)return!1}return!0}var PF=class{timer=null;pending=null;constructor(e,t=500,n=ib){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=r.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return NF(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{r.mkdirSync(c.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;r.writeFileSync(t,JSON.stringify(e),{mode:384}),r.chmodSync(t,384),r.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const FF={default_empty_value:`string`,default_separator:`string`,palette:`string`,style:`string`,preset:`string`,endcaps:`string`,variation:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,updateNotice:`boolean`,colorCompatibility:`string`,menuGlyph:`string`},IF=new Set([`1`,`true`]),LF=new Set([`0`,`false`,``]);function RF(e,t){let n=lI(e),r=n.scope===`segment-palette`?`string`:FF[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(IF.has(t))return`true`;if(LF.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function zF(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function BF(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(c.dirname(e),{recursive:!0}),Me(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function VF(e){return/^\s*$/.test(e)?null:zo(e)}function HF(e,t){return e!==null&&Vo(e,t)!==void 0}function UF(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(UF),...i}}return e}function WF(e){if(!Pc(e))return UF(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,UF(t)])),...n}}const GF=TA,KF=GF.segments,qF=GF.presets,JF=GF.root;function YF(e,t,n,r){if(!HF(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function XF(e,t){let n=wx(t);return t.scope===`segment-palette`&&YF(e,[`segments`,t.segment],KF[t.segment],n.join(`.`)),n}function ZF(e){return zo(Yo(e))}function QF(){return Object.entries(JF.rows).map(([e,t])=>{let n=UF(t);return{path:[`root`],fragment:ZF({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function $F(e,t){let n=e===null?void 0:Vo(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function eI(e,t){if(t===void 0)return null;let n=WF(t);return{path:e,fragment:ZF(n),unit:{path:e,value:n}}}function tI(e,t){let n=[`presets`,t],r=[...n,`root`],i=qF[t];YF(e,n,i,r.join(`.`));let a=$F(e,r)??eI(r,i?.root);return a!==null&&gs(a.fragment)?a:null}function nI(e,t){let n=hs(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function rI(e,t){return[...QF(),$F(e,[`root`]),tI(e,t)].filter(e=>e!==null).reduce(nI,new Map)}function iI(e,t,n){for(let{node:r,...i}of rI(e,t).values())if(vs(r,n))return i;throw new $(`${aI(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 aI(e,t){return tI(e,t)?.path??[`root`]}function oI(e,t){return t.scope===`preset-root`?aI(e,t.preset):wx(t)}function sI(e,{unit:t}){return t===null?e:ls(e,t.path,Yo(t.value),qo)}function cI(e){let t=Cx(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function lI(e){let t=cI(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function uI(e,t,n,r){dI(t,r),BF(t,r,e.logger),e.record(t,n,r)}function dI(e,t){try{return fE(uE(e,t,DA),e)}catch(e){throw e instanceof Cs?new $(`refused: the config file would not load after this click — ${e.message}`):e}}function fI(e,t){let n=lI(t),r=VF(zF(e)??``),i=r===null?void 0:Vo(r,wx(n));return i!==void 0&&`value`in i?i.value:void 0}function pI(e,t,n){mI(e,t,n,[])}function mI(e,t,n,r){let i=zF(t);uI(e,t,i,hI(n.reduce((e,[t,n])=>ls(e,XF(VF(e),lI(t)),RF(t,n),qo),i??``),t,r,e=>e))}function hI(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=iI(VF(s),n,i),l=Ss(sI(s,c),c.path,i,a,Yo(o));if(l===null)throw new $(`${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 gI(e,t,n){let r=VF(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of rI(r,t)){if(!vs(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?Uo(e,c):Yo(s.value);if(a!==`#`)return ls(e,[...i,`rows`,a],l,qo);if(tI(r,t)!==null)throw new $(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return ls(e,i,l,qo)}return e}function _I(e,t){return ds(e,t,t[0]===`presets`&&t.length>2&&!kA(t[1])?2:0)}function vI(e,t,n){let r=n.map(cI),i=zF(t);if(i===null)return;let a=r.reduce((e,t)=>_I(e,oI(VF(e),t)),i);a!==i&&uI(e,t,i,a)}function yI(e){let t=e===null?void 0:Vo(e,[`presets`]),n=new Set([...OA,...t?.kind===`object`?t.entries.map(e=>e.key):[]].map(Su));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(Su(e)))}function bI(e,t,n,r,i,a){let o=zF(t),s=VF(o??``),c=yI(s),l=[`presets`,c],u=tI(s,n),d=[...u===null?[]:[[[...l,`root`],u.unit===null?Uo(o??``,u.fragment):Yo(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Yo(r)]]],f=i.map(([e,t])=>{let n=Sx(c,e);return[XF(s,lI(n)),RF(n,t)]});return uI(e,t,o,hI([...d,...f].reduce((e,[t,n])=>ls(e,t,n,qo),ls(o??``,l,`{}`,qo)),t,a.map(e=>({...e,preset:c})),gI)),c}function xI(e,t,n){if(kA(n))throw new $(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=zF(t),a=VF(i??``);if(i===null||a===null||Vo(a,r)===void 0)throw new $(`cannot delete preset "${n}": ${t} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Vo(a,[`globals`,`preset`]);uI(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>_I(e,t),i))}function SI(e,t,n,r){let i=cI(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=zF(t),o=r.op===`remove`?r.target:r.anchor,s=iI(VF(a??``),i.preset,o),c=sI(a??``,s),{after:l,placed:u}=CI(c,s.path,r,()=>{let e=dI(t,c);return j_(e.presets).map(t=>P_(e,t).node)});if(l===null)throw new $(`${s.path.join(`.`)} in ${t} 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 uI(e,t,a,l),u}function CI(e,t,n,r){switch(n.op){case`remove`:return{after:bs(e,t,n.target),placed:null};case`insert`:{let i=Qk(n.segment,n.anchor,r());return{after:xs(e,t,i,n.anchor,n.relation),placed:i}}}}const wI={load:()=>({}),save:()=>{}},TI=new Set(Bb.map(e=>e.sessionKey)),EI=e=>TI.has(e)||e.startsWith(tv),DI=8*1024*1024,OI={past:[],future:[]},kI=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var AI=class{state=new Map;constructor(e,t,n=wI){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}useStorage(e){this.storage=e,this.state=new Map(Object.entries(e.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??OI;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??OI}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(kI(n));r.set(kI(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:kF(this.sessionState,e=>EI(e)||e===`edit.mode`,(e,r,i,a)=>{if(r===`edit.mode`){let t=n.get(e);n.set(e,{before:t===void 0?i:t.before,after:a});return}t(e,{kind:`session`,key:r,before:i,after:a})}),file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=new Map(e),r=new Map(n);e.clear(),n.clear();for(let e of new Set([...t.keys(),...r.keys()])){let n=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=n.length===0?i:RI(i,n),o=r.get(e),s=o===void 0?a:HI(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new $(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,BI(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new $(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(kI)),a=n.net.filter(e=>!i.has(kI(e))),o=NI(UI(VI(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new $(`rewind: ${r.map(GI).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new $(`redo: nothing to redo`);let a=[...n,i],o=NI(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...FI(t.savepoint,a.length-o.length,i)}),i}apply(e,t,n,r,i){let a=n===`before`?`after`:`before`,o=t.filter(t=>this.read(e,t)!==t[a]);if(o.length>0){let t=new Set(o.map(kI)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:UI(n,t),future:UI(i,t),...a!==void 0&&{savepoint:{at:UI([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(kI(e))),below:UI(a.below,t)}}}),new $(`${r}: ${o.map(GI).join(`, `)} changed since that edit — refusing to overwrite it; this session's undo history no longer steps it`)}let s=[];try{for(let r of t)this.write(e,r,r[n]),s.push(r);this.put(e,i)}catch(t){try{for(let t of s.reverse())this.write(e,t,t[a])}catch(e){throw Error(`${t.message}; and putting the step back failed, so it is half-applied: ${e.message}`)}throw t}}read(e,t){return t.kind===`session`?this.sessionState.get(e,t.key):zF(t.file)}write(e,t,n){t.kind===`file`?BF(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||jI(n)>DI;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,MI(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${DI} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function jI(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 MI({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...FI(n,1,[])}:{past:e,future:t.slice(1),...FI(n,0,[])}}function NI(e){return e.slice(-50)}const PI=e=>e===rv.member;function FI(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:II(e.net,n),below:e.below}}}function II(e,t){let n=new Map(e.map(e=>[kI(e),e]));for(let e of t){let t=n.get(kI(e));n.set(kI(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const LI=e=>e.map(e=>({...e,before:e.after,after:e.before}));function RI(e,t){let n=[...e.past,t],r=NI(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...FI(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...zI(e.future,a),...i.below]},n.length-r.length,t)}}function zI(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function BI(e,t){return{past:e.past.slice(0,-1),future:NI([...e.future,t]),...FI(e.savepoint,0,LI(t))}}function VI(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...zI(r,t.at-i.length),...t.below]}function HI(e,t){if(PI(t.after)&&!PI(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!PI(t.after)&&PI(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function UI(e,t){return e.map(e=>e.filter(e=>!t.has(kI(e)))).filter(e=>e.length>0)}function WI(e){return e.map(GI).join(`, `)}function GI(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function KI(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function qI(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(KI))}function JI(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(KI)&&qI(t.below)}function YI(e){if(typeof e!=`object`||!e)return!1;let t=e;return qI(t.past)&&qI(t.future)&&(t.savepoint===void 0||JI(t.savepoint))}function XI(e,t){return{load:()=>{let n;try{n=r.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(YI))return e}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{r.mkdirSync(c.dirname(e),{recursive:!0}),Me(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const ZI=e=>!EI(e)&&!iS(e)&&e!==`update.dismissed`;var QI=class{past=new Map;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:kF(e,ZI,(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 $(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,Mv.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)}};function $I(e){let t=gN(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures}`]);return t.kind===`ok`?{kind:`ok`,value:t.stdout.trim().split(`,`).filter(e=>e!==``)}:{kind:`failed`,reason:t.reason}}function eL(e){return{probeTmux:$I,loadConfig:e}}function tL(e,t){let n=e.loadConfig(t),r={path:n.path,warnings:n.warning===null?[]:n.warning.split(`
201
- `)};return n.error===null?{...r,kind:`loaded`,shadowed:sE(t.projectDir,t.cwd,t.configFile??void 0),unused:n.unused}:{...r,kind:`failed`,error:n.error}}function nL(e){let t=_S(e).env;if(t===void 0)return{path:e,env:{}};if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`cannot read ${e}: \`env\` is not an object`);return{path:e,env:t}}function rL(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function iL(e){return{kind:`arrived`,handler:e,bar:zE}}function aL(e,t,n){return{tmux:rL(e,t.tmux),config:tL(e,n),claudeSettings:nL(mS(pS(t.claudeConfigDir)))}}function oL(e,t){let n=t.claudeSettings.path;switch(e.kind){case`claude-settings-env`:{let i=ls(gS(n),[`env`,e.name],JSON.stringify(e.value),Jo);return r.mkdirSync(c.dirname(n),{recursive:!0}),Me(n,i),{...t,claudeSettings:nL(n)}}default:return e.kind}}const sL={connectMs:200,budgetMs:500};async function cL(e){let n=e.includes(`--json`),r=await lL();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${RE(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
202
- `);return}t.stdout.write(pL(r.value))}function lL(){return ME({kind:`stats`},sL,e=>`stats`in e?e.stats:void 0)}function uL(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function dL(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function fL(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${e%60}s`:`${Math.floor(e/3600)}h${Math.floor(e%3600/60)}m`}function pL(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` version ${e.version}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${fL(e.uptimeSec)}`),t.push(` rss ${uL(e.rssBytes)}`),t.push(` heapUsed ${uL(e.heapUsedBytes)}`),t.push(` heapTotal ${uL(e.heapTotalBytes)}`),t.push(` external ${uL(e.externalBytes)}`),t.push(` arrayBuffers ${uL(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` hit rate ${dL(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` invalidations ${e.gitCache.invalidations}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${dL(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` evicted ${e.watchers.evicted}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let n=Object.entries(e.subprocesses.byCategory),r=n.reduce((e,[t])=>Math.max(e,t.length),13);for(let[i,a]of n){let n=e.subprocesses.p50DurationMs[i],o=e.subprocesses.p99DurationMs[i],s=n!==void 0&&o!==void 0?` (p50 ${n}ms · p99 ${o}ms)`:``;t.push(` ${i.padEnd(r)} ${a}${s}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
198
+ `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function HP(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,...UP(e,r)]}function UP(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 WP(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:HP(e.direction,e.children.map((t,i)=>n(t,[...r,GP(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function GP(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:ks[e.direction]}}const KP={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:ma(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,Fs(t.path,n)))}},render(e,t){return HP(e.direction,e.children.map((n,r)=>t.renderChild(n,t.visible,GP(e,r))))}},qP={drop:e=>e.place,above:()=>`above`},JP={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},YP={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:As(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Qc(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Is(t.path)),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){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(!t.visible)return[];let a=ky(t.scope,e.settings);try{if(!EN(i.when,a))return[];let n=Qb(e.settings.theme,t.palette),o=e.opens!==void 0&&EN(e.opens.open,t.scope),{styles:s,fragments:c,lead:l,trail:u,drops:d,open:f}=t.evaluateSegment(e,a,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,lead:e.lead,trail:e.trail},o),p=f?s.trigger:s.closed,m={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:p,padding:t.padding},h=e.opens,g=h===void 0?[]:t.renderBody(h.body,o,s.disclosure).map(e=>({...e,place:qP[h.placement](e)})),_=VP(FN(c,p)).map((e,t)=>({cells:jN(e,{...m,lead:t===0?FN(l,p):[],trail:t===0?FN(u,p):[]}),band:`own`,place:`flow`})),v=d.map(e=>({cells:jN(FN([e],s.band),{...m,baseStyle:s.band}),band:`deeper`,place:`flow`})),y=(e,t,n)=>jN(FN([e],t),{...m,width:`auto`,baseStyle:t,padding:n}),b=g.findIndex(e=>e.band===`own`),{lead:x,stays:S}=h!==void 0&&b!==-1?JP[h.placement](_,()=>y(t.closeDisclosure(h.key),s.close,t.padding)):{lead:[],stays:_},C=x.flatMap(e=>y(new W(` `.repeat(kN(e).reduce((e,t)=>e+t.cellLength,0))),s.trigger,0)),w=(e,t)=>e.band===`own`?t===b?x:C:[],ee=g.map((e,t)=>({cells:[...w(e,t),...e.cells],band:`deeper`,place:e.place})),te=[...S,...v];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...te.flatMap(e=>e.cells),...g.flatMap(w)].flatMap(kN)),[...te,...ee]}catch(n){let r=n.message??String(n);t.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:jN([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,lead:XP(e.lead,e,a,t),trail:XP(e.trail,e,a,t)}),band:`own`,place:`flow`}]}}};function XP(e,t,n,r){if(e===void 0)return[];try{return r.evaluateSegment(t,n,r.palette,r.region,{bg:void 0,fg:void 0,body:e,lead:void 0,trail:void 0},!1).fragments}catch(e){return r.onSegmentError?.(t.id,e.message??String(e)),[]}}const ZP={container:KP,segment:YP};function QP(e){return ZP[e]}function $P(e){if(`ttl`in e)return{kind:`ttl`,durationMs:yb(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 eF(e,t){switch(zs(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,regex:new RegExp(e.regex),default:t};case`text`:return{kind:`text`,default:t}}}function tF(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:$P(n.cache),parse:eF(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:$P(n.cache),parse:eF(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,ttlMs:n.cache?yb(n.cache.ttl):void 0,varDefault:n.default});break;case`git`:e.declareGit(t,{field:n.field,cwd:r,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function nF(e,t){let n=$d.EMPTY;for(let[r,i]of Object.entries(t))try{n=e.parse(`{{ define "${r}" }}${i}{{ end }}`,n).defines()}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}return n}const rF=e=>So(void 0,null,e.globals.variation);function iF(e,t,n){let r=n.cwd,i=ax(e.globals.palette),a={store:t.variableStore,compiled:new Map,chromeCols:kk({endcaps:`powerline`,charset:_o}),width:80,basePalette:i,palette:i,variation:oa[rF(e)],padding:1,seamCols:Ak({endcaps:`powerline`,charset:_o}),layout:()=>[]},o=cP(t.drawnAt),s={action:a,activeSegment:o},c=Object.keys(e.styles),l=j_(e.presets),u=dw(e),d=Ey({...ZN(a),...bP(a,o),...CP(a,o),...DP(a,o),...MP(a,o),...IP(s),...zP(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},n.clock,t.drawnAt),f=nF(d,e.helpers),p=e=>d.parse(e,f),m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let n=p(e);return m.set(e,n),n},g=new Map;for(let[t,n]of Wb)n in e.variables&&g.set(t,n);for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&!g.has(n.key)&&g.set(n.key,t);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&!g.has(r.key)&&g.set(r.key,`${t}.${e}`);a.compiled=zN(p,e.actions,g,u);let _=[];for(let[n,i]of Object.entries(e.variables))try{tF(t,n,i,r)}catch(e){_.push(`Variable "${n}": ${e.message??String(e)}`)}for(let[n,i]of Object.entries(e.segments))if(i.vars)for(let[e,a]of Object.entries(i.vars))try{tF(t,`${n}.${e}`,a,r)}catch(t){_.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let v=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=p)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};v[t]={when:n.when===void 0?void 0:e(n.when,`when`,h),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let y=(e,t,n)=>{try{return h(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},b=t.variableStore,x=t=>{let n=Ws(e.segments[t.name]),r=Object.create(null);for(let[e,i]of Object.entries(n)){let n=t.settings?.[e]??i.default,a=t.drafts?.[e];Object.defineProperty(r,e,{enumerable:!0,get:a===void 0?()=>n:()=>Ys(i,String(b.read(a.variable)))??n})}return Object.freeze(r)},S=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:y(e.when,t,`when`),parse:(e,n)=>y(e,t,n),compileChild:S,placementSettings:x};return QP(e.kind).compile(e,n)},C=new Map;for(let t of l){let{node:n,path:r}=P_(e,t);C.set(t,S(n,r))}let w=new Map(io.map(e=>[e,new Map])),ee=[[`globals`,e.globals],...Object.entries(e.presets).map(([e,t])=>[`presets.${e}.globals`,t.globals??{}])];for(let[e,t]of ee)for(let n of io){let r=t[n];if(!ao(r))continue;let i=`${e}.${n}`,a=w.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:aF(p,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:v,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:w,loadWarnings:_}}function aF(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function oF(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 render but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r}function sF(e,t){return e.template.evaluate(t).map(e=>e.plain).join(``)}function cF(e,t){return e.kind===`decided`?e.name:t}function lF(e,t,n,r,i,a,o,s){let{perSegmentSink:c,onSegmentError:l,onRenderWarning:u}=o??{};r.drawAt(yo(a.colorCompatibility));let{preset:d=k_}=s??{},f=F_(e,d),p=oa[s?.variation??So(void 0,null,f.variation)];t.menuRuntime.action.variation=p;let m=s?.style??uo(`none`,e.styles),h=s?.theme??rx(void 0,null,f.palette),g=(e,t)=>({...i,term:{cols:a.width},theme:{effective:e},style:{effective:t}});r.applyInput(g(cF(h,Za),cF(m,co))),t.menuRuntime.action.chromeCols=kk(a),t.menuRuntime.action.padding=a.padding,t.menuRuntime.action.width=a.width,t.menuRuntime.action.seamCols=Ak(a);let _=Dy(n),v=so(h,e=>{let n=oF(t,`palette`,e);return nx(sF(n,_),n.where,e=>u?.(e))}),y=so(m,n=>uo(sF(oF(t,`style`,n),_),e.styles));(v!==h||y!==m)&&r.applyInput(g(v.name,y.name));let b=v.value;t.menuRuntime.action.basePalette=b;let x=ex(b,y.value);t.menuRuntime.action.palette=x,c?.clear();let S=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},C=(e,n,i,a,o,s)=>{try{let c=r.drawnAt(),{tint:l,disclosure:u}=Ja(i,a,c),d=lP(t.activeSegment,e.name,e.id,i,u,l),f=Mx(d,c,o.bg,o.fg,n),p=()=>La(i,u,c).state;s&&(d.bg=p());let m=o.body.evaluate(n),h=d.drops.length>0||s;h&&(d.bg=p());let g=o.lead?.evaluate(n)??[],_=o.trail?.evaluate(n)??[];return{styles:{closed:f,get trigger(){return $N(i,p(),c)},get band(){return $N(i,La(i,u,c).plane,c)},get close(){return tP(i,p(),c)},disclosure:u},fragments:m,lead:g,trail:_,drops:d.drops,open:h}}finally{t.activeSegment.current=null}},w=(e,t,r)=>{let i=t&&EN(e.when,_),o={scope:_,palette:x,visible:i,padding:a.padding,region:r,perSegmentSink:c,onSegmentError:l,evaluateSegment:C,lookupSegment:S,renderChild:(e,t,n)=>w(e,t,Ka(r,n)),renderBody:(e,t,n)=>w(e,i&&t,qa(n)),closeDisclosure:e=>QN(n,e)};return QP(e.kind).render(e,o)},ee=t.roots.get(d);if(ee===void 0)throw Error(`Preset "${d}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${k_}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let te=e=>{if(!EN(e.when,_))return!1;if(e.kind===`container`)return!0;if(Sw(e.name)===void 0)return!1;try{return EN(t.segments[e.name].when,ky(_,e.settings))}catch{return!0}};return t.menuRuntime.action.layout=()=>WP(ee,te).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=Sw(e);return r===void 0?[]:[{name:r,address:t,palette:Qb(n.theme,x)}]})),w(ee,!0,Ga(p)).map(e=>jk(PN(e.cells,a),a)).join(`
199
+ `)}function*uF(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*dF(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);for(let t of j_(e.presets)){for(let n of Ps(P_(e,t).node))n.when!==void 0&&(yield n.when);let n=F_(e,t);for(let e of io){let t=n[e];ao(t)&&(yield t)}}for(let[,t]of uF(e))t.kind===`template`&&(yield t.template),Vs(t)&&t.cache&&`key`in t.cache&&(yield t.cache.key);for(let t of Object.values(e.actions))`copy`in t&&(yield t.copy),`open`in t&&(yield t.open),`preset`in t&&t.preset===`delete`&&(yield t.name)}function fF(e,t){return e===t||t.startsWith(`${e}.`)||e.startsWith(`${t}.`)}function pF(e,t){let n=new Set,r=new Set,i=new Set;for(let e of dF(t)){for(let r of xv(e,t.helpers).keys())n.add(r);for(let{name:n}of Tv(e,t.helpers))r.add(n);for(let n of Ev(e,t.helpers))i.add(n)}for(let[,e]of uF(t))if(Vs(e)&&e.cache&&`depends_on`in e.cache)for(let t of e.cache.depends_on)n.add(t);let a=new Set(r);for(let e of r){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)a.add(e)}let o=new Set,s=new Set;for(let e of a){let n=t.actions[e];if(n!==void 0&&(`set`in n&&o.add(n.set),`insertSegment`in n&&s.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)s.add(e)}for(let e of j_(t.presets))for(let n of Ps(P_(t,e).node))n.kind===`segment`&&s.add(n.name);let c=(e,t)=>[...n].some(t=>fF(t,e))||t.kind===`state`&&o.has(t.key),l=e=>[...e].filter(e=>!Ou(e)),u=(e,t,n)=>l(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),d=new Map(uF(e));return[...u(`variable`,d.keys(),e=>c(e,d.get(e))),...u(`action`,Object.keys(e.actions??{}),e=>a.has(e)),...u(`helper`,Object.keys(e.helpers??{}),e=>i.has(e)),...u(`segment`,Object.keys(e.segments??{}),e=>s.has(e))]}var mF=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,bF(e,t,n,`initial value`),this.cell=Mv.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){bF(this.name,this.type,e,`set value`),!Object.is(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}},hF=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,Mv.computed)(()=>{let e=n();return bF(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},gF=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=Mv.observable.box(yF(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=yF(e);vF(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function _F(e){return JSON.stringify(e)}function vF(e,t){return _F(e)===_F(t)}function yF(e){return e.kind===`ok`?{kind:`ok`,value:Nv(e.value)}:e}function bF(e,t,n,r){let i=Pv(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var xF=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new mF(e,t,n))}defineDocument(e,t){this.assertNotDefined(e),this.nodes.set(e,new gF(e,t))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new hF(e,t,()=>n(r)))}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()}setDocument(e,t){let n=this.requireNode(e);if(n.kind!==`document`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,Mv.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireNode(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,Mv.runInAction)(()=>n.set(t))}runInAction(e){(0,Mv.runInAction)(e)}has(e){return this.nodes.has(e)}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`)return _F(t.read());try{return String(t.read())}catch(e){return`failed:${e instanceof Error?e.message:String(e)}`}}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.nodes.keys()]}requireNode(e){let t=this.nodes.get(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}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}assertNotDefined(e){if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`)}};function SF(e,t,n){return e+`\0`+t+`\0`+(n??``)}function CF(e,t){return new Set(j_(e.presets).filter(n=>P_(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function wF(e){let t=c.basename(e),n=c.dirname(e);for(;!r.existsSync(n);)t=c.basename(n),n=c.dirname(n);return{dir:n,name:t}}function TF(e,t){let n=new Map;for(let t of iE(e.projectDir,e.cwd,e.configFile)){let{dir:e,name:r}=wF(t);n.has(e)||n.set(e,new Set),n.get(e).add(r)}return{files:t===null?[]:[t],dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({path:e,filenames:[...t].sort()}))}}function EF(e){return e.filter(Boolean).join(`
200
+ `)||null}function DF(e,t,n,r){let i=fE(t,AA),{config:a,raw:o}=i;n.push(...i.warnings);let s=hE(i,t??`<default>`),c=new xF,l=new Ib(c,s.globals.default_empty_value??``,r.gitService,r.sessionState),u;try{u=iF(s,l,{cwd:e}),n.push(...u.loadWarnings),sM(s),mA(s)}catch(e){throw l.dispose(),e}return{config:s,store:c,registry:l,compiled:u,neededInputPaths:vj(s),lastRenderCellsBySegment:new Map,authoredRoots:CF(a,o),fileHeldSettings:qj(o),unused:pF(o,a)}}function OF(e,t,n,r){let i=oE(e,t,n),a=i.kind===`file`?i.path:null,o=[dE(e,t),cE(i)],s;try{s=DF(t,a,o,r)}catch(e){return e instanceof Cs&&o.push(...e.warnings),{resolvedPath:a,warning:EF(o),state:null,error:e instanceof Cs||e instanceof Error?e.message:String(e)}}return{resolvedPath:a,warning:EF(o),state:s,error:null}}var kF=class{entries=new Map;deps;maxEntries;observers;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}getOrCreate(e,t,n){let r=SF(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=OF(e,t,n,this.deps),o={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:a.error,lastWarning:a.warning,state:a.state??DF(t,null,[],this.deps),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;n.state.registry.dispose(),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a.resolvedPath),this.observers.onReload?.(o),o}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=OF(e.projectDir,e.cwd,e.configFile,this.deps);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(e.state.registry.dispose(),e.state=t.state),this.refreshWatcher(e,t.resolvedPath),this.observers.onReload?.(e)}refreshWatcher(e,t){e.configFilePath=t;let n=TF(e,t),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){Z(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const AF=16384;var jF=class{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;watchersOpened=0;watchersClosed=0;watchersEvicted=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<AF){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%AF}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:HE,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,renderCache:{size:e.renderCacheSize},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes}}};function MF(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),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 NF={load:()=>({}),save:()=>{},flush:()=>{}};function PF(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var FF=class{sessions;storage;atom=(0,Mv.createAtom)(`SessionState`);constructor(e=NF,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=PF(this.storage.load()),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.get(t)??null):null}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,Mv.runInAction)(()=>{let n=this.sessions.get(e)??new Map;for(let{key:e,value:r}of t)n.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,Mv.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.delete(t),n.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,Mv.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()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,n]of this.sessions)e[t]=Object.fromEntries(n);return e}};function IF(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e)){if(typeof t!=`object`||!t||Array.isArray(t))return!1;for(let e of Object.values(t))if(typeof e!=`string`)return!1}return!0}var LF=class{timer=null;pending=null;constructor(e,t=500,n=ib){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=r.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return IF(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{r.mkdirSync(c.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;r.writeFileSync(t,JSON.stringify(e),{mode:384}),r.chmodSync(t,384),r.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const RF={default_empty_value:`string`,default_separator:`string`,palette:`string`,style:`string`,preset:`string`,endcaps:`string`,variation:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,updateNotice:`boolean`,colorCompatibility:`string`,menuGlyph:`string`},zF=new Set([`1`,`true`]),BF=new Set([`0`,`false`,``]);function VF(e,t){let n=fI(e),r=n.scope===`segment-palette`?`string`:RF[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(zF.has(t))return`true`;if(BF.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function HF(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function UF(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(c.dirname(e),{recursive:!0}),Me(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function WF(e){return/^\s*$/.test(e)?null:zo(e)}function GF(e,t){return e!==null&&Vo(e,t)!==void 0}function KF(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(KF),...i}}return e}function qF(e){if(!Pc(e))return KF(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,KF(t)])),...n}}const JF=OA,YF=JF.segments,XF=JF.presets,ZF=JF.root;function QF(e,t,n,r){if(!GF(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function $F(e,t){let n=Ex(t);return t.scope===`segment-palette`&&QF(e,[`segments`,t.segment],YF[t.segment],n.join(`.`)),n}function eI(e){return zo(Yo(e))}function tI(){return Object.entries(ZF.rows).map(([e,t])=>{let n=KF(t);return{path:[`root`],fragment:eI({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function nI(e,t){let n=e===null?void 0:Vo(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function rI(e,t){if(t===void 0)return null;let n=qF(t);return{path:e,fragment:eI(n),unit:{path:e,value:n}}}function iI(e,t){let n=[`presets`,t],r=[...n,`root`],i=XF[t];QF(e,n,i,r.join(`.`));let a=nI(e,r)??rI(r,i?.root);return a!==null&&gs(a.fragment)?a:null}function aI(e,t){let n=hs(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function oI(e,t){return[...tI(),nI(e,[`root`]),iI(e,t)].filter(e=>e!==null).reduce(aI,new Map)}function sI(e,t,n){for(let{node:r,...i}of oI(e,t).values())if(vs(r,n))return i;throw new $(`${cI(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 cI(e,t){return iI(e,t)?.path??[`root`]}function lI(e,t){return t.scope===`preset-root`?cI(e,t.preset):Ex(t)}function uI(e,{unit:t}){return t===null?e:ls(e,t.path,Yo(t.value),qo)}function dI(e){let t=Tx(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function fI(e){let t=dI(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function pI(e,t,n,r){mI(t,r),UF(t,r,e.logger),e.record(t,n,r)}function mI(e,t){try{return hE(pE(e,t,AA),e)}catch(e){throw e instanceof Cs?new $(`refused: the config file would not load after this click — ${e.message}`):e}}function hI(e,t){let n=fI(t),r=WF(HF(e)??``),i=r===null?void 0:Vo(r,Ex(n));return i!==void 0&&`value`in i?i.value:void 0}function gI(e,t,n){_I(e,t,n,[])}function _I(e,t,n,r){let i=HF(t);pI(e,t,i,vI(n.reduce((e,[t,n])=>ls(e,$F(WF(e),fI(t)),VF(t,n),qo),i??``),t,r,e=>e))}function vI(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=sI(WF(s),n,i),l=Ss(uI(s,c),c.path,i,a,Yo(o));if(l===null)throw new $(`${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 yI(e,t,n){let r=WF(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of oI(r,t)){if(!vs(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?Uo(e,c):Yo(s.value);if(a!==`#`)return ls(e,[...i,`rows`,a],l,qo);if(iI(r,t)!==null)throw new $(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return ls(e,i,l,qo)}return e}function bI(e,t){return ds(e,t,t[0]===`presets`&&t.length>2&&!MA(t[1])?2:0)}function xI(e,t,n){let r=n.map(dI),i=HF(t);if(i===null)return;let a=r.reduce((e,t)=>bI(e,lI(WF(e),t)),i);a!==i&&pI(e,t,i,a)}function SI(e){let t=e===null?void 0:Vo(e,[`presets`]),n=new Set([...jA,...t?.kind===`object`?t.entries.map(e=>e.key):[]].map(Su));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(Su(e)))}function CI(e,t,n,r,i,a){let o=HF(t),s=WF(o??``),c=SI(s),l=[`presets`,c],u=iI(s,n),d=[...u===null?[]:[[[...l,`root`],u.unit===null?Uo(o??``,u.fragment):Yo(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Yo(r)]]],f=i.map(([e,t])=>{let n=wx(c,e);return[$F(s,fI(n)),VF(n,t)]});return pI(e,t,o,vI([...d,...f].reduce((e,[t,n])=>ls(e,t,n,qo),ls(o??``,l,`{}`,qo)),t,a.map(e=>({...e,preset:c})),yI)),c}function wI(e,t,n){if(MA(n))throw new $(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=HF(t),a=WF(i??``);if(i===null||a===null||Vo(a,r)===void 0)throw new $(`cannot delete preset "${n}": ${t} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Vo(a,[`globals`,`preset`]);pI(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>bI(e,t),i))}function TI(e,t,n,r){let i=dI(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=HF(t),o=r.op===`remove`?r.target:r.anchor,s=sI(WF(a??``),i.preset,o),c=uI(a??``,s),{after:l,placed:u}=EI(c,s.path,r,()=>{let e=mI(t,c);return j_(e.presets).map(t=>P_(e,t).node)});if(l===null)throw new $(`${s.path.join(`.`)} in ${t} 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 pI(e,t,a,l),u}function EI(e,t,n,r){switch(n.op){case`remove`:return{after:bs(e,t,n.target),placed:null};case`insert`:{let i=tA(n.segment,n.anchor,r());return{after:xs(e,t,i,n.anchor,n.relation),placed:i}}}}const DI={load:()=>({}),save:()=>{}},OI=new Set(Bb.map(e=>e.sessionKey)),kI=e=>OI.has(e)||e.startsWith(tv),AI=8*1024*1024,jI={past:[],future:[]},MI=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var NI=class{state=new Map;constructor(e,t,n=DI){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}useStorage(e){this.storage=e,this.state=new Map(Object.entries(e.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??jI;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??jI}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(MI(n));r.set(MI(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:MF(this.sessionState,e=>kI(e)||e===`edit.mode`,(e,r,i,a)=>{if(r===`edit.mode`){let t=n.get(e);n.set(e,{before:t===void 0?i:t.before,after:a});return}t(e,{kind:`session`,key:r,before:i,after:a})}),file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=new Map(e),r=new Map(n);e.clear(),n.clear();for(let e of new Set([...t.keys(),...r.keys()])){let n=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=n.length===0?i:VI(i,n),o=r.get(e),s=o===void 0?a:GI(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new $(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,UI(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new $(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(MI)),a=n.net.filter(e=>!i.has(MI(e))),o=II(KI(WI(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new $(`rewind: ${r.map(JI).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new $(`redo: nothing to redo`);let a=[...n,i],o=II(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...RI(t.savepoint,a.length-o.length,i)}),i}apply(e,t,n,r,i){let a=n===`before`?`after`:`before`,o=t.filter(t=>this.read(e,t)!==t[a]);if(o.length>0){let t=new Set(o.map(MI)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:KI(n,t),future:KI(i,t),...a!==void 0&&{savepoint:{at:KI([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(MI(e))),below:KI(a.below,t)}}}),new $(`${r}: ${o.map(JI).join(`, `)} changed since that edit — refusing to overwrite it; this session's undo history no longer steps it`)}let s=[];try{for(let r of t)this.write(e,r,r[n]),s.push(r);this.put(e,i)}catch(t){try{for(let t of s.reverse())this.write(e,t,t[a])}catch(e){throw Error(`${t.message}; and putting the step back failed, so it is half-applied: ${e.message}`)}throw t}}read(e,t){return t.kind===`session`?this.sessionState.get(e,t.key):HF(t.file)}write(e,t,n){t.kind===`file`?UF(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||PI(n)>AI;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,FI(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${AI} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function PI(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 FI({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...RI(n,1,[])}:{past:e,future:t.slice(1),...RI(n,0,[])}}function II(e){return e.slice(-50)}const LI=e=>e===rv.member;function RI(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:zI(e.net,n),below:e.below}}}function zI(e,t){let n=new Map(e.map(e=>[MI(e),e]));for(let e of t){let t=n.get(MI(e));n.set(MI(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const BI=e=>e.map(e=>({...e,before:e.after,after:e.before}));function VI(e,t){let n=[...e.past,t],r=II(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...RI(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...HI(e.future,a),...i.below]},n.length-r.length,t)}}function HI(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function UI(e,t){return{past:e.past.slice(0,-1),future:II([...e.future,t]),...RI(e.savepoint,0,BI(t))}}function WI(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...HI(r,t.at-i.length),...t.below]}function GI(e,t){if(LI(t.after)&&!LI(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!LI(t.after)&&LI(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function KI(e,t){return e.map(e=>e.filter(e=>!t.has(MI(e)))).filter(e=>e.length>0)}function qI(e){return e.map(JI).join(`, `)}function JI(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function YI(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function XI(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(YI))}function ZI(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(YI)&&XI(t.below)}function QI(e){if(typeof e!=`object`||!e)return!1;let t=e;return XI(t.past)&&XI(t.future)&&(t.savepoint===void 0||ZI(t.savepoint))}function $I(e,t){let n=e=>e.kind===`file`||kI(e.key)?!0:(t.add(e.key),!1),r=e=>e.map(e=>e.filter(n)).filter(e=>e.length>0),{savepoint:i}=e,a=r(e.past),o=r(e.future);return i===void 0?{past:a,future:o}:{past:a,future:o,savepoint:{at:r(e.past.slice(0,i.at)).length,net:i.net.filter(n),below:r(i.below)}}}function eL(e,t){return{load:()=>{let n;try{n=r.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(QI)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,$I(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{r.mkdirSync(c.dirname(e),{recursive:!0}),Me(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const tL=e=>!kI(e)&&!oS(e)&&e!==`update.dismissed`;var nL=class{past=new Map;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:MF(e,tL,(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 $(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,Mv.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)}};function rL(e){let t=yN(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures}`]);return t.kind===`ok`?{kind:`ok`,value:t.stdout.trim().split(`,`).filter(e=>e!==``)}:{kind:`failed`,reason:t.reason}}function iL(e){return{probeTmux:rL,loadConfig:e}}function aL(e,t){let n=e.loadConfig(t),r={path:n.path,warnings:n.warning===null?[]:n.warning.split(`
201
+ `)};return n.error===null?{...r,kind:`loaded`,shadowed:uE(t.projectDir,t.cwd,t.configFile??void 0),unused:n.unused}:{...r,kind:`failed`,error:n.error}}function oL(e){let t=yS(e).env;if(t===void 0)return{path:e,env:{}};if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`cannot read ${e}: \`env\` is not an object`);return{path:e,env:t}}function sL(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function cL(e){return{kind:`arrived`,handler:e,bar:HE}}function lL(e,t,n){return{tmux:sL(e,t.tmux),config:aL(e,n),claudeSettings:oL(gS(hS(t.claudeConfigDir)))}}function uL(e,t){let n=t.claudeSettings.path;switch(e.kind){case`claude-settings-env`:{let i=ls(vS(n),[`env`,e.name],JSON.stringify(e.value),Jo);return r.mkdirSync(c.dirname(n),{recursive:!0}),Me(n,i),{...t,claudeSettings:oL(n)}}default:return e.kind}}const dL={connectMs:200,budgetMs:500};async function fL(e){let n=e.includes(`--json`),r=await pL();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${VE(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
202
+ `);return}t.stdout.write(_L(r.value))}function pL(){return FE({kind:`stats`},dL,e=>`stats`in e?e.stats:void 0)}function mL(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function hL(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function gL(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${e%60}s`:`${Math.floor(e/3600)}h${Math.floor(e%3600/60)}m`}function _L(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` version ${e.version}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${gL(e.uptimeSec)}`),t.push(` rss ${mL(e.rssBytes)}`),t.push(` heapUsed ${mL(e.heapUsedBytes)}`),t.push(` heapTotal ${mL(e.heapTotalBytes)}`),t.push(` external ${mL(e.externalBytes)}`),t.push(` arrayBuffers ${mL(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` hit rate ${hL(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` invalidations ${e.gitCache.invalidations}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${hL(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` evicted ${e.watchers.evicted}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let n=Object.entries(e.subprocesses.byCategory),r=n.reduce((e,[t])=>Math.max(e,t.length),13);for(let[i,a]of n){let n=e.subprocesses.p50DurationMs[i],o=e.subprocesses.p99DurationMs[i],s=n!==void 0&&o!==void 0?` (p50 ${n}ms · p99 ${o}ms)`:``;t.push(` ${i.padEnd(r)} ${a}${s}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
203
203
  `)+`
204
- `}const mL=e=>({kind:`ok`,value:e}),hL=e=>({kind:`failed`,reason:e});var gL=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const _L=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function vL(e){return _L.test(e)?e:null}function yL(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return mL(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return mL({app:n,missing:hL(`its script could not be read (${r.reason})`)});let i=OO(r.value);return mL({app:n,missing:i===null?hL("its script is not one `cc-candybar install` wrote"):mL([i.node,i.script].filter(t=>!e.exists(t)))})}async function bL(e,t){let n=e.now()+5e3;for(;e.now()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,handler:r.handler,bar:n.value.version}}return null}async function xL(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${DD}://${XD}/${n}`);return(r===null?await bL(e,n):null)??{kind:`lost`,unopened:r,opener:yL(e)}}function SL(e,t,n){let r=Ae({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?mL(r.stdout):hL(r.stderr.trim()||r.error||r.reason)}const CL=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${DD}://probe"));u.isNil() ? "" : u.path.js`;async function wL(){let e=await lL();if(e.kind!==`ok`)return hL(RE(e).split(`
205
- `).join(` — `));let{version:t,handlerProbes:n}=e.value;return Array.isArray(n)?mL({version:t,arrivals:n}):hL(`the running daemon (${t}) predates this check`)}function TL(){return{platform:process.platform,sockets:{own:Le(),handler:Re()},now:Date.now,nonce:se,daemon:wL,open:e=>{let t=SL(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=SL(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,CL]);if(e.kind===`failed`)return e;let t=e.value.trim();return mL(t===``?null:t)},script:e=>SL(`doctor.osadecompile`,`/usr/bin/osadecompile`,[kO(e)]),exists:r.existsSync}}const EL=/^─{20,}/,DL=/^❯(\s|$)/,OL=/›\s*stashed$/;function kL(e){if(e.inMode)return{kind:`in-mode`};let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>EL.test(e)?[t]:[]).at(-2);return n===void 0||!DL.test(t[n+1]??``)?{kind:`no-prompt`}:OL.test(t[n-1]??``)?{kind:`stashed`}:{kind:`ready`}}const AL={"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 jL(e,t,n){if(t===void 0)return{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`};if(t===null)return{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only type into a tmux pane`};let r=kL(e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:AL[r.kind]};let i=e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}const ML=`cc-candybar-slash`;function NL(e,t,n,r){let i=gN(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function PL(e){let t=NL(e,`claude-input.read`,[`display`,`-p`,`-t`,e.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,e.pane]);if(t.kind===`rate-limited`)throw Error(t.reason);let[n=``,...r]=t.stdout.split(`
206
- `);return{inMode:n!==`0`,screen:r}}function FL(e,t){let n=NL(e,`claude-input.type`,[`load-buffer`,`-b`,ML,`-`,`;`,`send-keys`,`-t`,e.pane,`C-s`,`;`,`paste-buffer`,`-p`,`-d`,`-b`,ML,`-t`,e.pane,`;`,`send-keys`,`-t`,e.pane,`Enter`],t);return n.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${n.reason})`}}function IL(){return{read:PL,type:FL}}function LL(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function RL(e){return zL(()=>decodeURIComponent(e))}function zL(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function BL(e,t){let n=Ae({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const VL=(e,t)=>BL(RL(e),t),HL=(e,t)=>{let n=Ae({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,RL(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},UL=(e,t)=>BL(RL(e),t),WL=(e,t)=>BL(RL(e),t),GL=(e,t)=>{let n=LL(RL(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},KL=(e,t)=>{let[n=``,...r]=zL(()=>eO(e)),i=LL(n),a=iM(iR(t,i));if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new $(`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 $(`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 $(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}XL(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},qL=/^-?\d+$/;function JL(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const YL=(e,t)=>{let[n=``,r=``,i=``]=zL(()=>eO(e)),a=LL(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!qL.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=iR(t,a),c=iM(s),l=c.rangeParamsFor(r);if(!l)throw new $(`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&&qL.test(u)?ZL(l,parseInt(u,10)):QL(`step-state`,r,l,sM(s,e=>t.sessionState.get(a,e),r)),f=JL(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new $(`step-state: ${p.reason}`);XL(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function XL(e,t,n,r){let i=r.filter(e=>e.key.startsWith(tv));if(i.length===0)return;let a=zj(iR(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new $(`${n}: refused — ${a.join(`; `)}`)}function ZL(e,t){return Math.max(e.min,Math.min(e.max,t))}function QL(e,t,n,r){if(r===null)return n.min;if(!qL.test(r))throw new $(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return ZL(n,parseInt(r,10))}const $L=`render-origin`;function eR(e){return JSON.stringify(e)}function tR(e){let t;try{t=JSON.parse(e)}catch{throw new $(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new $(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new $(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function nR(e,t){let n=e.sessionState.get(t,$L);if(n===null)throw new $(`session ${t} has not rendered yet — no config to act on`);return tR(n)}function rR(e,t,n){let r=e.sessionState.get(t,$L);if(r===null)return;let i=tR(r),a=aR(i);n.some(e=>e.kind===`file`&&e.file===a)&&e.reloadConfig(i)}function iR(e,t){return e.configFor(nR(e,t))}function aR(e){return iE(e.projectDir,e.cwd,e.configFile??void 0)}function oR(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const sR=(e,t)=>{let[n=``,r=``,i=``]=zL(()=>eO(e)),a=LL(n),o=nR(t,a),s=t.configFor(o),c=dA(s);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new $(`set-config: ${l.reason}`);let u=aR(o),d=Lj(s,e=>t.sessionState.get(a,e),r);pI(oR(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u} (session=${a})`)},cR=(e,t)=>{let[n=``,r=``,i=``]=zL(()=>eO(e)),a=LL(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!qL.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=nR(t,a),c=t.configFor(s),l=dA(c),u=l.rangeParamsFor(r);if(!u)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=aR(s),f=Lj(c,e=>t.sessionState.get(a,e),r),p=fI(d,f.key),m=typeof p==`number`?ZL(u,p):QL(`step-config`,r,u,pA(f.globals,r)),h=JL(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new $(`step-config: ${g.reason}`);pI(oR(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.dlog(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d} (session=${a})`)},lR=(e,t)=>{let[n=``]=zL(()=>eO(e)),r=LL(n),i=nR(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=Fj(a,o),c=Rj(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=iM(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new $(`save: ${t.reason}`);return[e.target,t.value]});dR(`save`,l,c);let d=aR(i);mI(oR(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.dlog(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(uR)].join(` `)} → ${d} (session=${r})`)},uR=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Js(e.value)}`;function dR(e,t,n){for(let r of n){let n=t.validate(r.key,Js(r.value));if(!n.ok)throw new $(`${e}: ${n.reason}`)}}const fR=(e,t)=>{let[n=``]=zL(()=>eO(e)),r=LL(n),i=nR(t,r),a=t.configFor(i),o=Hj(a,e=>t.sessionState.get(r,e)),s=iM(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new $(`save-preset: ${t.reason}`);return[e.configKey,t.value]});dR(`save-preset`,s,o.placements);let l=aR(i),u=bI(oR(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Bb.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,zb.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(uR)].join(` `)} → ${l} (session=${r})`)},pR=(e,t)=>{let[n=``,r=``]=zL(()=>eO(e)),i=LL(n);if(!r)throw new $(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=nR(t,i),o=aR(a);xI(oR(t,i),o,r),t.reloadConfig(a);let s=zb.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o} (session=${i})`)},mR=(e,t)=>{let[n=``,...r]=zL(()=>eO(e)),i=LL(n),a=nR(t,i),o=dA(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new $(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=aR(a),l=r.map(Uj),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);vI(oR(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.dlog(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c} (session=${i})`)};function hR(e,t){let n=(e,t)=>[...Ps(P_(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(j_(t.presets).flatMap(e=>n(t,e).map(t=>nv(Su(e),As(t)))));return j_(e.presets).flatMap(t=>n(e,t).map(e=>({member:nv(Su(t),As(e)),node:e})).filter(({member:e})=>!r.has(e)))}function gR(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[X_]:[]])}const _R=(e,t)=>{let[n=``,r=``,i=``]=zL(()=>eO(e)),a=LL(n),o=nR(t,a),s=t.configFor(o),c=dA(s);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new $(`apply-layout-op: ${l.reason}`);let u=Zk(l.value);if(u===null)throw new $(`apply-layout-op: "${l.value}" is not a layout op token`);let d=aR(o),f=SI(oR(t,a),d,r,u);t.reloadConfig(o);let p=gR(hR(s,t.configFor(o)),t.sessionState.get(a,X_)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.dlog(`info`,`apply-layout-op: ${r} ${l.value} → ${d} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},vR=(e,t)=>{let[n=``]=zL(()=>eO(e)),r=LL(n);t.journal.commit();let i=t.history.undo(r);rR(t,r,i),t.dlog(`info`,`undo: restored ${WI(i)} (session=${r})`)},yR=(e,t)=>{let n=LL(RL(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,iM(iR(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},bR=(e,t)=>{let n=LL(RL(e));t.journal.commit();let r=t.history.rewind(n);rR(t,n,r),t.dlog(`info`,`rewind: put back ${WI(r)||`nothing`} as edit mode found it (session=${n})`)},xR=(e,t)=>{let[n=``]=zL(()=>eO(e)),r=LL(n);t.journal.commit();let i=t.history.redo(r);rR(t,r,i),t.dlog(`info`,`redo: re-applied ${WI(i)} (session=${r})`)},SR=(e,t)=>{LL(RL(e)),t.applyUpdate()},CR=`client-hints`;function wR(e,t){let n=e.sessionState.get(t,CR);if(n===null)throw new $(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new $(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new $(`client hints record is not an object: ${n}`);return yE(r)}function TR(e,t,n){let r=qx(n);e.sessionState.setBatch(t,Qx(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} (session=${t})`)}function ER(e,t){return{...aL(e.doctor,wR(e,t),nR(e,t)),urlHandler:iL(e.clientVersion)}}const DR=(e,t)=>{let n=LL(RL(e));TR(t,n,ER(t,n))},OR=(e,t)=>{let n=vL(RL(e));if(n===null)throw new $(`doctor-probe: the value is not a probe nonce`);t.probes.arrive({nonce:n,handler:t.clientVersion}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${t.clientVersion??`unreported`}`)},kR=(e,t)=>{let[n=``,r=``]=zL(()=>eO(e)),i=LL(n),a=Jx(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=ER(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new $(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=oL(s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.name}=${s.fix.value} (session=${i})`),TR(t,i,c)},AR=(e,t)=>{let[n=``,...r]=zL(()=>eO(e)),i=LL(n),a=nR(t,i),o=Object.values(t.configFor(a).actions).filter(e=>`ceiling`in e).find(e=>{let t=Ow(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(o===void 0)throw new $(`ceiling: "${r.join(` `)}" is not a move this config declares`);let s=o.ceiling===`set`?{kind:`set`,to:o.to}:{kind:`clear`},c=UA({sessionId:i,projectDir:a.projectDir,cwd:a.cwd},wR(t,i));t.memento.move(c,s),t.dlog(`info`,`ceiling: ${r.join(` `)} (session=${i} claudeConfigDir=${c.claudeConfigDir})`)},jR=(e,t)=>{let[n=``,r=``]=zL(()=>eO(e)),i=LL(n),a=Object.values(t.configFor(nR(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new $(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=jL(t.claudeInput,wR(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new $(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)},MR=`config-override`,NR=new Map([[jD,VL],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=LL(zL(()=>decodeURIComponent(e.slice(0,n)))),i=zL(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new $(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new $(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,MR),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,MR,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[MD,HL],[kD,KL],[AD,YL],[ID,sR],[LD,cR],[VD,mR],[RD,lR],[zD,fR],[BD,pR],[HD,_R],[UD,vR],[WD,xR],[GD,yR],[KD,bR],[PD,UL],[FD,WL],[ND,GL],[qD,SR],[JD,DR],[YD,kR],[XD,OR],[ZD,AR],[QD,jR]]),PR=new Set([kD,AD,ID,LD,VD,RD,zD,BD,HD,UD,WD,GD,KD,ND,qD,JD,YD,ZD,QD]),FR=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of iO(nO(e))){if(!i&&PR.has(a)){let e=eO(o);e.length>0&&e[0]&&(i=e[0])}let e=NR.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof $||(r=!0),n.push(`${a}: ${e instanceof Error?e.message:String(e)}`)}}if(n.length>0){i&&t.sessionState.set(i,`click.error`,n.join(`
207
- `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}};function IR(e){return(t,n)=>{let r=n.history.begin(),i=n.navigation.begin(r.sessionState),a=[];try{e(t,{...n,sessionState:r.sessionState,journal:r,navigating:i.sessionState})}catch(e){a.push(e)}i.commit();try{r.commit()}catch(e){a.push(e)}if(a.length===1)throw a[0];if(a.length>1)throw Error(a.map(e=>String(e.message??e)).join(`; `))}}const LR=new Map([...NR,[OD,FR]].map(([e,t])=>[e,IR(t)]));Object.freeze([...LR.keys()]);const RR=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`]),zR=[[`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`]],BR=[[`workspace.added_dirs`,`string-list`]];function VR(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of zR){let i=WR(n,e);if(i==null)t.missingRequired.push(e);else{let n=HR(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of BR){let i=WR(n,e),a=i===void 0?r:UR(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))RR.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function HR(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function UR(e){return Array.isArray(e)&&e.every(e=>HR(e)===`string`)?`string-list`:HR(e)}function WR(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 GR(e,t){switch(e){case`vars`:return{what:e,vars:KR(t)};case`segments`:return{what:e,segments:ZR(t)};case`config`:return{what:e,config:tz(t)}}}function KR(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=YR(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...qR(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:JR(r.lastUpdatedMs())})}return o}function qR(e){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`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function JR(e){return e===null?null:Math.max(0,Date.now()-e)}function YR(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,XR(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}`,XR(i));return t}function XR(e){return e.kind}function ZR(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=$R(n),o=QR(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:ez(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function QR(e){let t=new Map;for(let n of j_(e.presets))for(let r of Ps(P_(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=As(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function $R(e){let t=[],n=new Set;for(let r of Ps(Lc(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 ez(e,t,n){let r=new Set;for(let i of xv(e,t).keys()){if(n.has(i)){r.add(i);continue}let e=i.split(`.`);for(;e.length>1;){e.pop();let t=e.join(`.`);if(n.has(t)){r.add(t);break}}}return Array.from(r).sort()}function tz(e){return e===null?null:e.config}const nz=[`vars`,`segments`,`config`];function rz(e){return typeof e==`string`&&nz.includes(e)}function iz(e){return Math.max(1,e-2)}var az=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return c.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t){let n=this.pathFor(e);if(t===(this.written.get(e)??null))return null;try{return t===null?(r.rmSync(n,{force:!0}),this.written.delete(e)):(r.mkdirSync(this.dir,{recursive:!0,mode:448}),r.writeFileSync(n,t,{mode:384}),this.written.set(e,t)),null}catch(e){return`${n}: ${e.message}`}}reset(){this.written.clear();try{return r.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};const oz=new OF,sz=new gL;De(oz.launchStats);const cz=new ob({counters:oz,logger:Z}),lz=SN({watchers:cz,logger:Z}),{gitProvider:uz,usageStore:dz,mementoProvider:fz}=lz,pz=new MF,mz=new AI(pz,Z),hz=new QI,gz=new az(Ye()),_z=new EF({gitService:uz,sessionState:pz,watchers:cz},{observers:{onReload:e=>Z(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} file=${e.configFilePath??`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),vz=60*1e3;function yz(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(T(e)),t.argv[1]&&n.push(t.argv[1]);let i=new Map;for(let e of n)try{i.set(e,r.statSync(e).mtimeMs)}catch{}let a=null,o=()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){Z(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),Fz(0);return}}catch(e){Z(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,vz),a.unref())},checkNow:o}}const bz=yz(),xz=EM({entryUrl:import.meta.url,intervalMs:vz,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>bz.checkNow(),log:Z});let Sz=null,Cz=null,wz=0;function Tz(){t.on(`uncaughtException`,e=>{Z(`error`,`uncaughtException: ${e.stack||e.message}`),Fz(1)}),t.on(`unhandledRejection`,e=>{Z(`error`,`unhandledRejection: ${String(e)}`),Fz(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Z(`info`,`received ${e}, shutting down`),Fz(0)});try{wz=eD(t.env)}catch(e){Z(`error`,`refusing to boot: ${e.message}`),Fz(1);return}Sz=ek(t.pid);let e=uk(fk(Sz));if(!e.decision.allow){Z(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),Fz(1);return}Cz=e.registryPath,r.mkdirSync(Ie(),{recursive:!0}),Be(Le()),pz.useStorage(new PF(Ue(),500,Z)),mz.useStorage(XI(We(),Z)),rk({anchor:nk(t.env),isAlive:ik,onOrphaned:e=>{Z(`info`,`parent watchdog: ${e}; shutting down`),Fz(0)}}),Ez(b.createServer({allowHalfOpen:!1},e=>{Iz(e)}),Le(),!1)}function Ez(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Z(`error`,`server error: ${i.message}`),Fz(1);return}if(r){Z(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}Dz(e,n)}),e.listen(n,()=>Oz(n))}function Dz(e,n){let i=WO(GO(Ve(n)),(e,t)=>$O(e,t,{readStartTime:QO,pidAlive:ik}));if(i.kind===`attach-and-exit`){Z(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}Z(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){Z(`error`,`cannot unlink stale socket ${n}: ${e.message}`),Fz(1);return}}Ez(e,n,!0)}function Oz(e){let n=JO(e);if(n.kind!==`present`){Z(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),Fz(0);return}Mz(e);try{r.chmodSync(e,384)}catch(e){Z(`warn`,`chmod socket failed: ${e.message}`)}Z(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(ne.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(wz/1048576)}MB`),_D();let i=gz.reset();i!==null&&Z(`warn`,`diagnostic dump wipe failed: ${i}`),bz.arm(),xz.arm(),jz(),kz(e,n.identity)}function kz(e,n){ZO({bound:n,myPid:t.pid,readIdentity:()=>JO(e),readLease:()=>GO(Ve(e)),shutdown:e=>Fz(e),log:Z}).arm()}let Az=null;function jz(){Az=iD(cD(oz.startedAt.getTime(),e=>Fz(e),{rssLimitBytes:wz})),Az.arm()}function Mz(e){let n=KO(Ve(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:Sz});n!==null&&Z(`warn`,`lease write failed: ${n}`)}let Nz=0,Pz=!1;function Fz(e){if(!Pz){Pz=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{uz.close()}catch(e){Z(`warn`,`gitService close failed: ${e.message}`)}try{dz.close()}catch(e){Z(`warn`,`usageStore close failed: ${e.message}`)}try{cz.closeAll()}catch(e){Z(`warn`,`watcherRegistry close failed: ${e.message}`)}try{pz.flush()}catch(e){Z(`warn`,`sessionState flush failed: ${e.message}`)}qO(He(),t.pid),Cz!==null&&dk(Cz,t.pid,ck,e=>r.unlinkSync(e)),t.exit(e)}}function Iz(e){Nz++,oz.inFlight=Nz;let t=!1,n=(n,r)=>{if(t){r!==null&&Z(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>Fz(r);try{e.end(kE(n),i)}catch(e){Z(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{oz.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=AE(e=>{Rz(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{Z(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{Z(`warn`,`frame parse failed: ${e.message}`),n({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null)});e.on(`data`,i),e.on(`error`,e=>{Z(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),Nz=Math.max(0,Nz-1),oz.inFlight=Nz})}const Lz=e=>({resp:e,exitAfterFlush:null});async function Rz(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return Lz({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?Z(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):Z(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null};if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0};if(e.kind===`stats`)return Lz({ok:!0,stats:oz.snapshot({gitCache:uz.getStats(),usageCache:dz.getStats(),renderCacheSize:_z.size,watchersActive:cz.size(),nextRestartReason:Az?.describeNextRestart()??null,handlerProbes:sz.list()})});if(e.kind===`render`){oz.requestsTotal++;let t=Date.now();try{let{report:n}=VR(e.hookData);for(let e of n.unknownTopLevelFields)Z(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let r=[];for(let e of n.missingRequired)r.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:i}of n.typeMismatches)r.push(`field '${e}' expected ${t}, got ${i}`);if(e.cwd===``&&r.push(`request 'cwd' is empty`),r.length>0)return oz.requestsErrored++,Z(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),Lz({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=zz(e.args),s=e.hookData.session_id,c=yE(e),l=JSON.stringify(c);pz.get(s,`client-hints`)!==l&&pz.set(s,CR,l);let u=pz.get(s,`config-override`)??a??c.configEnv,d=_z.getOrCreate(i,e.cwd,u),f=eR({projectDir:i,cwd:e.cwd,configFile:u??null});pz.get(s,`render-origin`)!==f&&pz.set(s,$L,f);let p=c.termCols,m=iz(p??120),h=kk(c.termRows),{authoredRoots:g}=d.state,_=t=>pz.get(e.hookData.session_id,t),v=nj(d.state.config,_,e=>g.has(e)),y=await yj(e.hookData,{...Wz,navigation:e=>hz.depth(e,pz,iM(d.state.config))},e.cwd,d.state.neededInputPaths(v.preset),v,c,{...Gj(d.state.config,d.state.fileHeldSettings,_),configPath:d.configFilePath}),b=[],x=rj(v,m),S=oF(d.state.config,d.state.compiled,d.state.store,d.state.registry,y,x,{perSegmentSink:d.state.lastRenderCellsBySegment,onRenderWarning:e=>b.push(e)},ij(v)),C=pz.get(e.hookData.session_id,`click.error`);C&&pz.clear(e.hookData.session_id,`click.error`);let w=[o,d.lastError,C].filter(Boolean).join(`
208
- `),ee=xz.notice({sessionId:s,dismissed:pz.get(s,uM),enabled:v.updateNotice}),te=d.lastError===null?null:d.configFilePath,ne=Pk(w,ee,[d.lastWarning??``,...b].filter(Boolean).join(`
209
- `)),re=gz.sync(s,ne===null?null:Ik(ne));re!==null&&Z(`warn`,`diagnostic dump failed: ${re}`);let ie=Lk(S,ne,{fullText:re===null?{kind:`file`,path:gz.pathFor(s)}:{kind:`unavailable`,reason:re},failedConfigFile:te},{width:m,rowCap:h,colorCompatibility:v.colorCompatibility}),T=Date.now()-t,E=uz.getStats(),ae=dz.getStats();return Z(`info`,`render sid=${e.hookData.session_id??`?`} took=${T}ms termCols=${p??`?`} termRows=${c.termRows??`?`} width=${m} git=${E.size}/${E.hits}h/${E.misses}m usage=${ae.size}/${ae.hits}h/${ae.misses}m err=${w?`Y`:`N`} upd=${ee.length} warn=${d.lastWarning?`Y`:`N`}`),Lz({ok:!0,output:ie+`
210
- `})}catch(e){throw oz.requestsErrored++,e}}if(e.kind===`click`)return Lz(Gz(e.verb,e.value,DE(e.clientVersion)));if(e.kind===`debug`){if(!rz(e.what))return Lz({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${nz.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=_z.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?Uz(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):Hz};return Lz({ok:!0,debug:GR(e.what,n)})}return Lz({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function zz(e){let{values:t,tokens:n}=v({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=[...new Set((n??[]).filter(e=>e.kind===`option`&&e.name!==`config`).map(e=>`--${e.name}`))];return{configFile:SE(t.config),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}const Bz={sessionState:pz,dlog:Z,applyUpdate:()=>xz.act(),doctor:eL(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];_z.reload(...t);let n=_z.getOrCreate(...t);return{path:n.configFilePath,error:n.lastError,warning:n.lastWarning,unused:n.state.unused}}),probes:sz,memento:fz,claudeInput:IL(),history:mz,navigation:hz,configFor:e=>_z.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>_z.reload(e.projectDir,e.cwd,e.configFile??void 0)};Bz.reloadConfig;const Vz={endcaps:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:_o,width:1/0},Hz=new Map;function Uz(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,Ok(a,{...Vz,charset:t,colorCompatibility:n}));return r}const Wz={...lz,clock:()=>new Date,history:e=>mz.depth(e)};function Gz(e,t,n){let r=LR.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return r(t,{...Bz,clientVersion:n}),{ok:!0,output:``}}catch(e){let t=e instanceof $?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}const Kz={connectMs:200,budgetMs:500};async function qz(e,n){let r=n.includes(`--json`),i=await Jz(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${RE(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
211
- `);return}t.stdout.write(Yz(i.value))}function Jz(e){return ME({kind:`debug`,what:e},Kz,e=>`debug`in e?e.debug:void 0)}function Yz(e){switch(e.what){case`vars`:return Xz(e.vars);case`segments`:return Zz(e.segments);case`config`:return Qz(e.config);default:return e}}function Xz(e){if(e.length===0)return`no variables (DSL not active)
212
- `;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${eB(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${$z(a.value)}${e}${o}`)}return t.join(`
204
+ `}const vL=e=>({kind:`ok`,value:e}),yL=e=>({kind:`failed`,reason:e});var bL=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const xL=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function SL(e){return xL.test(e)?e:null}function CL(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return vL(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return vL({app:n,missing:yL(`its script could not be read (${r.reason})`)});let i=jO(r.value);return vL({app:n,missing:i===null?yL("its script is not one `cc-candybar install` wrote"):vL([i.node,i.script].filter(t=>!e.exists(t)))})}async function wL(e,t){let n=e.now()+5e3;for(;e.now()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,handler:r.handler,bar:n.value.version}}return null}async function TL(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${AD}://${$D}/${n}`);return(r===null?await wL(e,n):null)??{kind:`lost`,unopened:r,opener:CL(e)}}function EL(e,t,n){let r=Ae({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?vL(r.stdout):yL(r.stderr.trim()||r.error||r.reason)}const DL=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${AD}://probe"));u.isNil() ? "" : u.path.js`;async function OL(){let e=await pL();if(e.kind!==`ok`)return yL(VE(e).split(`
205
+ `).join(` — `));let{version:t,handlerProbes:n}=e.value;return Array.isArray(n)?vL({version:t,arrivals:n}):yL(`the running daemon (${t}) predates this check`)}function kL(){return{platform:process.platform,sockets:{own:Le(),handler:Re()},now:Date.now,nonce:se,daemon:OL,open:e=>{let t=EL(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=EL(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,DL]);if(e.kind===`failed`)return e;let t=e.value.trim();return vL(t===``?null:t)},script:e=>EL(`doctor.osadecompile`,`/usr/bin/osadecompile`,[MO(e)]),exists:r.existsSync}}const AL=/^─{20,}/,jL=/^❯(\s|$)/,ML=/›\s*stashed$/;function NL(e){if(e.inMode)return{kind:`in-mode`};let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>AL.test(e)?[t]:[]).at(-2);return n===void 0||!jL.test(t[n+1]??``)?{kind:`no-prompt`}:ML.test(t[n-1]??``)?{kind:`stashed`}:{kind:`ready`}}const PL={"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 FL(e,t,n){if(t===void 0)return{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`};if(t===null)return{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only type into a tmux pane`};let r=NL(e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:PL[r.kind]};let i=e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}const IL=`cc-candybar-slash`;function LL(e,t,n,r){let i=yN(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function RL(e){let t=LL(e,`claude-input.read`,[`display`,`-p`,`-t`,e.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,e.pane]);if(t.kind===`rate-limited`)throw Error(t.reason);let[n=``,...r]=t.stdout.split(`
206
+ `);return{inMode:n!==`0`,screen:r}}function zL(e,t){let n=LL(e,`claude-input.type`,[`load-buffer`,`-b`,IL,`-`,`;`,`send-keys`,`-t`,e.pane,`C-s`,`;`,`paste-buffer`,`-p`,`-d`,`-b`,IL,`-t`,e.pane,`;`,`send-keys`,`-t`,e.pane,`Enter`],t);return n.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${n.reason})`}}function BL(){return{read:RL,type:zL}}function VL(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function HL(e){return UL(()=>decodeURIComponent(e))}function UL(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function WL(e,t){let n=Ae({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const GL=(e,t)=>WL(HL(e),t),KL=(e,t)=>{let n=Ae({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,HL(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},qL=(e,t)=>WL(HL(e),t),JL=(e,t)=>WL(HL(e),t),YL=(e,t)=>{let n=VL(HL(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},XL=(e,t)=>{let[n=``,...r]=UL(()=>rO(e)),i=VL(n),a=sM(cR(t,i));if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new $(`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 $(`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 $(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}eR(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},ZL=/^-?\d+$/;function QL(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const $L=(e,t)=>{let[n=``,r=``,i=``]=UL(()=>rO(e)),a=VL(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!ZL.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=cR(t,a),c=sM(s),l=c.rangeParamsFor(r);if(!l)throw new $(`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&&ZL.test(u)?tR(l,parseInt(u,10)):nR(`step-state`,r,l,uM(s,e=>t.sessionState.get(a,e),r)),f=QL(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new $(`step-state: ${p.reason}`);eR(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function eR(e,t,n,r){let i=r.filter(e=>e.key.startsWith(tv));if(i.length===0)return;let a=Hj(cR(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new $(`${n}: refused — ${a.join(`; `)}`)}function tR(e,t){return Math.max(e.min,Math.min(e.max,t))}function nR(e,t,n,r){if(r===null)return n.min;if(!ZL.test(r))throw new $(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return tR(n,parseInt(r,10))}const rR=`render-origin`;function iR(e){return JSON.stringify(e)}function aR(e){let t;try{t=JSON.parse(e)}catch{throw new $(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new $(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new $(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function oR(e,t){let n=e.sessionState.get(t,rR);if(n===null)throw new $(`session ${t} has not rendered yet — no config to act on`);return aR(n)}function sR(e,t,n){let r=e.sessionState.get(t,rR);if(r===null)return;let i=aR(r),a=lR(i);n.some(e=>e.kind===`file`&&e.file===a)&&e.reloadConfig(i)}function cR(e,t){return e.configFor(oR(e,t))}function lR(e){return sE(e.projectDir,e.cwd,e.configFile??void 0)}function uR(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const dR=(e,t)=>{let[n=``,r=``,i=``]=UL(()=>rO(e)),a=VL(n),o=oR(t,a),s=t.configFor(o),c=mA(s);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new $(`set-config: ${l.reason}`);let u=lR(o),d=Bj(s,e=>t.sessionState.get(a,e),r);gI(uR(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u} (session=${a})`)},fR=(e,t)=>{let[n=``,r=``,i=``]=UL(()=>rO(e)),a=VL(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!ZL.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=oR(t,a),c=t.configFor(s),l=mA(c),u=l.rangeParamsFor(r);if(!u)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=lR(s),f=Bj(c,e=>t.sessionState.get(a,e),r),p=hI(d,f.key),m=typeof p==`number`?tR(u,p):nR(`step-config`,r,u,gA(f.globals,r)),h=QL(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new $(`step-config: ${g.reason}`);gI(uR(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.dlog(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d} (session=${a})`)},pR=(e,t)=>{let[n=``]=UL(()=>rO(e)),r=VL(n),i=oR(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=Rj(a,o),c=Vj(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=sM(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new $(`save: ${t.reason}`);return[e.target,t.value]});hR(`save`,l,c);let d=lR(i);_I(uR(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.dlog(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(mR)].join(` `)} → ${d} (session=${r})`)},mR=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Js(e.value)}`;function hR(e,t,n){for(let r of n){let n=t.validate(r.key,Js(r.value));if(!n.ok)throw new $(`${e}: ${n.reason}`)}}const gR=(e,t)=>{let[n=``]=UL(()=>rO(e)),r=VL(n),i=oR(t,r),a=t.configFor(i),o=Gj(a,e=>t.sessionState.get(r,e)),s=sM(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new $(`save-preset: ${t.reason}`);return[e.configKey,t.value]});hR(`save-preset`,s,o.placements);let l=lR(i),u=CI(uR(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Bb.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,zb.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(mR)].join(` `)} → ${l} (session=${r})`)},_R=(e,t)=>{let[n=``,r=``]=UL(()=>rO(e)),i=VL(n);if(!r)throw new $(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=oR(t,i),o=lR(a);wI(uR(t,i),o,r),t.reloadConfig(a);let s=zb.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o} (session=${i})`)},vR=(e,t)=>{let[n=``,...r]=UL(()=>rO(e)),i=VL(n),a=oR(t,i),o=mA(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new $(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=lR(a),l=r.map(Kj),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);xI(uR(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.dlog(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c} (session=${i})`)};function yR(e,t){let n=(e,t)=>[...Ps(P_(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(j_(t.presets).flatMap(e=>n(t,e).map(t=>nv(Su(e),As(t)))));return j_(e.presets).flatMap(t=>n(e,t).map(e=>({member:nv(Su(t),As(e)),node:e})).filter(({member:e})=>!r.has(e)))}function bR(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[X_]:[]])}const xR=(e,t)=>{let[n=``,r=``,i=``]=UL(()=>rO(e)),a=VL(n),o=oR(t,a),s=t.configFor(o),c=mA(s);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new $(`apply-layout-op: ${l.reason}`);let u=eA(l.value);if(u===null)throw new $(`apply-layout-op: "${l.value}" is not a layout op token`);let d=lR(o),f=TI(uR(t,a),d,r,u);t.reloadConfig(o);let p=bR(yR(s,t.configFor(o)),t.sessionState.get(a,X_)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.dlog(`info`,`apply-layout-op: ${r} ${l.value} → ${d} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},SR=(e,t)=>{let[n=``]=UL(()=>rO(e)),r=VL(n);t.journal.commit();let i=t.history.undo(r);sR(t,r,i),t.dlog(`info`,`undo: restored ${qI(i)} (session=${r})`)},CR=(e,t)=>{let n=VL(HL(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,sM(cR(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},wR=(e,t)=>{let n=VL(HL(e));t.journal.commit();let r=t.history.rewind(n);sR(t,n,r),t.dlog(`info`,`rewind: put back ${qI(r)||`nothing`} as edit mode found it (session=${n})`)},TR=(e,t)=>{let[n=``]=UL(()=>rO(e)),r=VL(n);t.journal.commit();let i=t.history.redo(r);sR(t,r,i),t.dlog(`info`,`redo: re-applied ${qI(i)} (session=${r})`)},ER=(e,t)=>{VL(HL(e)),t.applyUpdate()},DR=`client-hints`;function OR(e,t){let n=e.sessionState.get(t,DR);if(n===null)throw new $(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new $(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new $(`client hints record is not an object: ${n}`);return SE(r)}function kR(e,t,n){let r=Yx(n);e.sessionState.setBatch(t,eS(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} (session=${t})`)}function AR(e,t){return{...lL(e.doctor,OR(e,t),oR(e,t)),urlHandler:cL(e.clientVersion)}}const jR=(e,t)=>{let n=VL(HL(e));kR(t,n,AR(t,n))},MR=(e,t)=>{let n=SL(HL(e));if(n===null)throw new $(`doctor-probe: the value is not a probe nonce`);t.probes.arrive({nonce:n,handler:t.clientVersion}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${t.clientVersion??`unreported`}`)},NR=(e,t)=>{let[n=``,r=``]=UL(()=>rO(e)),i=VL(n),a=Xx(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=AR(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new $(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=uL(s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.name}=${s.fix.value} (session=${i})`),kR(t,i,c)},PR=(e,t)=>{let[n=``,...r]=UL(()=>rO(e)),i=VL(n),a=oR(t,i),o=Object.values(t.configFor(a).actions).filter(e=>`ceiling`in e).find(e=>{let t=jw(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(o===void 0)throw new $(`ceiling: "${r.join(` `)}" is not a move this config declares`);let s=o.ceiling===`set`?{kind:`set`,to:o.to}:{kind:`clear`},c=KA({sessionId:i,projectDir:a.projectDir,cwd:a.cwd},OR(t,i));t.memento.move(c,s),t.dlog(`info`,`ceiling: ${r.join(` `)} (session=${i} claudeConfigDir=${c.claudeConfigDir})`)},FR=(e,t)=>{let[n=``,r=``]=UL(()=>rO(e)),i=VL(n),a=Object.values(t.configFor(oR(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new $(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=FL(t.claudeInput,OR(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new $(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)},IR=`config-override`,LR=new Map([[PD,GL],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=VL(UL(()=>decodeURIComponent(e.slice(0,n)))),i=UL(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new $(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new $(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,IR),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,IR,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[FD,KL],[MD,XL],[ND,$L],[zD,dR],[BD,fR],[WD,vR],[VD,pR],[HD,gR],[UD,_R],[GD,xR],[KD,SR],[qD,TR],[JD,CR],[YD,wR],[LD,qL],[RD,JL],[ID,YL],[XD,ER],[ZD,jR],[QD,NR],[$D,MR],[eO,PR],[tO,FR]]),RR=new Set([MD,ND,zD,BD,WD,VD,HD,UD,GD,KD,qD,JD,YD,ID,XD,ZD,QD,eO,tO]),zR=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of sO(aO(e))){if(!i&&RR.has(a)){let e=rO(o);e.length>0&&e[0]&&(i=e[0])}let e=LR.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof $||(r=!0),n.push(`${a}: ${e instanceof Error?e.message:String(e)}`)}}if(n.length>0){i&&t.sessionState.set(i,`click.error`,n.join(`
207
+ `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}};function BR(e){return(t,n)=>{let r=n.history.begin(),i=n.navigation.begin(r.sessionState),a=[];try{e(t,{...n,sessionState:r.sessionState,journal:r,navigating:i.sessionState})}catch(e){a.push(e)}i.commit();try{r.commit()}catch(e){a.push(e)}if(a.length===1)throw a[0];if(a.length>1)throw Error(a.map(e=>String(e.message??e)).join(`; `))}}const VR=new Map([...LR,[jD,zR]].map(([e,t])=>[e,BR(t)]));Object.freeze([...VR.keys()]);const HR=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`]),UR=[[`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`]],WR=[[`workspace.added_dirs`,`string-list`]];function GR(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of UR){let i=JR(n,e);if(i==null)t.missingRequired.push(e);else{let n=KR(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of WR){let i=JR(n,e),a=i===void 0?r:qR(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))HR.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function KR(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function qR(e){return Array.isArray(e)&&e.every(e=>KR(e)===`string`)?`string-list`:KR(e)}function JR(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 YR(e,t){switch(e){case`vars`:return{what:e,vars:XR(t)};case`segments`:return{what:e,segments:tz(t)};case`config`:return{what:e,config:az(t)}}}function XR(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=$R(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...ZR(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:QR(r.lastUpdatedMs())})}return o}function ZR(e){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`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function QR(e){return e===null?null:Math.max(0,Date.now()-e)}function $R(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,ez(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}`,ez(i));return t}function ez(e){return e.kind}function tz(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=rz(n),o=nz(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:iz(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function nz(e){let t=new Map;for(let n of j_(e.presets))for(let r of Ps(P_(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=As(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function rz(e){let t=[],n=new Set;for(let r of Ps(Lc(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 iz(e,t,n){let r=new Set;for(let i of xv(e,t).keys()){if(n.has(i)){r.add(i);continue}let e=i.split(`.`);for(;e.length>1;){e.pop();let t=e.join(`.`);if(n.has(t)){r.add(t);break}}}return Array.from(r).sort()}function az(e){return e===null?null:e.config}const oz=[`vars`,`segments`,`config`];function sz(e){return typeof e==`string`&&oz.includes(e)}function cz(e){return Math.max(1,e-2)}var lz=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return c.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t){let n=this.pathFor(e);if(t===(this.written.get(e)??null))return null;try{return t===null?(r.rmSync(n,{force:!0}),this.written.delete(e)):(r.mkdirSync(this.dir,{recursive:!0,mode:448}),r.writeFileSync(n,t,{mode:384}),this.written.set(e,t)),null}catch(e){return`${n}: ${e.message}`}}reset(){this.written.clear();try{return r.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};const uz=new jF,dz=new bL;De(uz.launchStats);const fz=new ob({counters:uz,logger:Z}),pz=TN({watchers:fz,logger:Z}),{gitProvider:mz,usageStore:hz,mementoProvider:gz}=pz,_z=new FF,vz=new NI(_z,Z),yz=new nL,bz=new lz(Ye()),xz=new kF({gitService:mz,sessionState:_z,watchers:fz},{observers:{onReload:e=>Z(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} file=${e.configFilePath??`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),Sz=60*1e3;function Cz(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(T(e)),t.argv[1]&&n.push(t.argv[1]);let i=new Map;for(let e of n)try{i.set(e,r.statSync(e).mtimeMs)}catch{}let a=null,o=()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){Z(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),zz(0);return}}catch(e){Z(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,Sz),a.unref())},checkNow:o}}const wz=Cz(),Tz=kM({entryUrl:import.meta.url,intervalMs:Sz,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>wz.checkNow(),log:Z});let Ez=null,Dz=null,Oz=0;function kz(){t.on(`uncaughtException`,e=>{Z(`error`,`uncaughtException: ${e.stack||e.message}`),zz(1)}),t.on(`unhandledRejection`,e=>{Z(`error`,`unhandledRejection: ${String(e)}`),zz(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Z(`info`,`received ${e}, shutting down`),zz(0)});try{Oz=rD(t.env)}catch(e){Z(`error`,`refusing to boot: ${e.message}`),zz(1);return}Ez=rk(t.pid);let e=pk(hk(Ez));if(!e.decision.allow){Z(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),zz(1);return}Dz=e.registryPath,r.mkdirSync(Ie(),{recursive:!0}),Be(Le()),_z.useStorage(new LF(Ue(),500,Z)),vz.useStorage(eL(We(),Z)),ok({anchor:ak(t.env),isAlive:sk,onOrphaned:e=>{Z(`info`,`parent watchdog: ${e}; shutting down`),zz(0)}}),Az(b.createServer({allowHalfOpen:!1},e=>{Bz(e)}),Le(),!1)}function Az(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Z(`error`,`server error: ${i.message}`),zz(1);return}if(r){Z(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}jz(e,n)}),e.listen(n,()=>Mz(n))}function jz(e,n){let i=qO(JO(Ve(n)),(e,t)=>nk(e,t,{readStartTime:tk,pidAlive:sk}));if(i.kind===`attach-and-exit`){Z(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}Z(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){Z(`error`,`cannot unlink stale socket ${n}: ${e.message}`),zz(1);return}}Az(e,n,!0)}function Mz(e){let n=ZO(e);if(n.kind!==`present`){Z(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),zz(0);return}Iz(e);try{r.chmodSync(e,384)}catch(e){Z(`warn`,`chmod socket failed: ${e.message}`)}Z(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(ne.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(Oz/1048576)}MB`),bD();let i=bz.reset();i!==null&&Z(`warn`,`diagnostic dump wipe failed: ${i}`),wz.arm(),Tz.arm(),Fz(),Nz(e,n.identity)}function Nz(e,n){ek({bound:n,myPid:t.pid,readIdentity:()=>ZO(e),readLease:()=>JO(Ve(e)),shutdown:e=>zz(e),log:Z}).arm()}let Pz=null;function Fz(){Pz=sD(dD(uz.startedAt.getTime(),e=>zz(e),{rssLimitBytes:Oz})),Pz.arm()}function Iz(e){let n=YO(Ve(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:Ez});n!==null&&Z(`warn`,`lease write failed: ${n}`)}let Lz=0,Rz=!1;function zz(e){if(!Rz){Rz=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{mz.close()}catch(e){Z(`warn`,`gitService close failed: ${e.message}`)}try{hz.close()}catch(e){Z(`warn`,`usageStore close failed: ${e.message}`)}try{fz.closeAll()}catch(e){Z(`warn`,`watcherRegistry close failed: ${e.message}`)}try{_z.flush()}catch(e){Z(`warn`,`sessionState flush failed: ${e.message}`)}XO(He(),t.pid),Dz!==null&&mk(Dz,t.pid,dk,e=>r.unlinkSync(e)),t.exit(e)}}function Bz(e){Lz++,uz.inFlight=Lz;let t=!1,n=(n,r)=>{if(t){r!==null&&Z(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>zz(r);try{e.end(ME(n),i)}catch(e){Z(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{uz.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=NE(e=>{Hz(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{Z(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{Z(`warn`,`frame parse failed: ${e.message}`),n({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null)});e.on(`data`,i),e.on(`error`,e=>{Z(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),Lz=Math.max(0,Lz-1),uz.inFlight=Lz})}const Vz=e=>({resp:e,exitAfterFlush:null});async function Hz(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return Vz({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?Z(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):Z(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null};if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0};if(e.kind===`stats`)return Vz({ok:!0,stats:uz.snapshot({gitCache:mz.getStats(),usageCache:hz.getStats(),renderCacheSize:xz.size,watchersActive:fz.size(),nextRestartReason:Pz?.describeNextRestart()??null,handlerProbes:dz.list()})});if(e.kind===`render`){uz.requestsTotal++;let t=Date.now();try{let{report:n}=GR(e.hookData);for(let e of n.unknownTopLevelFields)Z(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let r=[];for(let e of n.missingRequired)r.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:i}of n.typeMismatches)r.push(`field '${e}' expected ${t}, got ${i}`);if(e.cwd===``&&r.push(`request 'cwd' is empty`),r.length>0)return uz.requestsErrored++,Z(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),Vz({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=Uz(e.args),s=e.hookData.session_id,c=SE(e),l=JSON.stringify(c);_z.get(s,`client-hints`)!==l&&_z.set(s,DR,l);let u=_z.get(s,`config-override`)??a??c.configEnv,d=xz.getOrCreate(i,e.cwd,u),f=iR({projectDir:i,cwd:e.cwd,configFile:u??null});_z.get(s,`render-origin`)!==f&&_z.set(s,rR,f);let p=c.termCols,m=cz(p??120),h=Mk(c.termRows),{authoredRoots:g}=d.state,_=t=>_z.get(e.hookData.session_id,t),v=aj(d.state.config,_,e=>g.has(e)),y=await Sj(e.hookData,{...Jz,navigation:e=>yz.depth(e,_z,sM(d.state.config))},e.cwd,d.state.neededInputPaths(v.preset),v,c,{...Jj(d.state.config,d.state.fileHeldSettings,_),configPath:d.configFilePath}),b=[],x=oj(v,m),S=lF(d.state.config,d.state.compiled,d.state.store,d.state.registry,y,x,{perSegmentSink:d.state.lastRenderCellsBySegment,onRenderWarning:e=>b.push(e)},sj(v)),C=_z.get(e.hookData.session_id,`click.error`);C&&_z.clear(e.hookData.session_id,`click.error`);let w=[o,d.lastError,C].filter(Boolean).join(`
208
+ `),ee=Tz.notice({sessionId:s,dismissed:_z.get(s,pM),enabled:v.updateNotice}),te=d.lastError===null?null:d.configFilePath,ne=Lk(w,ee,[d.lastWarning??``,...b].filter(Boolean).join(`
209
+ `)),re=bz.sync(s,ne===null?null:zk(ne));re!==null&&Z(`warn`,`diagnostic dump failed: ${re}`);let ie=Bk(S,ne,{fullText:re===null?{kind:`file`,path:bz.pathFor(s)}:{kind:`unavailable`,reason:re},failedConfigFile:te},{width:m,rowCap:h,colorCompatibility:v.colorCompatibility}),T=Date.now()-t,E=mz.getStats(),ae=hz.getStats();return Z(`info`,`render sid=${e.hookData.session_id??`?`} took=${T}ms termCols=${p??`?`} termRows=${c.termRows??`?`} width=${m} git=${E.size}/${E.hits}h/${E.misses}m usage=${ae.size}/${ae.hits}h/${ae.misses}m err=${w?`Y`:`N`} upd=${ee.length} warn=${d.lastWarning?`Y`:`N`}`),Vz({ok:!0,output:ie+`
210
+ `})}catch(e){throw uz.requestsErrored++,e}}if(e.kind===`click`)return Vz(Yz(e.verb,e.value,AE(e.clientVersion)));if(e.kind===`debug`){if(!sz(e.what))return Vz({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${oz.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=xz.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?qz(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):Kz};return Vz({ok:!0,debug:YR(e.what,n)})}return Vz({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function Uz(e){let{values:t,tokens:n}=v({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=[...new Set((n??[]).filter(e=>e.kind===`option`&&e.name!==`config`).map(e=>`--${e.name}`))];return{configFile:TE(t.config),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}const Wz={sessionState:_z,dlog:Z,applyUpdate:()=>Tz.act(),doctor:iL(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];xz.reload(...t);let n=xz.getOrCreate(...t);return{path:n.configFilePath,error:n.lastError,warning:n.lastWarning,unused:n.state.unused}}),probes:dz,memento:gz,claudeInput:BL(),history:vz,navigation:yz,configFor:e=>xz.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>xz.reload(e.projectDir,e.cwd,e.configFile??void 0)};Wz.reloadConfig;const Gz={endcaps:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:_o,width:1/0},Kz=new Map;function qz(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,jk(a,{...Gz,charset:t,colorCompatibility:n}));return r}const Jz={...pz,clock:()=>new Date,history:e=>vz.depth(e)};function Yz(e,t,n){let r=VR.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return r(t,{...Wz,clientVersion:n}),{ok:!0,output:``}}catch(e){let t=e instanceof $?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}const Xz={connectMs:200,budgetMs:500};async function Zz(e,n){let r=n.includes(`--json`),i=await Qz(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${VE(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
211
+ `);return}t.stdout.write($z(i.value))}function Qz(e){return FE({kind:`debug`,what:e},Xz,e=>`debug`in e?e.debug:void 0)}function $z(e){switch(e.what){case`vars`:return eB(e.vars);case`segments`:return tB(e.segments);case`config`:return nB(e.config);default:return e}}function eB(e){if(e.length===0)return`no variables (DSL not active)
212
+ `;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${iB(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${rB(a.value)}${e}${o}`)}return t.join(`
213
213
  `)+`
214
- `}function Zz(e){if(e.length===0)return`no segments (DSL not active)
214
+ `}function tB(e){if(e.length===0)return`no segments (DSL not active)
215
215
  `;let t=[`segments (${e.length})`,``];for(let n of e){t.push(` ${n.name}`),n.description!==null&&t.push(` shows ${n.description}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`);for(let{id:e,lastRender:r}of n.placements)r!==null&&t.push(` last ${e}: ${r}`)}return t.join(`
216
216
  `)+`
217
- `}function Qz(e){return e===null?`config: DSL not active
217
+ `}function nB(e){return e===null?`config: DSL not active
218
218
  `:JSON.stringify(e,null,2)+`
219
- `}function $z(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function eB(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function tB(){let e=rB();return e===null?null:r.readFileSync(e,`utf-8`)}function nB(){let e;try{e=tB()}catch(e){t.stderr.write(`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`),t.exit(2)}e===null&&(t.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),t.exit(2)),t.stdout.write(e),t.exit(0)}function rB(){let e=c.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let i=c.dirname(c.resolve(n));for(;;){let t=c.join(i,e);if(r.existsSync(t))return t;let n=c.dirname(i);if(n===i)return null;i=n}}function iB(e){let t=e.CC_CANDYBAR_CONFIG??``;return t===``?void 0:t}const aB=5e3;function oB(e,t){let n=`/home/tester`,r=Math.floor(Date.now()/1e3),i=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,a={current_dir:`${n}/code/cc-candybar/src`,project_dir:`${n}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:i,version:`1.15.0`,home:n,cwd:`${n}/code/cc-candybar/src`,transcript_path:`${n}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:a,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:r+2*3600},weekly:{percentage:21,resetsAt:r+5*86400},cache:{expiresAt:r+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:CS(4e5,1e6),...aj(e),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:Gb(()=>!0),resumeCommand:tj(a,i,void 0),configPath:t??`${n}/.config/cc-candybar/config.json5`}}function sB(e,t){let n=rE(e,e),r=aE(n);return r!==null&&t.push(r),n.kind===`file`?n.path:null}async function cB(e,n=t.cwd()){let i=[],a=e===void 0?sB(n,i):c.resolve(eE(e));if(e!==void 0&&a!==null){let e;try{e=r.statSync(a,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:a,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:a,message:`not a file`}}let o=cE(n,n);o!==null&&i.push(o);try{return{kind:`clean`,configPath:a,warnings:i,rendered:await dB(a,n,i)}}catch(e){let t=e;return a!==null&&typeof t==`object`&&t&&typeof t.code==`string`&&t.path===a&&typeof t.message==`string`?{kind:`unreadable`,path:a,message:t.message}:(e instanceof Cs&&i.push(...e.warnings),{kind:`fatal`,configPath:a,message:e instanceof Cs||e instanceof Error?e.message:String(e),warnings:i})}}async function lB(e,t,n){let r=lE(e,DA);n.push(...r.warnings);let i=fE(r,e??`<default>`),a=new vF,o=new Ib(a,i.globals.default_empty_value??``,void 0,new MF);try{let r=tF(i,o,{cwd:t});n.push(...r.loadWarnings);let s=await o.settled(aB);return s.length>0&&n.push(`source${s.length===1?``:`s`} still running after ${aB} ms, rendered with fallback values: ${s.join(`, `)}`),{configPath:e,config:i,compiled:r,store:a,registry:o}}catch(e){throw o.dispose(),e}}function uB({configPath:e,config:t,compiled:n,store:r,registry:i},a,o){let s=new Map;return{rendered:oF(t,n,r,i,oB(a,e),rj(a,o),{onSegmentError:(e,t)=>s.set(`segment "${e}"`,t),onRenderWarning:e=>s.set(`theme rule`,e)},ij(a)),failures:s}}async function dB(e,t,n){let r=await lB(e,t,n),{config:i}=r;try{let e=TM();try{iM(i),dA(i)}finally{e()}let t=M_(null,i.globals.preset,i.presets),n=(e,t)=>{let n=nj(i,t=>t===`preset`?e:null,()=>t),a;try{a=uB(r,n,200)}catch(e){a={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]])}}return{preset:e,customized:t,...a}},a=n(t,!1),o=[a,n(t,!0),...j_(i.presets).filter(e=>e!==t).flatMap(e=>[n(e,!1),n(e,!0)])],s=new Map;for(let{preset:e,customized:t,failures:n}of o)for(let[r,i]of n){let n=`${r}: ${i}`,a=s.get(n)??new Map;a.set(e,(a.get(e)??new Set).add(t)),s.set(n,a)}let c=[...s].map(([e,n])=>n.get(t)?.has(!1)?e:`${e} (under ${[...n].map(([e,n])=>[...e===t?[]:[`preset "${e}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`),l=a.rendered;if(c.length>0||l===void 0)throw Error(`config renders with ${c.length} render error${c.length===1?``:`s`} (the daemon would show them on the bar):\n`+c.map(e=>` ${e}`).join(`
220
- `));return l}finally{r.registry.dispose()}}function fB(e){return e.map(e=>`warning: ${e}\n`).join(``)}function pB(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.configPath??`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${e.rendered}\n`:``),stderr:fB(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:fB(e.warnings)+`✗ ${e.configPath??`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const mB=`--render`,hB=`Usage: cc-candybar check [${mB}] [config-file]\n`;function gB(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==mB);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${hB}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${hB}`}:{kind:`run`,target:n[0],render:t.includes(mB)}}async function _B(e){let n=gB(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:pB(await cB(n.target??iB(t.env)),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const vB=`${_k}${gk}`;function yB(e){return`${vB}⚠ cc-candybar: ${bB(e)}\n`}function bB(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: ${hk(e.message,60)}`;case`render_failed`:return`render failed: ${hk(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${hk(e.message,60)}`}}function xB(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
221
- `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:yB(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function SB(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 CB=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function wB(e,t,n){return{termCols:SB(e.COLUMNS,n.columns),termRows:SB(e.LINES,n.rows),ssh:CB.some(t=>(e[t]??``)!==``),tmux:Rx(e),configEnv:iB(e),claudeConfigDir:fS(e,t),mementoEnv:Qe(e,t)}}const TB=` (fix: click the settings menu (${qc} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`;function EB({check:e,verdict:t}){return t.ok?`✓ ${e.label}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:TB}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)}function DB(e){let t=TF(e.projectDir,e.cwd,e.configFile??void 0,{sessionState:new MF});return t.state?.registry.dispose(),{path:t.resolvedPath,error:t.error,warning:t.warning,unused:t.state?.unused??[]}}async function OB(e,t,n,r,i=void 0){let a;try{a={...aL(e,{tmux:Rx(n),claudeConfigDir:fS(n,r)},{projectDir:r,cwd:r,configFile:SE(i??iB(n))??null}),urlHandler:await xL(t)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let o=qx(a);return{stdout:o.map(EB).join(``),stderr:``,code:+!o.every(e=>e.verdict.ok)}}async function kB(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
219
+ `}function rB(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function iB(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function aB(){let e=sB();return e===null?null:r.readFileSync(e,`utf-8`)}function oB(){let e;try{e=aB()}catch(e){t.stderr.write(`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`),t.exit(2)}e===null&&(t.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),t.exit(2)),t.stdout.write(e),t.exit(0)}function sB(){let e=c.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let i=c.dirname(c.resolve(n));for(;;){let t=c.join(i,e);if(r.existsSync(t))return t;let n=c.dirname(i);if(n===i)return null;i=n}}function cB(e){let t=e.CC_CANDYBAR_CONFIG??``;return t===``?void 0:t}const lB=5e3;function uB(e,t){let n=`/home/tester`,r=Math.floor(Date.now()/1e3),i=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,a={current_dir:`${n}/code/cc-candybar/src`,project_dir:`${n}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:i,version:`1.15.0`,home:n,cwd:`${n}/code/cc-candybar/src`,transcript_path:`${n}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:a,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:r+2*3600},weekly:{percentage:21,resetsAt:r+5*86400},cache:{expiresAt:r+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:TS(4e5,1e6),...cj(e),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:Gb(()=>!0),resumeCommand:ij(a,i,void 0),configPath:t??`${n}/.config/cc-candybar/config.json5`}}function dB(e,t){let n=oE(e,e),r=cE(n);return r!==null&&t.push(r),n.kind===`file`?n.path:null}async function fB(e,n=t.cwd()){let i=[],a=e===void 0?dB(n,i):c.resolve(rE(e));if(e!==void 0&&a!==null){let e;try{e=r.statSync(a,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:a,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:a,message:`not a file`}}let o=dE(n,n);o!==null&&i.push(o);try{return{kind:`clean`,configPath:a,warnings:i,rendered:await hB(a,n,i)}}catch(e){let t=e;return a!==null&&typeof t==`object`&&t&&typeof t.code==`string`&&t.path===a&&typeof t.message==`string`?{kind:`unreadable`,path:a,message:t.message}:(e instanceof Cs&&i.push(...e.warnings),{kind:`fatal`,configPath:a,message:e instanceof Cs||e instanceof Error?e.message:String(e),warnings:i})}}async function pB(e,t,n){let r=fE(e,AA);n.push(...r.warnings);let i=hE(r,e??`<default>`),a=new xF,o=new Ib(a,i.globals.default_empty_value??``,void 0,new FF);try{let r=iF(i,o,{cwd:t});n.push(...r.loadWarnings);let s=await o.settled(lB);return s.length>0&&n.push(`source${s.length===1?``:`s`} still running after ${lB} ms, rendered with fallback values: ${s.join(`, `)}`),{configPath:e,config:i,compiled:r,store:a,registry:o}}catch(e){throw o.dispose(),e}}function mB({configPath:e,config:t,compiled:n,store:r,registry:i},a,o){let s=new Map;return{rendered:lF(t,n,r,i,uB(a,e),oj(a,o),{onSegmentError:(e,t)=>s.set(`segment "${e}"`,t),onRenderWarning:e=>s.set(`theme rule`,e)},sj(a)),failures:s}}async function hB(e,t,n){let r=await pB(e,t,n),{config:i}=r;try{let e=OM();try{sM(i),mA(i)}finally{e()}let t=M_(null,i.globals.preset,i.presets),n=(e,t)=>{let n=aj(i,t=>t===`preset`?e:null,()=>t),a;try{a=mB(r,n,200)}catch(e){a={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]])}}return{preset:e,customized:t,...a}},a=n(t,!1),o=[a,n(t,!0),...j_(i.presets).filter(e=>e!==t).flatMap(e=>[n(e,!1),n(e,!0)])],s=new Map;for(let{preset:e,customized:t,failures:n}of o)for(let[r,i]of n){let n=`${r}: ${i}`,a=s.get(n)??new Map;a.set(e,(a.get(e)??new Set).add(t)),s.set(n,a)}let c=[...s].map(([e,n])=>n.get(t)?.has(!1)?e:`${e} (under ${[...n].map(([e,n])=>[...e===t?[]:[`preset "${e}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`),l=a.rendered;if(c.length>0||l===void 0)throw Error(`config renders with ${c.length} render error${c.length===1?``:`s`} (the daemon would show them on the bar):\n`+c.map(e=>` ${e}`).join(`
220
+ `));return l}finally{r.registry.dispose()}}function gB(e){return e.map(e=>`warning: ${e}\n`).join(``)}function _B(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.configPath??`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${e.rendered}\n`:``),stderr:gB(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:gB(e.warnings)+`✗ ${e.configPath??`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const vB=`--render`,yB=`Usage: cc-candybar check [${vB}] [config-file]\n`;function bB(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==vB);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${yB}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${yB}`}:{kind:`run`,target:n[0],render:t.includes(vB)}}async function xB(e){let n=bB(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:_B(await fB(n.target??cB(t.env)),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const SB=`${bk}${yk}`;function CB(e){return`${SB}⚠ cc-candybar: ${wB(e)}\n`}function wB(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: ${vk(e.message,60)}`;case`render_failed`:return`render failed: ${vk(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${vk(e.message,60)}`}}function TB(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
221
+ `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:CB(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function EB(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 DB=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function OB(e,t,n){return{termCols:EB(e.COLUMNS,n.columns),termRows:EB(e.LINES,n.rows),ssh:DB.some(t=>(e[t]??``)!==``),tmux:Bx(e),configEnv:cB(e),claudeConfigDir:mS(e,t),mementoEnv:Qe(e,t)}}const kB=` (fix: click the settings menu (${qc} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`;function AB({check:e,verdict:t}){return t.ok?`✓ ${e.label}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:kB}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)}function jB(e){let t=OF(e.projectDir,e.cwd,e.configFile??void 0,{sessionState:new FF});return t.state?.registry.dispose(),{path:t.resolvedPath,error:t.error,warning:t.warning,unused:t.state?.unused??[]}}async function MB(e,t,n,r,i=void 0){let a;try{a={...lL(e,{tmux:Bx(n),claudeConfigDir:mS(n,r)},{projectDir:r,cwd:r,configFile:TE(i??cB(n))??null}),urlHandler:await TL(t)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let o=Yx(a);return{stdout:o.map(AB).join(``),stderr:``,code:+!o.every(e=>e.verdict.ok)}}async function NB(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
222
222
  Usage: cc-candybar doctor [config-file]
223
- `),t.exit(2));let n=t.cwd(),r=await OB(eL(DB),TL(),t.env,n,e[0]===void 0?void 0:c.resolve(n,eE(e[0])));t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const AB=e=>e.some(e=>t.argv.includes(e));function jB(){console.log(Fx)}async function MB(){try{AB(Nx.help)&&(jB(),t.exit(0)),AB(Nx.version)&&(console.log(`cc-candybar ${zE}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await HO(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(LO(),t.exit(0)),e===`url-handle`){await zO(t.argv[3]);return}if(e===`daemon`){Tz();return}if(e===`daemon-stats`&&(await cL(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){await _B(t.argv.slice(3));return}if(e===`schema`){nB();return}if(e===`doctor`){await kB(t.argv.slice(3));return}rz(e)&&(await qz(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
223
+ `),t.exit(2));let n=t.cwd(),r=await MB(iL(jB),kL(),t.env,n,e[0]===void 0?void 0:c.resolve(n,rE(e[0])));t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const PB=e=>e.some(e=>t.argv.includes(e));function FB(){console.log(Lx)}async function IB(){try{PB(Fx.help)&&(FB(),t.exit(0)),PB(Fx.version)&&(console.log(`cc-candybar ${HE}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await GO(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(BO(),t.exit(0)),e===`url-handle`){await HO(t.argv[3]);return}if(e===`daemon`){kz();return}if(e===`daemon-stats`&&(await fL(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){await xB(t.argv.slice(3));return}if(e===`schema`){oB();return}if(e===`doctor`){await NB(t.argv.slice(3));return}sz(e)&&(await Zz(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
224
224
 
225
225
  cc-candybar is designed to be used as a Claude Code statusLine command.
226
226
  It reads hook data from stdin and outputs formatted statusline.
@@ -229,11 +229,11 @@ Add to ~/.claude/settings.json:
229
229
  {
230
230
  "statusLine": {
231
231
  "type": "command",
232
- "command": "cc-candybar --style=powerline"
232
+ "command": "cc-candybar"
233
233
  }
234
234
  }
235
235
 
236
236
  Run with --help for more options.
237
237
 
238
238
  To test output manually:
239
- echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),t.exit(1)),O(`Working directory: ${t.cwd()}`),O(`Process args:`,t.argv);let r=await n(t.stdin);O(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),jB(),t.exit(1));let i=xB(await UE(r,t.argv,t.cwd(),wB(t.env,t.cwd(),t.stderr)));i.debug!==null&&O(i.debug),i.kick&&lD(),t.stdout.write(i.output),t.exit(0)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error generating statusline:`,n),t.exit(1)}}MB();export{};
239
+ echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),O(`Working directory: ${t.cwd()}`),O(`Process args:`,t.argv);let r=await n(t.stdin);O(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),FB(),t.exit(1));let i=TB(await KE(r,t.argv,t.cwd(),OB(t.env,t.cwd(),t.stderr)));i.debug!==null&&O(i.debug),i.kick&&fD(),t.stdout.write(i.output),t.exit(0)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error generating statusline:`,n),t.exit(1)}}IB();export{};