@promptctl/cc-candybar 1.87.0 → 1.87.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 +44 -44
  2. package/package.json +5 -5
package/dist/index.mjs CHANGED
@@ -87,14 +87,14 @@ Use 'override' annotation for methods overridden by subclass.`)}}var ra=la(0),ia
87
87
  `,1)[0]??``}function L_(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?Y:J(n)}function R_(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?J(t):Y}const z_=/^[A-Za-z]:[\\/]/;function B_(e){let t=e.trim();if(z_.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 V_(e){return B_(e)?.host||null}function H_(e){let t=V_(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}function U_(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 W_(e){return e.urls.find(e=>Y_(e)!==null)??e.urls[0]??null}function G_(e){return e.find(e=>e.name===`origin`)??e[0]??null}function K_(e){let t=G_(e);return t?W_(t):null}function q_(e){let t=G_(e);return t?t.urls.find(e=>H_(e)!==null)??W_(t):null}function J_(e){let t=(B_(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function Y_(e){let t=B_(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 X_(e){let t=K_(e);return t===null?null:Y_(t)}function Z_(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??I_(t.stderr)].filter(Boolean).join(`, `)}`)}function Q_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $_(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 ev(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(!Q_(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 tv(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(!Q_(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 nv(e){try{let t=r.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var rv=class{isGitRepo(e){try{return r.existsSync(c.join(e,`.git`))}catch{return!1}}async execGitAsync(e,t){return Te({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=L_(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=L_(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=L_(s,X_)),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 R_(F_(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async timeSinceCommit(e,t){return t.kind===`ok`?L_(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=R_(F_(`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=nv(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=F_(`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`?U_(t.value):[])}repoNameFrom(e,t){let n=K_(e);return(n===null?null:J_(n))??c.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=q_(t.value);return n===null?Y:J(n)}async execForgeAsync(e,t,n){return Te({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=H_(t);return n===`github`?Z_(`gh pr view`,await this.execForgeAsync(`gh`,[`pr`,`view`,`--json`,`number,state,url`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,ev):n===`gitlab`?Z_(`glab mr view`,await this.execForgeAsync(`glab`,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,tv):Y}isWorktree(e){try{let t=c.join(e,`.git`);return!!(r.existsSync(t)&&r.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){D(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=F_(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?J($_(t.value)):t}};const iv=(e,t)=>D(t);var av=class{slots=new Map;maxWatchers;counters;logger;closed=!1;constructor(e={}){this.maxWatchers=e.maxWatchers??128,this.counters=e.counters,this.logger=e.logger??iv}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()}},ov=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 sv=(e,t)=>D(t),cv={showSha:!0,showStashCount:!0};function lv(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function uv(e){let t=t=>{try{return r.statSync(c.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function dv(e,t){return e.head!==t.head||e.index!==t.index}function fv(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 pv=class extends rv{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new ov;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new rv,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??sv,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new av({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}|${lv(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=uv(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}`,fv(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}`,fv(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,{...cv});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,{...cv}),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=uv(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),dv(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 mv=/\r\n|\r|\n/g,hv=e=>J(e.replace(mv,` `).trim());function gv(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?X(`regex no-match`):J(n.replace(mv,` `))}}const _v=e=>{try{return J(JSON.parse(e))}catch(e){return X(`JSON parse failed: ${e.message}`)}};function vv(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function yv(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 bv=`session.id`;function xv(e,t){return{where:`output of "${e}"`,read:async()=>{let n=await Te({bin:`/bin/sh`,args:[`-c`,e],category:`user-shell`,signal:t});if(!n.ok&&n.reason===`aborted`)throw t.reason;return n.ok?J(n.stdout):X(`shell "${e}" ${n.exitCode===null?[n.reason,n.error].filter(e=>e!==void 0).join(`: `):`exited with code ${n.exitCode}`}`)}}}function Sv(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await v(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 Cv(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 wv=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Tv=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Ev=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],Dv=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function Ov(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>wv[e.getMonth()]],[`Monday`,e=>Ev[e.getDay()]],[`Jan`,e=>Tv[e.getMonth()]],[`Mon`,e=>Dv[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 kv={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function Av(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=kv[t];try{return Pv(r,e)}catch{return Fv(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return P_(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return P_(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return P_(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return P_(e.stashCount,0)}}var jv=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}},Mv=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:S(()=>{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&&(x(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())x(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function Nv(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function Pv(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`?Bg(e):t===`number`?Vg(e):Hg(e)}function Fv(e){return e===`number`?0:e===`boolean`?!1:``}var Iv=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new jv;ttlMgr=new Mv;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new ov;abort=new AbortController;drawn=Lg.observable.box(M.TRUECOLOR);drawnAt=()=>this.drawn.get();engine=A_(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 pv({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,zg(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,xv(t,this.abort.signal),vv(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,Sv(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,hv,t.default,n);case`regex`:return this.scalarPublisher(e,gv(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=Cv(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,P_(a,i))}}documentPublisher(e,t,n){let r=t===void 0?Y:J(t);return this.store.defineDocument(e,r),i=>{let a=Cv(i,_v,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=j_(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 Ov(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,Ov(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=kv[t.field],r=t.varDefault===void 0?Fv(n):Pv(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,Av(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(bv);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=Nv(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,Pv(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,Lg.reaction)(()=>{let t=j_(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,Lg.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,Pv(this.defaultEmptyValue,t))}catch{this.store.setBox(e,Fv(t))}}defaultFor(e){try{return Pv(this.defaultEmptyValue,e)}catch{return Fv(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 Lv={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[bv]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},"theme.effective":{kind:`input`,path:`theme.effective`,default:``},"look.effective":{kind:`input`,path:`look.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},"style.effective":{kind:`input`,path:`style.effective`,default:``},"progression.effective":{kind:`input`,path:`progression.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},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},Rv={theme:{configKey:`palette`,sessionKey:`theme`,effectiveVar:`theme.effective`},preset:{configKey:`preset`,sessionKey:`preset`,effectiveVar:`preset.effective`},look:{configKey:`look`,sessionKey:`look`,effectiveVar:`look.effective`},style:{configKey:`style`,sessionKey:`style`,effectiveVar:`style.effective`},progression:{configKey:`progression`,sessionKey:`progression`,effectiveVar:`progression.effective`},charset:{configKey:`charset`,sessionKey:`charset`,effectiveVar:`charset.effective`},colorCompatibility:{configKey:`colorCompatibility`,sessionKey:`colorCompatibility`,effectiveVar:`colorCompatibility.effective`},autoWrap:{configKey:`autoWrap`,sessionKey:`autoWrap`,effectiveVar:`autoWrap.effective`},padding:{configKey:`padding`,sessionKey:`padding`,effectiveVar:`padding.effective`}},zv=Object.values(Rv),Bv=new Map(zv.map(e=>[e.configKey,e.effectiveVar])),Vv=new Map(zv.map(e=>[e.sessionKey,e.effectiveVar]));function Hv(e,t,n){let r=new Set,i=e=>{for(let t of Dg(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 Qo(e))i(t.when);for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(bv);for(let t of Object.values(e.actions)){r.add(bv),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?Vv.get(t.set):void 0,n=`persist`in t?Bv.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function Uv(e,t,n){let r=Ng({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of Hv(e,t,n.helpers)){if(Mg(a,r))continue;let e=Lv[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function Wv(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function Gv(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 Kv(e){let t=new Set;for(let n of Qo(e))n.kind===`segment`&&t.add(n.name);return t}const qv=`default`,Jv={};function Yv(e){return[...new Set([qv,...Object.keys(e)])]}function Xv(e,t,n){return Ca(void 0,e,t,qv,n)}function Zv(e,t){let n={[qv]:Jv,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${qv}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function Qv(e,t){let n=Zv(e.presets,t).root??Bs;return{node:Ws(qs(n,e.root)),path:Js(n)?`presets.${t}.root`:`root`}}function $v(e,t){return{...e.globals,...Zv(e.presets,t).globals}}const ey=/^segments\.([^.]+)\.palette$/,ty=/^presets\.(.+)\.root$/,ny=/^presets\.(.+)\.globals\.([^.]+)$/;function ry(e){return`presets.${e}.root`}function iy(e,t){return`presets.${e}.globals.${t}`}function ay(e){if(Oc(e))return{scope:`globals`,field:e};let t=ey.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=ny.exec(e);if(n&&xc(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=ty.exec(e);return r?{scope:`preset-root`,preset:r[1]}:null}function oy(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 sy=`open`;function cy(e,t,n,r){let i={variable:e,key:e,member:sy};return r.variables[e]=sc(e,Qs),r.actions[e]=cc(e,sy),r.segments[e]={template:oc(e,`(?)`,`✕`),...ly(n)},rc(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 ly(e){let[t,...n]=e;return t===void 0?{}:{when:ic(t,...n)}}const uy={help:[`-h`,`--help`],version:[`-V`,`--version`]},dy=[`✚ inserts here`,`🚫 removes its segment`,`↺ resets layout`],fy=`
90
+ `).length:0)}async getRemotesAsync(e){let t=nv(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=F_(`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`?U_(t.value):[])}repoNameFrom(e,t){let n=K_(e);return(n===null?null:J_(n))??c.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=q_(t.value);return n===null?Y:J(n)}async execForgeAsync(e,t,n){return Te({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=H_(t);return n===`github`?Z_(`gh pr view`,await this.execForgeAsync(`gh`,[`pr`,`view`,`--json`,`number,state,url`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,ev):n===`gitlab`?Z_(`glab mr view`,await this.execForgeAsync(`glab`,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,tv):Y}isWorktree(e){try{let t=c.join(e,`.git`);return!!(r.existsSync(t)&&r.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){D(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=F_(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?J($_(t.value)):t}};const iv=(e,t)=>D(t);var av=class{slots=new Map;maxWatchers;counters;logger;closed=!1;constructor(e={}){this.maxWatchers=e.maxWatchers??128,this.counters=e.counters,this.logger=e.logger??iv}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()}},ov=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 sv=(e,t)=>D(t),cv={showSha:!0,showStashCount:!0};function lv(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function uv(e){let t=t=>{try{return r.statSync(c.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function dv(e,t){return e.head!==t.head||e.index!==t.index}function fv(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 pv=class extends rv{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new ov;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new rv,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??sv,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new av({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}|${lv(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=uv(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}`,fv(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}`,fv(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,{...cv});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,{...cv}),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=uv(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),dv(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 mv=/\r\n|\r|\n/g,hv=e=>J(e.replace(mv,` `).trim());function gv(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?X(`regex no-match`):J(n.replace(mv,` `))}}const _v=e=>{try{return J(JSON.parse(e))}catch(e){return X(`JSON parse failed: ${e.message}`)}};function vv(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function yv(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 bv=`session.id`;function xv(e,t){return{where:`output of "${e}"`,read:async()=>{let n=await Te({bin:`/bin/sh`,args:[`-c`,e],category:`user-shell`,signal:t});if(!n.ok&&n.reason===`aborted`)throw t.reason;return n.ok?J(n.stdout):X(`shell "${e}" ${n.exitCode===null?[n.reason,n.error].filter(e=>e!==void 0).join(`: `):`exited with code ${n.exitCode}`}`)}}}function Sv(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await v(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 Cv(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 wv=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Tv=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Ev=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],Dv=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function Ov(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>wv[e.getMonth()]],[`Monday`,e=>Ev[e.getDay()]],[`Jan`,e=>Tv[e.getMonth()]],[`Mon`,e=>Dv[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 kv={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function Av(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=kv[t];try{return Pv(r,e)}catch{return Fv(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return P_(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return P_(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return P_(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return P_(e.stashCount,0)}}var jv=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}},Mv=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:S(()=>{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&&(x(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())x(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function Nv(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function Pv(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`?Bg(e):t===`number`?Vg(e):Hg(e)}function Fv(e){return e===`number`?0:e===`boolean`?!1:``}var Iv=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new jv;ttlMgr=new Mv;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new ov;abort=new AbortController;drawn=Lg.observable.box(M.TRUECOLOR);drawnAt=()=>this.drawn.get();engine=A_(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 pv({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,zg(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,xv(t,this.abort.signal),vv(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,Sv(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,hv,t.default,n);case`regex`:return this.scalarPublisher(e,gv(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=Cv(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,P_(a,i))}}documentPublisher(e,t,n){let r=t===void 0?Y:J(t);return this.store.defineDocument(e,r),i=>{let a=Cv(i,_v,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=j_(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 Ov(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,Ov(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=kv[t.field],r=t.varDefault===void 0?Fv(n):Pv(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,Av(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(bv);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=Nv(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,Pv(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,Lg.reaction)(()=>{let t=j_(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,Lg.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,Pv(this.defaultEmptyValue,t))}catch{this.store.setBox(e,Fv(t))}}defaultFor(e){try{return Pv(this.defaultEmptyValue,e)}catch{return Fv(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 Lv={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[bv]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},"theme.effective":{kind:`input`,path:`theme.effective`,default:``},"look.effective":{kind:`input`,path:`look.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},"style.effective":{kind:`input`,path:`style.effective`,default:``},"progression.effective":{kind:`input`,path:`progression.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},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},Rv={theme:{configKey:`palette`,sessionKey:`theme`,effectiveVar:`theme.effective`},preset:{configKey:`preset`,sessionKey:`preset`,effectiveVar:`preset.effective`},look:{configKey:`look`,sessionKey:`look`,effectiveVar:`look.effective`},style:{configKey:`style`,sessionKey:`style`,effectiveVar:`style.effective`},progression:{configKey:`progression`,sessionKey:`progression`,effectiveVar:`progression.effective`},charset:{configKey:`charset`,sessionKey:`charset`,effectiveVar:`charset.effective`},colorCompatibility:{configKey:`colorCompatibility`,sessionKey:`colorCompatibility`,effectiveVar:`colorCompatibility.effective`},autoWrap:{configKey:`autoWrap`,sessionKey:`autoWrap`,effectiveVar:`autoWrap.effective`},padding:{configKey:`padding`,sessionKey:`padding`,effectiveVar:`padding.effective`}},zv=Object.values(Rv),Bv=new Map(zv.map(e=>[e.configKey,e.effectiveVar])),Vv=new Map(zv.map(e=>[e.sessionKey,e.effectiveVar])),Hv=new Map(Object.keys(Rv).map(e=>[Rv[e].sessionKey,e]));function Uv(e,t,n){let r=new Set,i=e=>{for(let t of Dg(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 Qo(e))i(t.when);for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(bv);for(let t of Object.values(e.actions)){r.add(bv),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?Vv.get(t.set):void 0,n=`persist`in t?Bv.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function Wv(e,t,n){let r=Ng({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of Uv(e,t,n.helpers)){if(Mg(a,r))continue;let e=Lv[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function Gv(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function Kv(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 qv(e){let t=new Set;for(let n of Qo(e))n.kind===`segment`&&t.add(n.name);return t}const Jv=`default`,Yv={};function Xv(e){return[...new Set([Jv,...Object.keys(e)])]}function Zv(e,t,n){return Ca(void 0,e,t,Jv,n)}function Qv(e,t){let n={[Jv]:Yv,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${Jv}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function $v(e,t){let n=Qv(e.presets,t).root??Bs;return{node:Ws(qs(n,e.root)),path:Js(n)?`presets.${t}.root`:`root`}}function ey(e,t){return{...e.globals,...Qv(e.presets,t).globals}}const ty=/^segments\.([^.]+)\.palette$/,ny=/^presets\.(.+)\.root$/,ry=/^presets\.(.+)\.globals\.([^.]+)$/;function iy(e){return`presets.${e}.root`}function ay(e,t){return`presets.${e}.globals.${t}`}function oy(e){if(Oc(e))return{scope:`globals`,field:e};let t=ty.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=ry.exec(e);if(n&&xc(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=ny.exec(e);return r?{scope:`preset-root`,preset:r[1]}:null}function sy(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 cy=`open`;function ly(e,t,n,r){let i={variable:e,key:e,member:cy};return r.variables[e]=sc(e,Qs),r.actions[e]=cc(e,cy),r.segments[e]={template:oc(e,`(?)`,`✕`),...uy(n)},rc(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 uy(e){let[t,...n]=e;return t===void 0?{}:{when:ic(t,...n)}}const dy={help:[`-h`,`--help`],version:[`-V`,`--version`]},fy=[`✚ inserts here`,`🚫 removes its segment`,`↺ resets layout`],py=`
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
- ${uy.help.join(`, `).padEnd(25)}Show this help
97
- ${uy.version.join(`, `).padEnd(25)}Print the version of this runtime (cc-candybar <version>)
96
+ ${dy.help.join(`, `).padEnd(25)}Show this help
97
+ ${dy.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
@@ -116,7 +116,7 @@ Configuration:
116
116
  failed row's [fix] to repair it (the same checks \`cc-candybar doctor\` runs).
117
117
 
118
118
  Anywhere the bar shows (?), clicking it reveals these same instructions
119
- in place. In edit mode: ${dy.join(`, `)}.
119
+ in place. In edit mode: ${fy.join(`, `)}.
120
120
 
121
121
  Subcommands:
122
122
  install One-shot setup: stages the runtime (native render
@@ -154,55 +154,55 @@ Config tooling:
154
154
  config [--json] The effective merged config. (All three query the
155
155
  running daemon; none spawn one.)
156
156
 
157
- `,py=`${_l}live`,my=[`☐ live`,`☑ live`],hy=`${_l}done`,gy={variable:py,key:py,member:`open`},_y=`and ${ac(dg)} (not ${ac(gy)})`,vy=`{{ ${_y} }}`;function yy(e,t){return`{{ if ${_y} }}${e}{{ else }}${t}{{ end }}`}const by=`{{ and ${ac(dg)} .preset.customized }}`,xy=bl;function Sy(e){return`${_l}addable.${e}`}function Cy(e){let t=Object.keys(e.segments).filter(e=>!xy(e)),n=new Map;for(let r of Yv(e.presets)){let{node:i}=Qv(e,r),a=Kv(i);n.set(Sy(r),{members:t.filter(e=>!a.has(e))})}return n}function wy(e,t,n){return n.segments[e]={template:t,when:fg},{kind:`segment`,name:e}}function Ty(e,t,n,r){let i=`${_l}${e}.remove.${ml(n)}`;return r.actions[i]={persist:t,removeSegment:n},`{{ if ${ac(dg)} }}{{ action "${i}" "🚫" }}{{ end }}`}const Ey=`${_l}label:`;function Dy(e){return e.startsWith(Ey)?e.slice(Ey.length):e.startsWith(`edit.`)?void 0:e}function Oy(e,t){let n=`${Ey}${e}`;return t.segments[n]={template:`{{ "${nc(e)}" }}`,when:vy},{kind:`segment`,name:n}}function ky(e,t,n,r,i,a,o){let s=`${_l}${e}.insert.${n}`,c=`${_l}${e}.insertSeg.${n}`;o.actions[s]={persist:t,insertSegmentFrom:r,anchor:i,relation:a};let l=Hh(s),u=Uh(c,s,void 0),d=Kh(u),f=Gh(u,l);return o.variables[u]=sc(u,Qs),o.variables[d]={kind:`state`,key:d,default:`0`},o.actions[f]=cc(u,l),o.actions[d]={set:d,int:!0},{host:c,template:`{{ $m := menu "${s}" "✚" "✕" }}{{ if ${ac({variable:u,key:u,member:l})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Qi}`}) $m }}{{ end }}`}}function Ay(e,t,n,r,i,a){let o=[],s=e.children.findIndex(e=>e.kind===`segment`&&!xy(e.name)),c=e=>Ay(e,t,n,r,i,a);for(let[l,u]of e.children.entries()){if(u.kind===`container`){o.push(c(u));continue}let d=Zo(u,c);if(xy(u.name)){o.push(d);continue}let f=e=>ky(t,n,String(a.n++),r,u.name,e,i),p=l===s?[f(`before`)]:[],m=f(`after`),h=Ty(t,n,u.name,i),g={kind:`container`,direction:`horizontal`,children:[...p.map(e=>wy(e.host,e.template,i)),{...Oy(u.name,i),trail:h},{...d,when:yy(`false`,u.when??`true`),trail:h},wy(m.host,m.template,i)]};o.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[g]}:g)}return{...e,children:o,...e.when!==void 0&&{when:yy(`true`,e.when)}}}function jy(e,t,n,r,i,a,o){let s=`${_l}${n}.resetLayout`,c=`${_l}${n}.customized`;i.actions[s]={reset:r};let l=nc(t);return i.segments[c]={template:`{{ action "${s}" "↺ ${l} customized" }}`,when:by},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[a,{kind:`segment`,name:c}]},My(e,o)]}}function My(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),My(n,t)]}:{...e,children:[...e.children,t]}}function Ny(e,t,n,r,i){let{node:a}=Qv(e,t),o=ry(t),s=Sy(t),c=ml(t);return jy(Ay(a,c,o,s,n,{n:0}),t,c,o,n,r,i)}function Py(e){let t={variables:{},actions:{},segments:{}},n=cy(`${_l}help`,dy,[dg],t);t.variables[py]=sc(py,Qs),t.actions[py]=cc(py,gy.member),t.segments[py]={template:oc(py,...my),when:fg};let r={kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:py},n]};t.segments[hy]={template:`{{ action "${lg}" "✎ done" }}`,when:fg};let i={kind:`segment`,name:hy},a={...e.presets},o=[];for(let n of Yv(e.presets)){let s=Ny(e,n,t,i,r);o.push(s),a[n]={...Zv(e.presets,n),root:s}}let s=Uv(t,o,e);return{...e,variables:{...s,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:a}}const Fy={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function Iy(e){let t=e[Fy.socket]??``,n=e[Fy.pane]??``;if(t===``||n===``)return null;let r=e[Fy.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const Ly=Fy.truecolor,Ry=[{name:`tmuxTruecolor`,label:`tmux truecolor`,probe:({tmux:e,claudeSettingsEnv: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[Ly];return typeof n==`string`&&n!==``?{ok:!1,reason:`${Ly} is set in ~/.claude/settings.json — restart Claude Code to apply`}:{ok:!1,reason:`Claude Code renders the bar in 256 colours inside tmux`,fix:{kind:`claude-settings-env`,name:Ly,value:`1`}}}}}}];function zy(e){return Ry.map(t=>({check:t,verdict:t.probe(e)}))}function By(e){return Ry.find(t=>t.name===e)}function Vy(e){let t=`settings.doctor.${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`}}function Hy(e){return e.flatMap(({check:e,verdict:t})=>{let n=Vy(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:``},{key:n.fixable,value:Ja}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:t.reason},{key:n.fixable,value:t.fix===void 0?Ja:qa}]})}const Uy={copySession:{copy:`{{ .session.id }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`}};function Wy(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}`,actions:Object.fromEntries(Object.entries(Uy).map(([t,n])=>[`${e}${t}`,n]))}}const Gy=`${vl}menu`,Ky=ug,qy=`${vl}edit`,Jy=`${vl}close`,Yy=`${vl}toolbar`,Xy=Wy(vl),Zy=`${vl}config`,Qy=`${vl}save`,$y=`${vl}unsaved`,eb=`${vl}preset.save`,tb=`${vl}preset.delete`,nb=`${vl}resetAll`,rb=`${nb}.arm`,ib=`${nb}.disarm`,ab=`armed`,ob=`disarmed`,sb=`${Gy}.toggle`,cb=`${Zy}.toggle`,lb={variable:Gy,key:Gy,member:Ky},ub={variable:Zy,key:Zy,member:Ky},db=`${vl}tools`,fb={variable:db,key:db,member:Ky},pb=[{seg:`${vl}undo`,depth:`undo`,action:{undo:!0},display:`↶ undo`},{seg:`${vl}redo`,depth:`redo`,action:{redo:!0},display:`↷ redo`}],mb=e=>`${vl}history.${e}`,hb=`${vl}doctor`,gb=`${hb}.run`,_b=e=>`${hb}.fix.${e}`,vb=e=>`${hb}.${e}`,yb=`${vl}pickers`,bb=[`{{ themePreview }}`],xb=[{name:`preset`,...Rv.preset,glyph:`▦`,domain:`presets`,beneath:[`{{ layoutPreview }}`,`{{ action "${eb}" "⊕ save as preset" }}{{ if not .preset.bundled }} {{ action "${tb}" (printf "🗑 delete %s" .${Rv.preset.effectiveVar}) }}{{ end }}`]}],Sb=[{name:`theme`,...Rv.theme,glyph:`🎨`,domain:`themes`,beneath:bb},{name:`look`,...Rv.look,glyph:`◐`,domain:`looks`,beneath:bb},{name:`style`,...Rv.style,glyph:`✦`,domain:`styles`,beneath:[]},{name:`progression`,...Rv.progression,glyph:`🎼`,domain:`progressions`,beneath:[`{{ layoutPreview }}`]},{name:`charset`,...Rv.charset,glyph:`🔣`,domain:`charsets`,beneath:[]},{name:`colorCompatibility`,...Rv.colorCompatibility,glyph:`🌈`,domain:`colorCompatibilities`,beneath:[]}],Cb={name:`wrap`,...Rv.autoWrap},wb={name:`padding`,...Rv.padding},Tb=`${vl}${Cb.name}`,Eb=`${vl}${wb.name}`,Db=[...xb,...Sb],Ob=[...Db,Cb,wb];new Set(Ob.flatMap(e=>[e.sessionKey,e.configKey]));const kb=e=>`${vl}${e}`,Ab=e=>`${vl}apply.${e}`,jb=e=>`${vl}reset.${e}`,Mb=e=>`${vl}carousel.${e}`,Nb=(e,t)=>`${Mb(e)}.${t}`,Pb=Wh(yb),Fb=e=>({variable:Pb,key:Pb,member:Hh(Ab(e.name))});function Ib(e){return rc(kb(e.name),Fb(e),{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:Mb(e.name)},...e.beneath.map((t,n)=>({kind:`segment`,name:Nb(e.name,n)}))]},`drop`)}function Lb(e){return e===Gy}function Rb(e){let t={kind:`segment`,name:Gy};if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[Rb(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 zb(e){return Bb(e)>0?e:Rb(e)}function Bb(e){let t=0;for(let n of Qo(e))n.kind===`segment`&&Lb(n.name)&&(t+=1);return t}function Vb(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&Lb(e.name)||e.opens!==void 0&&Vb(e.opens.body,!0):e.children.some(e=>Vb(e,n))}function Hb(e){return e.kind===`segment`?Lb(e.name)?rc(e.name,lb,{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:Yy},...xb.map(Ib),{kind:`segment`,name:Qy},rc(Zy,ub,{kind:`container`,direction:`horizontal`,children:[...Sb.map(Ib),{kind:`segment`,name:Tb},{kind:`segment`,name:Eb},{kind:`segment`,name:nb}]},`drop`),rc(db,fb,{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:hb},...Ry.map(e=>({kind:`segment`,name:vb(e.name)}))]},`drop`),{kind:`segment`,name:qy},...pb.map(e=>({kind:`segment`,name:e.seg}))]},`inline`):e:Ub(e)}function Ub(e){return{...e,children:e.children.map(e=>Hb(e))}}function Wb(e){let t={variables:{[Gy]:sc(Gy,Qs)},actions:{[sb]:cc(Gy,Ky),[Gy]:{do:[sb,ib]},[cb]:cc(Zy,Ky),[Zy]:{do:[cb,ib]},[db]:cc(db,Ky),[gb]:{doctor:`run`},[Jy]:{set:lb.key,to:Qs},[qy]:{do:[lg,Jy]},...Xy.actions,[Qy]:{save:!0},[eb]:{preset:`save`},[tb]:{preset:`delete`,name:`{{ .${Rv.preset.effectiveVar} }}`}},segments:{[Gy]:{template:oc(Gy,e,`❌`)},[Yy]:{template:Xy.template},[Qy]:{when:`{{ gt .${$y} 0 }}`,template:`{{ action "${Qy}" (printf "💾 save %d" .${$y}) }}`},[Zy]:{template:oc(Zy,`⚙ config ▸`,`⚙ config ▾`)},[db]:{template:oc(db,`🧰 tools ▸`,`🧰 tools ▾`)},[hb]:{template:`{{ action "${gb}" "🩺 doctor" }}`},[Tb]:{template:`{{ action "${Ab(`wrap`)}" "wrap: on" "wrap: off" }} {{ action "${jb(`wrap`)}" "↺" }}`},[Eb]:{template:`{{ action "${Ab(`padding`)}.down" "◀" }} padding {{ .${wb.effectiveVar} }} {{ action "${Ab(`padding`)}.up" "▶" }} {{ action "${jb(`padding`)}" "↺" }}`},[qy]:{template:`{{ action "${qy}" "✎ edit" "✎ done" }}`},[nb]:{template:`{{ if eq .${nb} "${ab}" }}{{ action "${nb}" "⟲ confirm reset all" }}{{ else }}{{ action "${rb}" "⟲ reset all" }}{{ end }}`}}};return t.variables[$y]={kind:`input`,path:`unsaved`,type:`number`,default:0},t.variables[Zy]=sc(Zy,Qs),t.variables[db]=sc(db,Qs),t.variables[nb]={kind:`state`,key:nb,default:ob},qb(t),Kb(t),Gb(t),t}function Gb(e){for(let t of pb){let n=mb(t.depth);e.variables[n]={kind:`input`,path:`history.${t.depth}`,type:`number`,default:0},e.actions[t.seg]=t.action,e.segments[t.seg]={when:`{{ gt .${n} 0 }}`,template:`{{ action "${t.seg}" "${t.display}" }}`}}}function Kb(e){for(let t of Ry){let n=Vy(t.name),r=_b(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[vb(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${qa}" }} {{ action "${r}" "[fix]" }}{{ end }}{{ end }}`}}}function qb(e){for(let t of Db){let n=Ab(t.name);e.actions[n]={set:t.sessionKey,from:t.domain},e.actions[jb(t.name)]={reset:t.configKey},Jb(t,e)}e.actions[Ab(Cb.name)]={set:Cb.sessionKey,cycle:[...Ya]},e.actions[jb(Cb.name)]={reset:Cb.configKey};for(let t of[-1,1])e.actions[`${Ab(wb.name)}.${t<0?`down`:`up`}`]={set:wb.sessionKey,...Xa,by:t};e.actions[jb(wb.name)]={reset:wb.configKey},e.actions[rb]={set:nb,to:ab},e.actions[ib]={set:nb,to:ob},e.actions[nb]={do:[ib,...Ob.map(e=>jb(e.name))]}}function Jb(e,t){let n=Ab(e.name),r=Fb(e),i=Gh(r.key,r.member);t.variables[r.key]=sc(r.key,Qs),t.actions[i]=cc(r.key,r.member),t.segments[kb(e.name)]={template:`${e.glyph} {{ .${e.effectiveVar} }} ${oc(i,`▸`,`▾`)} {{ action "${jb(e.name)}" "↺" }}`},t.segments[Mb(e.name)]={template:`{{ carousel "${n}" }}`},e.beneath.forEach((n,r)=>{t.segments[Nb(e.name,r)]={template:n}})}function Yb(e){e.variables[cg]=sc(cg,Qs),e.actions[lg]=cc(cg,ug)}function Xb(e){let t=Wb(e.globals.menuGlyph??`🍫`);Yb(t);let n={...e.presets},r=[];for(let t of Yv(e.presets)){let{node:i}=Qv(e,t),a=Hb(zb(i));r.push(a),n[t]={...Zv(e.presets,t),root:a}}let i=Uv(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const Zb=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`save`,`preset`,`doctor`,`do`];function Qb(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function $b(e,t){if(t===void 0)return{};if(!hs(t))return Z(e,`actions`,`actions must be an object, got ${gs(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=ex(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Z(e,t,n){e.issues.push({path:t,message:n,line:W(e.source,t.split(`.`))})}function ex(e,t,n){if(!hs(n))return Z(e,t,`${t} must be an action object, got ${gs(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let r=Zb.filter(e=>e in n);return r.length===1?tx[r[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${Zb.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const tx={set:(e,t,n)=>jx(e,t,n,`set`,Dx),persist:(e,t,n)=>jx(e,t,n,`persist`,Ox),copy:nx(`copy`),open:nx(`open`),reset:rx,undo:ax(`undo`),redo:ax(`redo`),save:ax(`save`),preset:ox,doctor:sx,do:cx};function nx(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=us(t,n,r,e);return i===null?null:{[e]:i}}}function rx(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=lx(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 ix={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,save:`it saves the session's unsaved settings`};function ax(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Z(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${ix[e]}), got ${G(r[e])}`),null)}}function ox(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${G(r)}`),null;if(r===`save`)return{preset:`save`};let a=us(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function sx(e,t,n){let r=n.doctor,i=r===`run`?[`doctor`]:[`doctor`,`check`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${i.join(`, `)}`);if(r!==`run`&&r!==`fix`)return Z(e,`${t}.doctor`,`doctor must be "run" or "fix", got ${G(r)}`),null;if(r===`run`)return{doctor:`run`};let a=n.check;return typeof a!=`string`||By(a)===void 0?(Z(e,`${t}.check`,`doctor fix must name a check (have: ${Ry.map(e=>e.name).join(`, `)}), got ${G(a)}`),null):{doctor:`fix`,check:a}}function cx(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${G(r)}`),null):{do:r}}function lx(e,t,n,r,i,a){let o=us(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Z(e,s,i),null):o.includes(`/`)?(Z(e,s,a(o)),null):o}const ux={set:`the SessionState key to write`,persist:`the config globals field to write`};function dx(e,t,n,r){let i=ux[r],a=lx(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 fx(e){return e===`set`?`set-state`:`set-config`}const px={to:Mx(`set`)},mx={to:Mx(`persist`)},hx={from:Nx(`set`)},gx={from:Nx(`persist`)},_x={min:Rx(),max:Rx(),by:Rx()},vx={int:Fx()},yx={cycle:Px(`set`)},bx={cycle:Px(`persist`)},xx={removeSegment:Ix(`removeSegment`)},Sx={insertSegment:Ix(`insertSegment`),anchor:Ix(`anchor`),relation:Lx()},Cx={insertSegmentFrom:Nx(`persist`),anchor:Ix(`anchor`),relation:Lx()},wx={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},Tx={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function Ex(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>vs(e,t,n,r),c=Ns(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?Es(s,...n):s}}const Dx=[Ex(`set`,px),Ex(`set`,hx),Ex(`set`,_x,[wx,Tx]),Ex(`set`,vx),Ex(`set`,yx)],Ox=[Ex(`persist`,mx),Ex(`persist`,gx),Ex(`persist`,_x,[wx,Tx]),Ex(`persist`,bx),Ex(`persist`,xx),Ex(`persist`,Sx,[],[`insertSegment`]),Ex(`persist`,Cx,[],[`insertSegmentFrom`])];function kx(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"styles"/"looks", 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 Ax(e){let t=kx(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 jx(e,t,n,r,i){let a=dx(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${Ax(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Z(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function Mx(e){let t=fx(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>lx(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 Nx(e){let t=fx(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${G(o)}`)}}}function Px(e){let t=fx(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Z(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${gs(o)}`);return}let c=o;if(c.length<2){Z(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Z(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Z(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Z(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function Fx(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${G(r[n])}`);return}return!0}}}function Ix(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=us(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Z(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Z(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function Lx(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${G(i)}`);return}return i}}}function Rx(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${G(i)}`);return}return i}}}const zx={noun:`look key`,fields:{hueShift:ks(),chromaScale:ks({min:0}),lightnessScale:ks(),lightnessShift:ks()}};function Bx(e,t){if(!hs(t))return e.issues.push({path:`looks`,message:`looks must be an object mapping look names to adaptation objects, got ${gs(t)}`,line:W(e.source,[`looks`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`looks.${r}`,message:`look name ${JSON.stringify(r)} must be non-empty and slash-free — a look picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:W(e.source,[`looks`,r])});continue}let t=_s(e,zx,`looks.${r}`,i);t!==null&&(n[r]={...On,...t})}return n}const Vx={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:Yl(e,`${t}.${n}`,r[n])},globals:{required:!1,json:Tc(),parse:(e,t,n,r)=>r[n]===void 0?void 0:wc(e,`${t}.${n}`,r[n])}}};function Hx(e,t){if(!hs(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${gs(t)}`,line:W(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:W(e.source,[`presets`,r])});continue}let t=_s(e,Vx,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function Ux(e,t){if(t===void 0)return{};if(!hs(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${gs(t)}`,line:W(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 ${G(i)}`,line:W(e.source,[`helpers`,r])});continue}n[r]=i}return n}const Wx=new Map,Gx=new Map;function Kx(e){let t=qx(e);if(t===null)throw Error(`Palette "${e}" (resolved "${va(e)}") did not resolve in the theme registry — allowed names and the registry are inconsistent`);return t}function qx(e){let t=va(e),n=Wx.get(t);if(n!==void 0)return n;let r=ir(t);return r===null?null:(Wx.set(t,r),r)}function Jx(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=Gx.get(n);if(r!==void 0)return r;let i=fr(e,t);return Gx.set(n,i),i}function Yx(e){let t=qx(e);return t===null?null:{kind:`decided`,name:e,value:t}}function Xx(e,t){let n=Yx(e);return n===null?(t(`globals.palette rendered "${ya}": "${e}" names no installed theme`),Qx()):n}function Zx(e,t,n){return Ea(e,t,n,Qx(),Yx)}function Qx(){return Yx(ya)}function $x(e){return Da(Zx(void 0,null,e),()=>ya,Qx).value}const eS=new Map;function tS(e,t,n){eS.set(e,{permanent:!0,resolve:t,paletteOf:n})}tS(`themes`,()=>Sa(),e=>Kx(e)),tS(`styles`,()=>Ma),tS(`progressions`,()=>Wa),tS(`charsets`,()=>Fa),tS(`colorCompatibilities`,()=>za);function nS(e){return new Map([[`looks`,{members:Object.keys(e.looks),paletteOf:(t,n)=>Jx(n,e.looks[t])}],[`presets`,{members:Yv(e.presets)}]])}function rS(e){return[...new Set([...eS.keys(),...e.keys()])]}function iS(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=eS.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf};throw Error(`unknown option domain "${e}" (have: ${rS(t).join(`, `)})`)}function aS(e,t){let n=new Map;for(let e of Object.keys(t)){let t=ml(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:W(e.source,[`presets`])})}function oS(e,t,n){t.globals.look!==void 0&&!Ta(t.globals.look)&&!Object.prototype.hasOwnProperty.call(t.looks,t.globals.look)&&e.issues.push({path:`globals.look`,message:`globals.look "${t.globals.look}" does not match any declared look (have: ${Object.keys(t.looks).join(`, `)})`,line:W(e.source,[`globals`,`look`])}),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:W(e.source,[`globals`,`preset`])}),aS(e,t.presets);let r=nS(t);for(let[n,i]of Object.entries(t.actions))!(`set`in i)||!(`from`in i)||typeof i.from!=`string`||rS(r).includes(i.from)||e.issues.push({path:`actions.${n}.from`,message:`actions.${n} from: references unknown option domain "${i.from}" (have: ${rS(r).join(`, `)})`,line:W(e.source,[`actions`,n,`from`])});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&&Qb(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:W(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=ay(i);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a config globals field (have: ${kc().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, or a "presets.<name>.root" target`,line:W(e.source,[`actions`,n,a])});continue}let s=sS.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:W(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){cS(e,t,n,a,i,o.preset,r);continue}if(o.scope===`preset-globals`&&!Yv(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: ${Yv(t.presets).join(`, `)})`,line:W(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(`, `)})${wl(o.segment)}`,line:W(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:W(e.source,[`actions`,n,a])})}}let i=Ng(t),a=Object.entries(t.segments).filter(([,e])=>ig(e.template)).map(([e])=>e),o=(t,n,r)=>{Bb(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Gy}" ${Bb(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}),Vb(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Gy}" 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}),s(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 Qo(t))e.kind===`segment`&&i.set(e.name,(i.get(e.name)??0)+1);for(let t of a)(i.get(t)??0)>1&&e.issues.push({path:n,message:`segment "${t}" hosts a {{ menu }} and is placed in the layout more than once — a menu's open-state is keyed by segment name, so the copies would share one state (clicking one would toggle both). Give each placement its own named segment.`,line:r})};function s(e,t=!1){return e.kind===`segment`?!1:t&&e.distribution!==void 0||e.children.some(n=>s(n,t||Xo[e.direction]===`cell`))}let c=(n,r)=>{for(let[a,o]of Ks(n,r)){let n=W(e.source,o.split(`.`));a.when!==void 0&&(fS(e,`${o}.when`,a.when,i,{line:n}),dS(e,`${o}.when`,a.when,n)),a.kind===`segment`&&(Lb(a.name)||Object.prototype.hasOwnProperty.call(t.segments,a.name)||e.issues.push({path:o,message:`${r} entry "${a.name}" does not match any declared segment${wl(a.name)}`,line:n}))}};n.root!==void 0&&c(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&c(t.root,`presets.${e}.root`);let l=new Map([[`root`,Ws(t.root)]]);for(let e of Yv(t.presets)){let{node:n,path:r}=Qv(t,e);l.set(r,n)}for(let[t,n]of l)o(n,t,W(e.source,t.split(`.`)));for(let[n,r]of Object.entries(t.variables))lS(e,`variables.${n}`,r,i);for(let[n,r]of Object.entries(t.segments)){if(r.vars)for(let[t,a]of Object.entries(r.vars))lS(e,`segments.${n}.vars.${t}`,a,i,n);for(let a of[`template`,`bg`,`fg`,`when`]){let o=r[a];if(typeof o==`string`){fS(e,`segments.${n}.${a}`,o,i,{segCtx:n});for(let r of kg(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}"`,line:W(e.source,[`segments`,n,a])});for(let r of jg(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}" (in a picker, menu or carousel)`,line:W(e.source,[`segments`,n,a])})}}}for(let[n,r]of Object.entries(t.variables))uS(e,`variables.${n}`,r,i);for(let[n,r]of Object.entries(t.segments))if(r.vars)for(let[t,a]of Object.entries(r.vars))uS(e,`segments.${n}.vars.${t}`,a,i,n)}const sS=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function cS(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=W(e.source,[`actions`,n,r]);if(!Yv(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Yv(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(`, `)})${wl(i)}`,line:c})};`removeSegment`in o&&f(`removeSegment`,o.removeSegment),`insertSegment`in o&&f(`insertSegment`,o.insertSegment),(`insertSegment`in o||`insertSegmentFrom`in o)&&f(`anchor`,o.anchor)}function lS(e,t,n,r,i){n.kind===`template`&&fS(e,`${t}.template`,n.template,r,{segCtx:i}),as(n)&&n.cache&&`key`in n.cache&&fS(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function uS(e,t,n,r,i){if(as(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:W(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function dS(e,t,n,r){try{sg.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function fS(e,t,n,r,i){for(let[a,o]of Dg(n,r.helpers)){if(Mg(a,r))continue;if(o!==null){pS(e,o,a);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&Mg(n,r)?` (segment-local vars are namespaced — write ".${n}")`:``;e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??W(e.source,t.split(`.`))})}}function pS(e,t,n){let r=`helpers.${t}`,i=`Template references unknown variable ".${n}"`;e.issues.some(e=>e.path===r&&e.message===i)||e.issues.push({path:r,message:i,line:W(e.source,[`helpers`,t])})}function mS(e,t){let{graph:n,nodeInfo:r}=hS(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:W(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function hS(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 Dg(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),as(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 gS=[`json5`,`json`];function _S(e){try{return r.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function vS(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?f.homedir()+e.slice(1):e}function yS(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?gS.map(t=>c.join(e,`.cc-candybar.${t}`)):[],...gS.map(e=>c.join(r,`.cc-candybar.${e}`)),...gS.map(e=>`${bS()}.${e}`)])]}function bS(){let e=process.env.XDG_CONFIG_HOME??c.join(f.homedir(),`.config`);return c.join(e,`cc-candybar`,`config`)}function xS(e,t,n){let r=[];for(let i of yS(e,t,n)){let e=_S(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 SS(e,t,n){let r=xS(e,t,n);return r.kind===`default`?`${bS()}.${gS[0]}`:r.path}function CS(e){return wS(e).join(`
158
- `)||null}function wS(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 TS(e,t){let n=yS(e,t).filter(e=>_S(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 ES(e,t,n){return e===null?{...OS,config:Ys(OS.raw,t)}:DS(e,r.readFileSync(e,`utf-8`),t,n)}function DS(e,t,n,r){let i={source:t,...jS(e,t,r,Tl(n))};return{...i,config:Ys(i.raw,n)}}const OS={raw:{},source:``,warnings:[]};function kS({config:e,raw:t,source:n},r=`<config>`,i=new Set(Sa())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(oS(o,e,t),mS(o,e),a.length>0)throw new Wo(r,a);return Py(Xb(e))}function AS(e,t,n=new Set(Sa()),r=MS){return jS(e,t,n,r).raw}function jS(e,t,n,r){let i=NS(e,t),a=qo(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(Sa()),groups:[]};if(!hs(i))throw new Wo(e,[{path:``,message:`Config root must be an object, got ${gs(i)}`}],o);let l=PS(c,i,r);if(s.length>0)throw new Wo(e,s,o);return{raw:l,warnings:o}}const MS=new Set;function NS(e,t){try{return Xe.default.parse(t)}catch(t){let n=t;throw new Wo(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function PS(e,t,n){for(let n of Object.keys(t))FS.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...FS].join(`, `)}`,line:W(e.source,[n])});let r={};return t.globals!==void 0&&(r.globals=Cc(e,`globals`,t.globals)),t.variables!==void 0&&(r.variables=Uc(e,`variables`,t.variables)),t.segments!==void 0&&(r.segments=El(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.
157
+ `,my=`${_l}live`,hy=[`☐ live`,`☑ live`],gy=`${_l}done`,_y={variable:my,key:my,member:`open`},vy=`and ${ac(dg)} (not ${ac(_y)})`,yy=`{{ ${vy} }}`;function by(e,t){return`{{ if ${vy} }}${e}{{ else }}${t}{{ end }}`}const xy=`{{ and ${ac(dg)} .preset.customized }}`,Sy=bl;function Cy(e){return`${_l}addable.${e}`}function wy(e){let t=Object.keys(e.segments).filter(e=>!Sy(e)),n=new Map;for(let r of Xv(e.presets)){let{node:i}=$v(e,r),a=qv(i);n.set(Cy(r),{members:t.filter(e=>!a.has(e))})}return n}function Ty(e,t,n){return n.segments[e]={template:t,when:fg},{kind:`segment`,name:e}}function Ey(e,t,n,r){let i=`${_l}${e}.remove.${ml(n)}`;return r.actions[i]={persist:t,removeSegment:n},`{{ if ${ac(dg)} }}{{ action "${i}" "🚫" }}{{ end }}`}const Dy=`${_l}label:`;function Oy(e){return e.startsWith(Dy)?e.slice(Dy.length):e.startsWith(`edit.`)?void 0:e}function ky(e,t){let n=`${Dy}${e}`;return t.segments[n]={template:`{{ "${nc(e)}" }}`,when:yy},{kind:`segment`,name:n}}function Ay(e,t,n,r,i,a,o){let s=`${_l}${e}.insert.${n}`,c=`${_l}${e}.insertSeg.${n}`;o.actions[s]={persist:t,insertSegmentFrom:r,anchor:i,relation:a};let l=Hh(s),u=Uh(c,s,void 0),d=Kh(u),f=Gh(u,l);return o.variables[u]=sc(u,Qs),o.variables[d]={kind:`state`,key:d,default:`0`},o.actions[f]=cc(u,l),o.actions[d]={set:d,int:!0},{host:c,template:`{{ $m := menu "${s}" "✚" "✕" }}{{ if ${ac({variable:u,key:u,member:l})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Qi}`}) $m }}{{ end }}`}}function jy(e,t,n,r,i,a){let o=[],s=e.children.findIndex(e=>e.kind===`segment`&&!Sy(e.name)),c=e=>jy(e,t,n,r,i,a);for(let[l,u]of e.children.entries()){if(u.kind===`container`){o.push(c(u));continue}let d=Zo(u,c);if(Sy(u.name)){o.push(d);continue}let f=e=>Ay(t,n,String(a.n++),r,u.name,e,i),p=l===s?[f(`before`)]:[],m=f(`after`),h=Ey(t,n,u.name,i),g={kind:`container`,direction:`horizontal`,children:[...p.map(e=>Ty(e.host,e.template,i)),{...ky(u.name,i),trail:h},{...d,when:by(`false`,u.when??`true`),trail:h},Ty(m.host,m.template,i)]};o.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[g]}:g)}return{...e,children:o,...e.when!==void 0&&{when:by(`true`,e.when)}}}function My(e,t,n,r,i,a,o){let s=`${_l}${n}.resetLayout`,c=`${_l}${n}.customized`;i.actions[s]={reset:r};let l=nc(t);return i.segments[c]={template:`{{ action "${s}" "↺ ${l} customized" }}`,when:xy},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[a,{kind:`segment`,name:c}]},Ny(e,o)]}}function Ny(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),Ny(n,t)]}:{...e,children:[...e.children,t]}}function Py(e,t,n,r,i){let{node:a}=$v(e,t),o=iy(t),s=Cy(t),c=ml(t);return My(jy(a,c,o,s,n,{n:0}),t,c,o,n,r,i)}function Fy(e){let t={variables:{},actions:{},segments:{}},n=ly(`${_l}help`,fy,[dg],t);t.variables[my]=sc(my,Qs),t.actions[my]=cc(my,_y.member),t.segments[my]={template:oc(my,...hy),when:fg};let r={kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:my},n]};t.segments[gy]={template:`{{ action "${lg}" "✎ done" }}`,when:fg};let i={kind:`segment`,name:gy},a={...e.presets},o=[];for(let n of Xv(e.presets)){let s=Py(e,n,t,i,r);o.push(s),a[n]={...Qv(e.presets,n),root:s}}let s=Wv(t,o,e);return{...e,variables:{...s,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:a}}const Iy={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function Ly(e){let t=e[Iy.socket]??``,n=e[Iy.pane]??``;if(t===``||n===``)return null;let r=e[Iy.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const Ry=Iy.truecolor,zy=[{name:`tmuxTruecolor`,label:`tmux truecolor`,probe:({tmux:e,claudeSettingsEnv: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[Ry];return typeof n==`string`&&n!==``?{ok:!1,reason:`${Ry} is set in ~/.claude/settings.json — restart Claude Code to apply`}:{ok:!1,reason:`Claude Code renders the bar in 256 colours inside tmux`,fix:{kind:`claude-settings-env`,name:Ry,value:`1`}}}}}}];function By(e){return zy.map(t=>({check:t,verdict:t.probe(e)}))}function Vy(e){return zy.find(t=>t.name===e)}function Hy(e){let t=`settings.doctor.${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`}}function Uy(e){return e.flatMap(({check:e,verdict:t})=>{let n=Hy(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:``},{key:n.fixable,value:Ja}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:t.reason},{key:n.fixable,value:t.fix===void 0?Ja:qa}]})}const Wy={copySession:{copy:`{{ .session.id }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`}};function Gy(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}`,actions:Object.fromEntries(Object.entries(Wy).map(([t,n])=>[`${e}${t}`,n]))}}const Ky=`${vl}menu`,qy=ug,Jy=`${vl}edit`,Yy=`${vl}close`,Xy=`${vl}toolbar`,Zy=Gy(vl),Qy=`${vl}config`,$y=`${vl}save`,eb=`${vl}unsaved`,tb=`${vl}preset.save`,nb=`${vl}preset.delete`,rb=`${vl}resetAll`,ib=`${rb}.arm`,ab=`${rb}.disarm`,ob=`armed`,sb=`disarmed`,cb=`${Ky}.toggle`,lb=`${Qy}.toggle`,ub={variable:Ky,key:Ky,member:qy},db={variable:Qy,key:Qy,member:qy},fb=`${vl}tools`,pb={variable:fb,key:fb,member:qy},mb=[{seg:`${vl}undo`,depth:`undo`,action:{undo:!0},display:`↶ undo`},{seg:`${vl}redo`,depth:`redo`,action:{redo:!0},display:`↷ redo`}],hb=e=>`${vl}history.${e}`,gb=`${vl}doctor`,_b=`${gb}.run`,vb=e=>`${gb}.fix.${e}`,yb=e=>`${gb}.${e}`,bb=`${vl}pickers`,xb=[`{{ themePreview }}`],Sb=[{name:`preset`,...Rv.preset,glyph:`▦`,domain:`presets`,beneath:[`{{ layoutPreview }}`,`{{ action "${tb}" "⊕ save as preset" }}{{ if not .preset.bundled }} {{ action "${nb}" (printf "🗑 delete %s" .${Rv.preset.effectiveVar}) }}{{ end }}`]}],Cb=[{name:`theme`,...Rv.theme,glyph:`🎨`,domain:`themes`,beneath:xb},{name:`look`,...Rv.look,glyph:`◐`,domain:`looks`,beneath:xb},{name:`style`,...Rv.style,glyph:`✦`,domain:`styles`,beneath:[]},{name:`progression`,...Rv.progression,glyph:`🎼`,domain:`progressions`,beneath:[`{{ layoutPreview }}`]},{name:`charset`,...Rv.charset,glyph:`🔣`,domain:`charsets`,beneath:[]},{name:`colorCompatibility`,...Rv.colorCompatibility,glyph:`🌈`,domain:`colorCompatibilities`,beneath:[]}],wb={name:`wrap`,...Rv.autoWrap},Tb={name:`padding`,...Rv.padding},Eb=`${vl}${wb.name}`,Db=`${vl}${Tb.name}`,Ob=[...Sb,...Cb],kb=[...Ob,wb,Tb];new Set(kb.flatMap(e=>[e.sessionKey,e.configKey]));const Ab=e=>`${vl}${e}`,jb=e=>`${vl}apply.${e}`,Mb=e=>`${vl}reset.${e}`,Nb=e=>`${vl}carousel.${e}`,Pb=(e,t)=>`${Nb(e)}.${t}`,Fb=Wh(bb),Ib=e=>({variable:Fb,key:Fb,member:Hh(jb(e.name))});function Lb(e){return rc(Ab(e.name),Ib(e),{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:Nb(e.name)},...e.beneath.map((t,n)=>({kind:`segment`,name:Pb(e.name,n)}))]},`drop`)}function Rb(e){return e===Ky}function zb(e){let t={kind:`segment`,name:Ky};if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[zb(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 Bb(e){return Vb(e)>0?e:zb(e)}function Vb(e){let t=0;for(let n of Qo(e))n.kind===`segment`&&Rb(n.name)&&(t+=1);return t}function Hb(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&Rb(e.name)||e.opens!==void 0&&Hb(e.opens.body,!0):e.children.some(e=>Hb(e,n))}function Ub(e){return e.kind===`segment`?Rb(e.name)?rc(e.name,ub,{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:Xy},...Sb.map(Lb),{kind:`segment`,name:$y},rc(Qy,db,{kind:`container`,direction:`horizontal`,children:[...Cb.map(Lb),{kind:`segment`,name:Eb},{kind:`segment`,name:Db},{kind:`segment`,name:rb}]},`drop`),rc(fb,pb,{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:gb},...zy.map(e=>({kind:`segment`,name:yb(e.name)}))]},`drop`),{kind:`segment`,name:Jy},...mb.map(e=>({kind:`segment`,name:e.seg}))]},`inline`):e:Wb(e)}function Wb(e){return{...e,children:e.children.map(e=>Ub(e))}}function Gb(e){let t={variables:{[Ky]:sc(Ky,Qs)},actions:{[cb]:cc(Ky,qy),[Ky]:{do:[cb,ab]},[lb]:cc(Qy,qy),[Qy]:{do:[lb,ab]},[fb]:cc(fb,qy),[_b]:{doctor:`run`},[Yy]:{set:ub.key,to:Qs},[Jy]:{do:[lg,Yy]},...Zy.actions,[$y]:{save:!0},[tb]:{preset:`save`},[nb]:{preset:`delete`,name:`{{ .${Rv.preset.effectiveVar} }}`}},segments:{[Ky]:{template:oc(Ky,e,`❌`)},[Xy]:{template:Zy.template},[$y]:{when:`{{ gt .${eb} 0 }}`,template:`{{ action "${$y}" (printf "💾 save %d" .${eb}) }}`},[Qy]:{template:oc(Qy,`⚙ config ▸`,`⚙ config ▾`)},[fb]:{template:oc(fb,`🧰 tools ▸`,`🧰 tools ▾`)},[gb]:{template:`{{ action "${_b}" "🩺 doctor" }}`},[Eb]:{template:`{{ action "${jb(`wrap`)}" "wrap: on" "wrap: off" }} {{ action "${Mb(`wrap`)}" "↺" }}`},[Db]:{template:`{{ action "${jb(`padding`)}.down" "◀" }} padding {{ .${Tb.effectiveVar} }} {{ action "${jb(`padding`)}.up" "▶" }} {{ action "${Mb(`padding`)}" "↺" }}`},[Jy]:{template:`{{ action "${Jy}" "✎ edit" "✎ done" }}`},[rb]:{template:`{{ if eq .${rb} "${ob}" }}{{ action "${rb}" "⟲ confirm reset all" }}{{ else }}{{ action "${ib}" "⟲ reset all" }}{{ end }}`}}};return t.variables[eb]={kind:`input`,path:`unsaved`,type:`number`,default:0},t.variables[Qy]=sc(Qy,Qs),t.variables[fb]=sc(fb,Qs),t.variables[rb]={kind:`state`,key:rb,default:sb},Jb(t),qb(t),Kb(t),t}function Kb(e){for(let t of mb){let n=hb(t.depth);e.variables[n]={kind:`input`,path:`history.${t.depth}`,type:`number`,default:0},e.actions[t.seg]=t.action,e.segments[t.seg]={when:`{{ gt .${n} 0 }}`,template:`{{ action "${t.seg}" "${t.display}" }}`}}}function qb(e){for(let t of zy){let n=Hy(t.name),r=vb(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[yb(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${qa}" }} {{ action "${r}" "[fix]" }}{{ end }}{{ end }}`}}}function Jb(e){for(let t of Ob){let n=jb(t.name);e.actions[n]={set:t.sessionKey,from:t.domain},e.actions[Mb(t.name)]={reset:t.configKey},Yb(t,e)}e.actions[jb(wb.name)]={set:wb.sessionKey,cycle:[...Ya]},e.actions[Mb(wb.name)]={reset:wb.configKey};for(let t of[-1,1])e.actions[`${jb(Tb.name)}.${t<0?`down`:`up`}`]={set:Tb.sessionKey,...Xa,by:t};e.actions[Mb(Tb.name)]={reset:Tb.configKey},e.actions[ib]={set:rb,to:ob},e.actions[ab]={set:rb,to:sb},e.actions[rb]={do:[ab,...kb.map(e=>Mb(e.name))]}}function Yb(e,t){let n=jb(e.name),r=Ib(e),i=Gh(r.key,r.member);t.variables[r.key]=sc(r.key,Qs),t.actions[i]=cc(r.key,r.member),t.segments[Ab(e.name)]={template:`${e.glyph} {{ .${e.effectiveVar} }} ${oc(i,`▸`,`▾`)} {{ action "${Mb(e.name)}" "↺" }}`},t.segments[Nb(e.name)]={template:`{{ carousel "${n}" }}`},e.beneath.forEach((n,r)=>{t.segments[Pb(e.name,r)]={template:n}})}function Xb(e){e.variables[cg]=sc(cg,Qs),e.actions[lg]=cc(cg,ug)}function Zb(e){let t=Gb(e.globals.menuGlyph??`🍫`);Xb(t);let n={...e.presets},r=[];for(let t of Xv(e.presets)){let{node:i}=$v(e,t),a=Ub(Bb(i));r.push(a),n[t]={...Qv(e.presets,t),root:a}}let i=Wv(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const Qb=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`save`,`preset`,`doctor`,`do`];function $b(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function ex(e,t){if(t===void 0)return{};if(!hs(t))return Z(e,`actions`,`actions must be an object, got ${gs(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=tx(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Z(e,t,n){e.issues.push({path:t,message:n,line:W(e.source,t.split(`.`))})}function tx(e,t,n){if(!hs(n))return Z(e,t,`${t} must be an action object, got ${gs(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let r=Qb.filter(e=>e in n);return r.length===1?nx[r[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${Qb.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const nx={set:(e,t,n)=>Mx(e,t,n,`set`,Ox),persist:(e,t,n)=>Mx(e,t,n,`persist`,kx),copy:rx(`copy`),open:rx(`open`),reset:ix,undo:ox(`undo`),redo:ox(`redo`),save:ox(`save`),preset:sx,doctor:cx,do:lx};function rx(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=us(t,n,r,e);return i===null?null:{[e]:i}}}function ix(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=ux(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 ax={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,save:`it saves the session's unsaved settings`};function ox(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Z(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${ax[e]}), got ${G(r[e])}`),null)}}function sx(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${G(r)}`),null;if(r===`save`)return{preset:`save`};let a=us(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function cx(e,t,n){let r=n.doctor,i=r===`run`?[`doctor`]:[`doctor`,`check`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${i.join(`, `)}`);if(r!==`run`&&r!==`fix`)return Z(e,`${t}.doctor`,`doctor must be "run" or "fix", got ${G(r)}`),null;if(r===`run`)return{doctor:`run`};let a=n.check;return typeof a!=`string`||Vy(a)===void 0?(Z(e,`${t}.check`,`doctor fix must name a check (have: ${zy.map(e=>e.name).join(`, `)}), got ${G(a)}`),null):{doctor:`fix`,check:a}}function lx(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${G(r)}`),null):{do:r}}function ux(e,t,n,r,i,a){let o=us(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Z(e,s,i),null):o.includes(`/`)?(Z(e,s,a(o)),null):o}const dx={set:`the SessionState key to write`,persist:`the config globals field to write`};function fx(e,t,n,r){let i=dx[r],a=ux(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 px(e){return e===`set`?`set-state`:`set-config`}const mx={to:Nx(`set`)},hx={to:Nx(`persist`)},gx={from:Px(`set`)},_x={from:Px(`persist`)},vx={min:zx(),max:zx(),by:zx()},yx={int:Ix()},bx={cycle:Fx(`set`)},xx={cycle:Fx(`persist`)},Sx={removeSegment:Lx(`removeSegment`)},Cx={insertSegment:Lx(`insertSegment`),anchor:Lx(`anchor`),relation:Rx()},wx={insertSegmentFrom:Px(`persist`),anchor:Lx(`anchor`),relation:Rx()},Tx={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},Ex={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function Dx(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>vs(e,t,n,r),c=Ns(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?Es(s,...n):s}}const Ox=[Dx(`set`,mx),Dx(`set`,gx),Dx(`set`,vx,[Tx,Ex]),Dx(`set`,yx),Dx(`set`,bx)],kx=[Dx(`persist`,hx),Dx(`persist`,_x),Dx(`persist`,vx,[Tx,Ex]),Dx(`persist`,xx),Dx(`persist`,Sx),Dx(`persist`,Cx,[],[`insertSegment`]),Dx(`persist`,wx,[],[`insertSegmentFrom`])];function Ax(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"styles"/"looks", 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 jx(e){let t=Ax(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 Mx(e,t,n,r,i){let a=fx(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${jx(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Z(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function Nx(e){let t=px(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>ux(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 Px(e){let t=px(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${G(o)}`)}}}function Fx(e){let t=px(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Z(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${gs(o)}`);return}let c=o;if(c.length<2){Z(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Z(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Z(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Z(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function Ix(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${G(r[n])}`);return}return!0}}}function Lx(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=us(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Z(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Z(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function Rx(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${G(i)}`);return}return i}}}function zx(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${G(i)}`);return}return i}}}const Bx={noun:`look key`,fields:{hueShift:ks(),chromaScale:ks({min:0}),lightnessScale:ks(),lightnessShift:ks()}};function Vx(e,t){if(!hs(t))return e.issues.push({path:`looks`,message:`looks must be an object mapping look names to adaptation objects, got ${gs(t)}`,line:W(e.source,[`looks`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`looks.${r}`,message:`look name ${JSON.stringify(r)} must be non-empty and slash-free — a look picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:W(e.source,[`looks`,r])});continue}let t=_s(e,Bx,`looks.${r}`,i);t!==null&&(n[r]={...On,...t})}return n}const Hx={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:Yl(e,`${t}.${n}`,r[n])},globals:{required:!1,json:Tc(),parse:(e,t,n,r)=>r[n]===void 0?void 0:wc(e,`${t}.${n}`,r[n])}}};function Ux(e,t){if(!hs(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${gs(t)}`,line:W(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:W(e.source,[`presets`,r])});continue}let t=_s(e,Hx,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function Wx(e,t){if(t===void 0)return{};if(!hs(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${gs(t)}`,line:W(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 ${G(i)}`,line:W(e.source,[`helpers`,r])});continue}n[r]=i}return n}const Gx=new Map,Kx=new Map;function qx(e){let t=Jx(e);if(t===null)throw Error(`Palette "${e}" (resolved "${va(e)}") did not resolve in the theme registry — allowed names and the registry are inconsistent`);return t}function Jx(e){let t=va(e),n=Gx.get(t);if(n!==void 0)return n;let r=ir(t);return r===null?null:(Gx.set(t,r),r)}function Yx(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=Kx.get(n);if(r!==void 0)return r;let i=fr(e,t);return Kx.set(n,i),i}function Xx(e){let t=Jx(e);return t===null?null:{kind:`decided`,name:e,value:t}}function Zx(e,t){let n=Xx(e);return n===null?(t(`globals.palette rendered "${ya}": "${e}" names no installed theme`),$x()):n}function Qx(e,t,n){return Ea(e,t,n,$x(),Xx)}function $x(){return Xx(ya)}function eS(e){return Da(Qx(void 0,null,e),()=>ya,$x).value}const tS=new Map;function nS(e,t,n){tS.set(e,{permanent:!0,resolve:t,paletteOf:n})}nS(`themes`,()=>Sa(),e=>qx(e)),nS(`styles`,()=>Ma),nS(`progressions`,()=>Wa),nS(`charsets`,()=>Fa),nS(`colorCompatibilities`,()=>za);function rS(e){return new Map([[`looks`,{members:Object.keys(e.looks),paletteOf:(t,n)=>Yx(n,e.looks[t])}],[`presets`,{members:Xv(e.presets)}]])}function iS(e){return[...new Set([...tS.keys(),...e.keys()])]}function aS(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=tS.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf};throw Error(`unknown option domain "${e}" (have: ${iS(t).join(`, `)})`)}function oS(e,t){let n=new Map;for(let e of Object.keys(t)){let t=ml(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:W(e.source,[`presets`])})}function sS(e,t,n){t.globals.look!==void 0&&!Ta(t.globals.look)&&!Object.prototype.hasOwnProperty.call(t.looks,t.globals.look)&&e.issues.push({path:`globals.look`,message:`globals.look "${t.globals.look}" does not match any declared look (have: ${Object.keys(t.looks).join(`, `)})`,line:W(e.source,[`globals`,`look`])}),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:W(e.source,[`globals`,`preset`])}),oS(e,t.presets);let r=rS(t);for(let[n,i]of Object.entries(t.actions))!(`set`in i)||!(`from`in i)||typeof i.from!=`string`||iS(r).includes(i.from)||e.issues.push({path:`actions.${n}.from`,message:`actions.${n} from: references unknown option domain "${i.from}" (have: ${iS(r).join(`, `)})`,line:W(e.source,[`actions`,n,`from`])});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&&$b(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:W(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=oy(i);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a config globals field (have: ${kc().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, or a "presets.<name>.root" target`,line:W(e.source,[`actions`,n,a])});continue}let s=cS.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:W(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){lS(e,t,n,a,i,o.preset,r);continue}if(o.scope===`preset-globals`&&!Xv(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: ${Xv(t.presets).join(`, `)})`,line:W(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(`, `)})${wl(o.segment)}`,line:W(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:W(e.source,[`actions`,n,a])})}}let i=Ng(t),a=Object.entries(t.segments).filter(([,e])=>ig(e.template)).map(([e])=>e),o=(t,n,r)=>{Vb(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Ky}" ${Vb(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}),Hb(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Ky}" 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}),s(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 Qo(t))e.kind===`segment`&&i.set(e.name,(i.get(e.name)??0)+1);for(let t of a)(i.get(t)??0)>1&&e.issues.push({path:n,message:`segment "${t}" hosts a {{ menu }} and is placed in the layout more than once — a menu's open-state is keyed by segment name, so the copies would share one state (clicking one would toggle both). Give each placement its own named segment.`,line:r})};function s(e,t=!1){return e.kind===`segment`?!1:t&&e.distribution!==void 0||e.children.some(n=>s(n,t||Xo[e.direction]===`cell`))}let c=(n,r)=>{for(let[a,o]of Ks(n,r)){let n=W(e.source,o.split(`.`));a.when!==void 0&&(pS(e,`${o}.when`,a.when,i,{line:n}),fS(e,`${o}.when`,a.when,n)),a.kind===`segment`&&(Rb(a.name)||Object.prototype.hasOwnProperty.call(t.segments,a.name)||e.issues.push({path:o,message:`${r} entry "${a.name}" does not match any declared segment${wl(a.name)}`,line:n}))}};n.root!==void 0&&c(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&c(t.root,`presets.${e}.root`);let l=new Map([[`root`,Ws(t.root)]]);for(let e of Xv(t.presets)){let{node:n,path:r}=$v(t,e);l.set(r,n)}for(let[t,n]of l)o(n,t,W(e.source,t.split(`.`)));for(let[n,r]of Object.entries(t.variables))uS(e,`variables.${n}`,r,i);for(let[n,r]of Object.entries(t.segments)){if(r.vars)for(let[t,a]of Object.entries(r.vars))uS(e,`segments.${n}.vars.${t}`,a,i,n);for(let a of[`template`,`bg`,`fg`,`when`]){let o=r[a];if(typeof o==`string`){pS(e,`segments.${n}.${a}`,o,i,{segCtx:n});for(let r of kg(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}"`,line:W(e.source,[`segments`,n,a])});for(let r of jg(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}" (in a picker, menu or carousel)`,line:W(e.source,[`segments`,n,a])})}}}for(let[n,r]of Object.entries(t.variables))dS(e,`variables.${n}`,r,i);for(let[n,r]of Object.entries(t.segments))if(r.vars)for(let[t,a]of Object.entries(r.vars))dS(e,`segments.${n}.vars.${t}`,a,i,n)}const cS=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function lS(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=W(e.source,[`actions`,n,r]);if(!Xv(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Xv(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(`, `)})${wl(i)}`,line:c})};`removeSegment`in o&&f(`removeSegment`,o.removeSegment),`insertSegment`in o&&f(`insertSegment`,o.insertSegment),(`insertSegment`in o||`insertSegmentFrom`in o)&&f(`anchor`,o.anchor)}function uS(e,t,n,r,i){n.kind===`template`&&pS(e,`${t}.template`,n.template,r,{segCtx:i}),as(n)&&n.cache&&`key`in n.cache&&pS(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function dS(e,t,n,r,i){if(as(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:W(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function fS(e,t,n,r){try{sg.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function pS(e,t,n,r,i){for(let[a,o]of Dg(n,r.helpers)){if(Mg(a,r))continue;if(o!==null){mS(e,o,a);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&Mg(n,r)?` (segment-local vars are namespaced — write ".${n}")`:``;e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??W(e.source,t.split(`.`))})}}function mS(e,t,n){let r=`helpers.${t}`,i=`Template references unknown variable ".${n}"`;e.issues.some(e=>e.path===r&&e.message===i)||e.issues.push({path:r,message:i,line:W(e.source,[`helpers`,t])})}function hS(e,t){let{graph:n,nodeInfo:r}=gS(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:W(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function gS(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 Dg(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),as(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 _S=[`json5`,`json`];function vS(e){try{return r.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function yS(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?f.homedir()+e.slice(1):e}function bS(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?_S.map(t=>c.join(e,`.cc-candybar.${t}`)):[],..._S.map(e=>c.join(r,`.cc-candybar.${e}`)),..._S.map(e=>`${xS()}.${e}`)])]}function xS(){let e=process.env.XDG_CONFIG_HOME??c.join(f.homedir(),`.config`);return c.join(e,`cc-candybar`,`config`)}function SS(e,t,n){let r=[];for(let i of bS(e,t,n)){let e=vS(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 CS(e,t,n){let r=SS(e,t,n);return r.kind===`default`?`${xS()}.${_S[0]}`:r.path}function wS(e){return TS(e).join(`
158
+ `)||null}function TS(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 ES(e,t){let n=bS(e,t).filter(e=>vS(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 DS(e,t,n){return e===null?{...kS,config:Ys(kS.raw,t)}:OS(e,r.readFileSync(e,`utf-8`),t,n)}function OS(e,t,n,r){let i={source:t,...MS(e,t,r,Tl(n))};return{...i,config:Ys(i.raw,n)}}const kS={raw:{},source:``,warnings:[]};function AS({config:e,raw:t,source:n},r=`<config>`,i=new Set(Sa())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(sS(o,e,t),hS(o,e),a.length>0)throw new Wo(r,a);return Fy(Zb(e))}function jS(e,t,n=new Set(Sa()),r=NS){return MS(e,t,n,r).raw}function MS(e,t,n,r){let i=PS(e,t),a=qo(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(Sa()),groups:[]};if(!hs(i))throw new Wo(e,[{path:``,message:`Config root must be an object, got ${gs(i)}`}],o);let l=FS(c,i,r);if(s.length>0)throw new Wo(e,s,o);return{raw:l,warnings:o}}const NS=new Set;function PS(e,t){try{return Xe.default.parse(t)}catch(t){let n=t;throw new Wo(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function FS(e,t,n){for(let n of Object.keys(t))IS.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...IS].join(`, `)}`,line:W(e.source,[n])});let r={};return t.globals!==void 0&&(r.globals=Cc(e,`globals`,t.globals)),t.variables!==void 0&&(r.variables=Uc(e,`variables`,t.variables)),t.segments!==void 0&&(r.segments=El(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.
159
159
  Replace: layout: [["seg1", "seg2"], ["seg3"]]
160
160
  With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
161
- Single-row example: root: { h: ["seg1", "seg2"] }`,line:W(e.source,[`layout`])}),t.root!==void 0&&(r.root=Yl(e,`root`,t.root)),t.actions!==void 0&&(r.actions=$b(e,t.actions)),t.looks!==void 0&&(r.looks=Bx(e,t.looks)),t.presets!==void 0&&(r.presets=Hx(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=Ec(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=Ux(e,t.helpers)),ru(e,r),og(e,r),hg(e,r),Sl(e,r,vl,`the global settings menu`),r}const FS=new Set([`globals`,`variables`,`segments`,`layout`,`root`,`actions`,`looks`,`presets`,`editGlobals`,`helpers`]);function IS(e){let t=BS(e.termCols),n=BS(e.termRows),r=VS(e.ssh),i=RS(e.tmux),a=LS(e.configEnv);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}}}function LS(e){return typeof e==`string`&&e!==``?vS(e):void 0}function RS(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 zS=1e4;function BS(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>zS?zS:t}function VS(e){return typeof e==`boolean`?e:void 0}var HS=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function US(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function WS(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 HS(`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 HS(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function GS(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=WS(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(US(t))})}async function KS(e,t,n){let r=null;try{r=await ZS(Ne(),t.connectMs);let i=await GS(r,{v:3,...e},t.budgetMs);return YS(e.kind,i,n)}catch(e){return XS(e)}finally{r&&r.destroy()}}function qS(e,t){return typeof e==`string`?e:t}function JS(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function YS(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=qS(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:JS(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 XS(e){if(e instanceof HS||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 ZS(e,t){return new Promise((n,r)=>{let i=g.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 QS(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 $S={connectMs:50,budgetMs:150},eC={connectMs:50,budgetMs:200};function tC(e){let t=e.output;return typeof t==`string`?t:void 0}function nC(e,t,n,r){return KS({kind:`render`,hookData:e,args:t,cwd:n,...r},$S,tC)}function rC(e,t){return KS({kind:`click`,verb:e,value:t},eC,tC)}let iC=null;function aC(e){if(iC!==null)return iC;r.mkdirSync(c.dirname(e),{recursive:!0});try{iC=r.statSync(e).size}catch{iC=0}return iC}function oC(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{}iC=0}function Q(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=Ge(),t=aC(e);r.appendFileSync(e,n),iC=t+Buffer.byteLength(n,`utf8`),iC>=5242880&&oC(e)}catch(e){iC=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}function sC(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(`
162
- `)}function cC(e,t){return e===`darwin`?[lC(`footprint`,[`-p`,String(t)]),lC(`vmmap`,[`--summary`,String(t)])]:e===`linux`?[uC(`/proc/self/smaps_rollup`),uC(`/proc/self/status`)]:[]}function lC(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=Ee({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}`}${dC(n.stderr)}`}}}}function uC(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 dC(e){let t=e.split(`
163
- `).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const fC=`CC_CANDYBAR_RSS_LIMIT_MB`;function pC(e){let t=e[fC];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${fC} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function mC(e){return pC(e)*2}const hC=1024*1024;function gC(e){return pC(e)*hC}const _C={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function vC(e,t,n){let{prefix:r,suffix:i}=_C[t];return c.join(e,`${r}${n}${i}`)}function yC(e){for(let t of Object.keys(_C)){let{prefix:n,suffix:r}=_C[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function bC(e){let t=e.rssLimitBytes??512*hC,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 xC(e.log,`memory report`,()=>{let t=vC(e.snapshotDir,`memoryReport`,o);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),xC(e.log,`heap snapshot`,()=>{let t=vC(e.snapshotDir,`heapSnapshot`,o);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),xC(e.log,`artifact rotation`,()=>{CC(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 xC(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function SC(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=yC(t);if(n===null)return t;let{prefix:r,suffix:i}=_C[n];return t.slice(r.length,t.length-i.length)}function CC(e,t,n){let r=new Map;for(let t of e){let e=SC(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 wC(e,t,n={}){let i=Me();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:Q,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},captureMemoryReport:()=>sC(cC(process.platform,process.pid)),writeMemoryReport:(e,t)=>r.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>C.writeHeapSnapshot(e),listArtifacts:()=>{try{return r.readdirSync(i).filter(e=>yC(e)!==null).map(e=>c.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function TC(e={}){if(VC()!==null)return;let n=e.spawn??HC,r=RC();if(r.kind===`contended`){let e=DC();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),EC(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),EC(n);return}try{EC(n)}finally{BC()}}function EC(e){PC()&&OC(e)}function DC(){try{let e=r.statSync(Ve());return Date.now()-e.mtimeMs}catch{return null}}function OC(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
164
- `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function kC(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function AC(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function jC(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 MC(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 NC(){try{r.unlinkSync(Ue())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function PC(){let e=He(),n=Ue(),r=jC(n),i=kC(FC(e),AC(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`),IC(e),MC(n,Math.min(r+1,5)),!0)}function FC(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function IC(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 LC=null;function RC(){let e=Ve();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 LC={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(!zC(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 zC(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function BC(){if(!LC)return;let{fd:e,path:t}=LC;LC=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function VC(){try{return r.mkdirSync(Me(),{recursive:!0}),null}catch(e){return`mkdir ${Me()}: ${e.message}`}}function HC(){let e=t.execPath,n=t.argv[1];return n?De({bin:e,args:[`--max-old-space-size=${mC(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const UC=`cc-candybar`,WC=`dispatch`,GC=`set-state`,KC=`step-state`,qC=`copy`,JC=`open-vscode`,YC=`toolbar-toggle`,XC=`show-config-error`,ZC=`show-config-warning`,QC=`set-config`,$C=`step-config`,ew=`save`,tw=`save-preset`,nw=`delete-preset`,rw=`reset-config`,iw=`apply-layout-op`,aw=`undo`,ow=`redo`,sw=`apply-update`,cw=`doctor-run`,lw=`doctor-fix`;function uw(e){return e.map(encodeURIComponent).join(`/`)}function dw(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function fw(e){return`${UC}://${WC}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${uw(e.args)}`)}`).join(`&`)}`}function pw(e){return new te(e).getAll(`e`).map(_w)}const mw=new Set([GC,rw]);function hw(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&gw(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function gw(e,t){if(e.verb!==t.verb||!mw.has(e.verb))return;let[n,r]=[_w(e.value),_w(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function _w(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const vw=`1.87.0`;function yw(){return c.join(f.homedir(),`.claude`,`settings.json`)}const bw=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function xw(e){let t=bw.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 Sw(e){return e.join(`.`)}function Cw([e,t,n],[r,i,a]){return e-r||t-i||n-a}const ww=`@promptctl/cc-candybar`;async function Tw(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`?xw(n.latest):Y}catch(e){return X(e instanceof Error?e.message:String(e))}}function Ew(e,t){let n=xw(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=Cw(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 Dw(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${Sw(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${Sw(t.installed)} is newer than the registry's latest release (${Sw(t.latest)}): an unpublished build.\n`};case`stale`:{let n=Sw(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${Sw(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 Ow=`CCCandybarURLHandler`,kw=[],Aw={"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 jw(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function Mw(e,t){return[e,...t].map(jw).join(` `)}function Nw(){return c.join(f.homedir(),`Applications`,`${Ow}.app`)}function Pw(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function Fw(){if(process.platform===`darwin`)return c.join(f.homedir(),`Library`,`Application Support`,`CCCandybar`);let e=process.env.XDG_DATA_HOME??c.join(f.homedir(),`.local`,`share`);return c.join(e,`cc-candybar`)}function Iw(){return c.join(Fw(),`bin`,`cc-candybar`)}function Lw(){return c.join(Fw(),`dist`,`index.mjs`)}function Rw(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(`
165
- `)}function zw(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 Bw(t){let n=Aw[`${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 Vw(e,t){c.resolve(e)!==c.resolve(t)&&r.copyFileSync(e,t)}function Hw(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 ${ww}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function Uw(){let e=zw(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=Bw(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(c.dirname(Lw()),{recursive:!0}),r.mkdirSync(c.dirname(Iw()),{recursive:!0}),Vw(e,Lw()),Vw(t.sourcePath,Iw()),r.chmodSync(Iw(),493),r.rmSync(c.join(Fw(),`url-handler.mjs`),{force:!0});let n=Hw(Iw());return process.stdout.write(`Staged cc-candybar v${vw} runtime at ${Fw()}\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:Iw(),distPath:Lw(),entryKind:n}}function Ww(){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>${UC}</string>`,` </array>`,` </dict>`,`</array>`].join(`
166
- `)}]}function Gw(e){let t=Nw();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=Ee({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,Rw(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 Ww())Ee({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of Ww()){let n=Ee({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 ${UC}:// with Launch Services\n`);let a=Ee({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(`✓ ${Ow}.app installed and registered.\n`),process.stdout.write(` Test: open '${UC}://hello-world' && pbpaste\n`)}function Kw(){Pw(),Gw(Uw().distPath)}function qw(e,t=UC){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:qC,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function Jw(e){e||(process.stderr.write(`url-handle: missing URL argument.
167
- `),process.exit(1));let t;try{t=qw(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await rC(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(TC(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(Yw(n)+`
168
- `),process.exit(1)}function Yw(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 Xw(){return`✓ install complete.
161
+ Single-row example: root: { h: ["seg1", "seg2"] }`,line:W(e.source,[`layout`])}),t.root!==void 0&&(r.root=Yl(e,`root`,t.root)),t.actions!==void 0&&(r.actions=ex(e,t.actions)),t.looks!==void 0&&(r.looks=Vx(e,t.looks)),t.presets!==void 0&&(r.presets=Ux(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=Ec(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=Wx(e,t.helpers)),ru(e,r),og(e,r),hg(e,r),Sl(e,r,vl,`the global settings menu`),r}const IS=new Set([`globals`,`variables`,`segments`,`layout`,`root`,`actions`,`looks`,`presets`,`editGlobals`,`helpers`]);function LS(e){let t=VS(e.termCols),n=VS(e.termRows),r=HS(e.ssh),i=zS(e.tmux),a=RS(e.configEnv);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}}}function RS(e){return typeof e==`string`&&e!==``?yS(e):void 0}function zS(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 BS=1e4;function VS(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>BS?BS:t}function HS(e){return typeof e==`boolean`?e:void 0}var US=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function WS(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function GS(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 US(`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 US(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function KS(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=GS(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(WS(t))})}async function qS(e,t,n){let r=null;try{r=await QS(Ne(),t.connectMs);let i=await KS(r,{v:3,...e},t.budgetMs);return XS(e.kind,i,n)}catch(e){return ZS(e)}finally{r&&r.destroy()}}function JS(e,t){return typeof e==`string`?e:t}function YS(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function XS(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=JS(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:YS(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 ZS(e){if(e instanceof US||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 QS(e,t){return new Promise((n,r)=>{let i=g.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 $S(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 eC={connectMs:50,budgetMs:150},tC={connectMs:50,budgetMs:200};function nC(e){let t=e.output;return typeof t==`string`?t:void 0}function rC(e,t,n,r){return qS({kind:`render`,hookData:e,args:t,cwd:n,...r},eC,nC)}function iC(e,t){return qS({kind:`click`,verb:e,value:t},tC,nC)}let aC=null;function oC(e){if(aC!==null)return aC;r.mkdirSync(c.dirname(e),{recursive:!0});try{aC=r.statSync(e).size}catch{aC=0}return aC}function sC(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{}aC=0}function Q(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=Ge(),t=oC(e);r.appendFileSync(e,n),aC=t+Buffer.byteLength(n,`utf8`),aC>=5242880&&sC(e)}catch(e){aC=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}function cC(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(`
162
+ `)}function lC(e,t){return e===`darwin`?[uC(`footprint`,[`-p`,String(t)]),uC(`vmmap`,[`--summary`,String(t)])]:e===`linux`?[dC(`/proc/self/smaps_rollup`),dC(`/proc/self/status`)]:[]}function uC(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=Ee({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}`}${fC(n.stderr)}`}}}}function dC(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 fC(e){let t=e.split(`
163
+ `).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const pC=`CC_CANDYBAR_RSS_LIMIT_MB`;function mC(e){let t=e[pC];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${pC} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function hC(e){return mC(e)*2}const gC=1024*1024;function _C(e){return mC(e)*gC}const vC={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function yC(e,t,n){let{prefix:r,suffix:i}=vC[t];return c.join(e,`${r}${n}${i}`)}function bC(e){for(let t of Object.keys(vC)){let{prefix:n,suffix:r}=vC[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function xC(e){let t=e.rssLimitBytes??512*gC,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 SC(e.log,`memory report`,()=>{let t=yC(e.snapshotDir,`memoryReport`,o);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),SC(e.log,`heap snapshot`,()=>{let t=yC(e.snapshotDir,`heapSnapshot`,o);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),SC(e.log,`artifact rotation`,()=>{wC(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 SC(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function CC(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=bC(t);if(n===null)return t;let{prefix:r,suffix:i}=vC[n];return t.slice(r.length,t.length-i.length)}function wC(e,t,n){let r=new Map;for(let t of e){let e=CC(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 TC(e,t,n={}){let i=Me();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:Q,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},captureMemoryReport:()=>cC(lC(process.platform,process.pid)),writeMemoryReport:(e,t)=>r.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>C.writeHeapSnapshot(e),listArtifacts:()=>{try{return r.readdirSync(i).filter(e=>bC(e)!==null).map(e=>c.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function EC(e={}){if(HC()!==null)return;let n=e.spawn??UC,r=zC();if(r.kind===`contended`){let e=OC();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),DC(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),DC(n);return}try{DC(n)}finally{VC()}}function DC(e){FC()&&kC(e)}function OC(){try{let e=r.statSync(Ve());return Date.now()-e.mtimeMs}catch{return null}}function kC(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
164
+ `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function AC(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function jC(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function MC(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 NC(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 PC(){try{r.unlinkSync(Ue())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function FC(){let e=He(),n=Ue(),r=MC(n),i=AC(IC(e),jC(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`),LC(e),NC(n,Math.min(r+1,5)),!0)}function IC(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function LC(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 RC=null;function zC(){let e=Ve();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 RC={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(!BC(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 BC(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function VC(){if(!RC)return;let{fd:e,path:t}=RC;RC=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function HC(){try{return r.mkdirSync(Me(),{recursive:!0}),null}catch(e){return`mkdir ${Me()}: ${e.message}`}}function UC(){let e=t.execPath,n=t.argv[1];return n?De({bin:e,args:[`--max-old-space-size=${hC(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const WC=`cc-candybar`,GC=`dispatch`,KC=`set-state`,qC=`step-state`,JC=`copy`,YC=`open-vscode`,XC=`toolbar-toggle`,ZC=`show-config-error`,QC=`show-config-warning`,$C=`set-config`,ew=`step-config`,tw=`save`,nw=`save-preset`,rw=`delete-preset`,iw=`reset-config`,aw=`apply-layout-op`,ow=`undo`,sw=`redo`,cw=`apply-update`,lw=`doctor-run`,uw=`doctor-fix`;function dw(e){return e.map(encodeURIComponent).join(`/`)}function fw(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function pw(e){return`${WC}://${GC}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${dw(e.args)}`)}`).join(`&`)}`}function mw(e){return new te(e).getAll(`e`).map(vw)}const hw=new Set([KC,iw]);function gw(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&_w(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function _w(e,t){if(e.verb!==t.verb||!hw.has(e.verb))return;let[n,r]=[vw(e.value),vw(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function vw(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const yw=`1.87.1`;function bw(){return c.join(f.homedir(),`.claude`,`settings.json`)}const xw=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function Sw(e){let t=xw.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 Cw(e){return e.join(`.`)}function ww([e,t,n],[r,i,a]){return e-r||t-i||n-a}const Tw=`@promptctl/cc-candybar`;async function Ew(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`?Sw(n.latest):Y}catch(e){return X(e instanceof Error?e.message:String(e))}}function Dw(e,t){let n=Sw(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=ww(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 Ow(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${Cw(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${Cw(t.installed)} is newer than the registry's latest release (${Cw(t.latest)}): an unpublished build.\n`};case`stale`:{let n=Cw(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${Cw(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 kw=`CCCandybarURLHandler`,Aw=[],jw={"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 Mw(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function Nw(e,t){return[e,...t].map(Mw).join(` `)}function Pw(){return c.join(f.homedir(),`Applications`,`${kw}.app`)}function Fw(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function Iw(){if(process.platform===`darwin`)return c.join(f.homedir(),`Library`,`Application Support`,`CCCandybar`);let e=process.env.XDG_DATA_HOME??c.join(f.homedir(),`.local`,`share`);return c.join(e,`cc-candybar`)}function Lw(){return c.join(Iw(),`bin`,`cc-candybar`)}function Rw(){return c.join(Iw(),`dist`,`index.mjs`)}function zw(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(`
165
+ `)}function Bw(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 Vw(t){let n=jw[`${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 Hw(e,t){c.resolve(e)!==c.resolve(t)&&r.copyFileSync(e,t)}function Uw(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 ${Tw}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function Ww(){let e=Bw(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=Vw(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(c.dirname(Rw()),{recursive:!0}),r.mkdirSync(c.dirname(Lw()),{recursive:!0}),Hw(e,Rw()),Hw(t.sourcePath,Lw()),r.chmodSync(Lw(),493),r.rmSync(c.join(Iw(),`url-handler.mjs`),{force:!0});let n=Uw(Lw());return process.stdout.write(`Staged cc-candybar v${yw} runtime at ${Iw()}\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:Lw(),distPath:Rw(),entryKind:n}}function Gw(){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>${WC}</string>`,` </array>`,` </dict>`,`</array>`].join(`
166
+ `)}]}function Kw(e){let t=Pw();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=Ee({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,zw(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 Gw())Ee({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of Gw()){let n=Ee({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 ${WC}:// with Launch Services\n`);let a=Ee({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(`✓ ${kw}.app installed and registered.\n`),process.stdout.write(` Test: open '${WC}://hello-world' && pbpaste\n`)}function qw(){Fw(),Kw(Ww().distPath)}function Jw(e,t=WC){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:JC,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function Yw(e){e||(process.stderr.write(`url-handle: missing URL argument.
167
+ `),process.exit(1));let t;try{t=Jw(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await iC(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(EC(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(Xw(n)+`
168
+ `),process.exit(1)}function Xw(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 Zw(){return`✓ install complete.
169
169
  Restart Claude Code to pick up the new statusline.
170
- Tip: every bar carries a settings menu — click it (${$s} by\n default) for quick actions, preset switching, edit mode, and clickable\n theme/look/style/wrap/padding controls.\n`}async function Zw(e){let t=e.includes(`--force`),n=e.filter(e=>e!==`--force`),r=n.length>0?n:[...kw],i=Uw();process.platform===`darwin`?Gw(i.distPath):process.stdout.write(`Skipping URL handler (cmd-click verbs are macOS-only).
171
- `),Qw(i.binPath,r,t),process.stdout.write(Xw());let a=Dw(ww,Ew(vw,await Tw(ww,fetch,`https://registry.npmjs.org`)));process[a.stream].write(a.text)}function Qw(e,t,n,i){let a=i??yw();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,jw(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:Mw(e,t)},ke(a,JSON.stringify(o,null,2)),process.stdout.write(`Updated ${a}\n`)}function $w(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 eT(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 tT(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 nT(e,t){let n=eT(e);if(n.kind===`owned`&&n.pid===t)try{r.unlinkSync(e)}catch{}}function rT(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 iT(e,t,n,r){let i=aT(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 aT(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 oT(e){let t=!1;function n(){let n=iT(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 sT(e,t=Ee){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 cT(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 lT(e,t=sT){let n=t(e);return n.kind===`start`?n.token:null}const uT=`CC_CANDYBAR_PARENT_PID`;function dT(e){let t=e[uT];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${uT} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function fT(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 pT(e){try{return t.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function mT(){let e=Number(process.env.CC_CANDYBAR_DAEMON_CEILING??``);return Number.isInteger(e)&&e>0?e:16}function hT(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 gT(e){try{return r.readdirSync(e).filter(e=>e.endsWith(`.json`)).map(t=>c.join(e,t))}catch{return[]}}function _T(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 vT(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 yT(e){if(!e.isolated)return{decision:hT(!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=hT(!0,vT(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 bT(e,t,n,r){let i=n(e);if(i!==null&&i.pid===t)try{r(e)}catch{}}function xT(e,t={}){return{isolated:!!process.env.CC_CANDYBAR_SOCKET,registryDir:Be(),ceiling:mT(),pid:process.pid,startTime:e,isSameLiveProcess:(e,t)=>cT(e,t,{readStartTime:sT,pidAlive:pT}),listFiles:gT,readEntry:_T,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?Pe:e=>{Pe(c.dirname(e)),Pe(e)},...t}}function ST(e){return e<32||e===127||e>=128&&e<=159}function CT(e){let t=``;for(let n of e)t+=ST(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function wT(e,t){let n=CT(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const TT=`\x1B[38;2;255;255;255m`,ET=`\x1B[48;2;200;40;40m`;function DT(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 OT={fg:DT(TT),bg:DT(ET)},kT={fg:DT(`\x1B[38;2;0;0;0m`),bg:DT(`\x1B[48;2;220;160;40m`)},AT={unicode:hi,ascii:{glyph:`>`,divider:`|`,lead:`<`,tail:`>`}},jT={unicode:{},ascii:{left:`(`,right:`)`}};function MT(e,t,n){switch(e){case`capsule`:return new _i(jT[t]);case`plain`:return new vi(n===void 0?{}:{separator:n});case`powerline`:return new gi(AT[t]);default:return e}}const NT=new Map;function PT(e){let t=JSON.stringify([e.style,e.charset,e.separator??null]),n=NT.get(t);if(n!==void 0)return n;let r=MT(e.style,e.charset,e.separator),i=e=>new H(`x`,{end:``,noWrap:!0,style:new B({bgcolor:e})}),a=e=>new H(xi(new oi(e,r),{colorSystem:null}).replace(/\n$/,``)).cellLength,o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return NT.set(t,s),s}function FT(e){return PT(e).chrome}function IT(e){return PT(e).seam}function LT(e,t){if(e.length===0)return``;let n=MT(t.style,t.charset,t.separator),r=t.colorCompatibility,i=t.wrap&&Number.isFinite(t.width)?xi(new Di([...e],{joiner:n}),{width:t.width,colorSystem:r}):xi(new oi([...e],n),{colorSystem:r});if(!i.endsWith(`
172
- `))throw Error(`renderStripCells: rich-js strip output did not end its last line`);return i.slice(0,-1)}function RT(e){return Math.min(20,e??20)}const zT={heading:`ERROR`,glyph:`⚠`,colors:OT},BT={heading:`WARNING`,glyph:`⚠`,colors:kT},VT={heading:`UPDATE`,glyph:`⬆`,colors:kT};function HT(e,t){return{text:CT(e),link:t}}function UT(e,t,n){let[r,...i]=[WT(e,zT,XC),t,WT(n,BT,ZC)].flat();return r===void 0?null:{channels:[r,...i]}}function WT(e,t,n){let r=fw([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>HT(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function GT(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
173
- `)}function KT(e,t,n,r){if(t===null)return e;let i=qT(r),a=t.channels.flatMap(e=>JT(e,i)),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[YT(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
174
- `);return e?`${l}\n${e}`:l}function qT(e){return{style:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function JT(e,t){let n=new B({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=Lt(Math.max(2,t.width-1)),i=(e,t)=>new H(`${e} `,{style:t,end:``,noWrap:!0});return e.lines.flatMap((a,o)=>LT([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=>Bt(e,r)).map(e=>i(e,t))})],t).split(`
175
- `))}function YT(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new B({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new H(e,{style:t,end:``,noWrap:!0}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(ne(a.path).href)):c(`full text unavailable: ${CT(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(CT(o),s.withLink(ne(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=H.fromFragments([...d,...p]).truncate(r.width);return m.noWrap=!0,LT([m],r)}const XT=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function ZT(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function QT(e,t){return r.readdirSync(t).filter(XT).sort().flatMap(n=>{let i=c.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?QT(e,i):[[c.relative(e,i).split(c.sep).join(`/`),ZT(i,a)]]})}function $T(e){let t=ie.createHash(`sha256`);for(let[n,r]of QT(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const eE=e=>e.slice(0,7);function tE(e){return c.dirname(c.dirname(e))}function nE(){return{version:vw,digest:`b8af4ab11d8997a8c414cc61cd82328a3626d2da694db6319db2d45a75a04a27`}}function rE(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 iE(e,t){try{let n=tE(w(e)),i=c.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=$T(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:rE(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var $=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};const aE=/^-?\d+$/;function oE(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function sE(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 cE(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!aE.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 lE(e,t,n){return r=>r?aE.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 uE(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=>!aE.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,seed:oE(r[0].seed,t,i)}}return{kind:`int`}}function dE(e){return e===`config`?`set-config`:`set-state`}function fE(e,t,n){return t.kind===`int`?cE(`menu page "${e}"`):t.kind===`range`?lE(t.min,t.max,`${n} stepper "${e}"`):sE(t.allowed,`${n} "${e}"`,dE(n))}function pE(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:uE(e,n,t)}))}function mE(e,t=`state`){let n=new Map(Object.entries(e).map(([e,t])=>[e,{validator:t,permanent:!0}]));function r(){let e=[];for(let[t,r]of n)r.permanent&&e.push(t);return e}return{register(e,i){if(!e)throw Error(`register: key is required`);if(e.includes(`/`))throw Error(`register: key "${e}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);let a=n.get(e);if(a){if(a.permanent)throw Error(`register: key "${e}" is a built-in ${t} key and cannot be re-claimed (built-in keys: ${[...r()].join(`, `)})`);let n=uE(e,[...a.specs,i],t);a.specs.push(i),a.merged=n,a.validator=fE(e,n,t)}else{let r=uE(e,[i],t);n.set(e,{permanent:!1,specs:[i],merged:r,validator:fE(e,r,t)})}let o=!0;return()=>{if(!o)return;o=!1;let r=n.get(e);if(!r||r.permanent)return;let a=r.specs.indexOf(i);a>=0&&r.specs.splice(a,1),r.specs.length===0?n.delete(e):(r.merged=uE(e,r.specs,t),r.validator=fE(e,r.merged,t))}},validate(e,r){let i=n.get(e);return i?i.validator(r):{ok:!1,reason:`unknown ${t} key "${e}" (have: ${[...n.keys()].join(`, `)})`}},listKeys(){return[...n.keys()]},listBaselineKeys(){return r()},rangeParamsFor(e){let t=n.get(e);if(!t||t.permanent||t.merged.kind!==`range`)return null;let{min:r,max:i,seed:a}=t.merged;return{min:r,max:i,seed:a}}}}const hE=mE({},`config`);function gE(){return hE.listKeys()}function _E(e,t){return hE.validate(e,t)}function vE(e){return hE.rangeParamsFor(e)}function yE(e,t,n){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:iS(e.from,n).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:[Wv({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Wv({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:iS(e.insertSegmentFrom,n).members.map(t=>Wv({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max,seed:oE(t.get(e.persist),e.min,e.max)}}]:[]}function bE(e){return jc(e.globals)}function xE(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?ay(n.persist):null;e?.scope===`preset-root`&&t.add(ry(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function SE(e){let t=bE(e),n=new Map([...nS(e),...Cy(e)]);return[...xE(e),...Object.values(e.actions).flatMap(e=>yE(e,t,n))]}function CE(e){return pE(SE(e),`config`)}function wE(e,t){return hE.register(e,t)}const TE=Sa(),EE=new Set(TE),DE=new Set(Ma),OE=e=>e?EE.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${TE.join(`, `)})`}:{ok:!1,reason:`theme name is required`},kE=e=>e?DE.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${Ma.join(`, `)})`}:{ok:!1,reason:`style name is required`},AE=new Set([`1`,`true`]),jE=new Set([`0`,`false`]),ME=mE({style:kE,theme:OE,"toolbar-expanded":e=>AE.has(e)?{ok:!0,value:`1`}:jE.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function NE(){return ME.listKeys()}function PE(e,t){return ME.register(e,t)}function FE(e,t){return ME.validate(e,t)}function IE(e){return ME.rangeParamsFor(e)}function LE(e,t,n){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:iS(e.from,n).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,seed:oE(t.get(e.set),e.min,e.max)}}]:[]}function RE(e){let t=new Set(ME.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function zE(e){let t=new Map,n=/^-?\d+$/;for(let r of Object.values(e.variables)){if(r.kind!==`state`)continue;let e=r.default;e!==void 0&&n.test(e)&&t.set(r.key,parseInt(e,10))}for(let[n,r]of jc(e.globals))t.set(n,r);return t}function BE(e){let t=zE(e),n=nS(e);return RE(Object.values(e.actions).flatMap(e=>LE(e,t,n)))}function VE(e){return pE(BE(e))}const HE=`update.dismissed`,UE=`updateNotice`;function WE(e){return e.kind===`source`?e.newer.digest:Sw(e.newer)}const GE=e=>`${e.version} [${eE(e.digest)}]`;function KE(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:GE(e.newer),running:GE(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:Sw(e.newer),running:Sw(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${ww}@${Sw(e.newer)}`,`install`]}}}}const qE={kind:`idle`},JE={kind:`running`};function YE(e,t,n){if(e===null)return[];let r=WE(e);if(!n.enabled||n.dismissed===r)return[];let i=KE(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(`
176
- `),c=fw([{verb:ZC,args:[s]}]),l=t.kind===`running`?HT(`[${i.busy}]`,c):HT(`[${i.act}]`,fw([{verb:sw,args:[n.sessionId]}]));return[{severity:VT,message:s,lines:[[HT(a,c),l,HT(`[dismiss]`,fw([{verb:GC,args:[n.sessionId,HE,r]}])),HT(`[disable]`,fw([{verb:QC,args:[n.sessionId,UE,`false`]}]))],...o.map(e=>[HT(e,c)])]}]}function XE(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 ZE(e){switch(e.kind){case`current`:return[`info`,`build: current ${GE(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${GE(e.source)}, running ${GE(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function QE(e){switch(e.kind){case`current`:return[`info`,`release: current ${Sw(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${Sw(e.latest)}, running ${Sw(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${Sw(e.installed)}, latest ${Sw(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function $E(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const eD=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function tD(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=eD(e.stderr)??e.error??eD(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function nD(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=qE,d=null,f=$E(s),p=$E(s),m=()=>XE(c,l);function h(){let e=m(),t=e===null?null:WE(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:PE(HE,{kind:`allow-list`,allowed:[t]})})}function g(){c=iE(t,nE),f(ZE(c)),h()}async function _(){l=Ew(vw,await Tw(ww,a,i)),p(QE(l)),h()}return{arm(){wE(UE,{kind:`allow-list`,allowed:[`false`]}),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>YE(m(),u,e),act(){let e=m();if(e===null)throw new $(`apply-update: nothing newer is known to apply`);let t=KE(e);if(u.kind===`running`)throw new $(`apply-update: already ${t.busy}`);u=JE,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),Te({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=qE,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=tD(n);u={kind:`failed`,identity:WE(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}var rD=class{static CACHE_DIR=O();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 D(`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`?(D(`Removing stale lock file ${e} for dead process ${i}`),r.unlinkSync(t),!1):(D(`Error checking process ${i} for lock ${e}:`,n),!0)}}catch(t){return D(`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`}),D(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await ae(50);else throw e}return D(`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),D(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&D(`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){D(`Failed to create cache directories:`,e)}}static createProjectHash(e){return T(`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)){D(`Cache for ${e} is locked, waiting...`),await ae(75);continue}try{let i=await r.promises.readFile(n,`utf-8`),a=JSON.parse(i);return!t||a.timestamp>=t?(D(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(a.data)):(D(`${e} cache outdated: cache=${a.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return D(`No shared ${e} usage cache found`),null;D(`Attempt ${a+1} failed to read ${e} cache: ${t.message}. Retrying...`),await ae(75)}}return D(`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)){D(`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`),D(`[CACHE-SET] ${e} disk cache stored`)}catch(t){D(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(i)}}};const iD={"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 aD=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 rD.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await rD.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new ee(this.GITHUB_PRICING_URL),n=E({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){D(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let r=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){D(`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)?(D(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),D(`Pricing last updated: ${n?.updated||`unknown`}`),e(i)):(D(`Invalid pricing data structure`),e(null))}catch(t){D(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{D(`Response error:`,t),e(null)})});n.on(`error`,t=>{D(`Request error:`,t),e(null)}),n.on(`timeout`,()=>{D(`Request timeout`),n.destroy(),e(null)}),n.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return D(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return D(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),D(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(D(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(iD).length} models`),this.executionCache=iD,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(iD).length} models`),iD)}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 D(`[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),D(`[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`}};function oD(e){if(!e)return 0;try{return o(e).mtimeMs}catch{return 0}}const sD=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 cD(e){return((...t)=>sD.run(()=>e(...t)))}const lD=cD(y),uD=cD(v),dD=cD(b);async function fD(e,t){return sD.run(async()=>{let n=null;try{n=await _(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=>{D(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}async function pD(e,t){return sD.run(async()=>{let n=null;try{n=await _(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=>{D(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}const mD=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function hD(e){if(typeof e==`string`)return mD.exec(e)?.[1]}function gD(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 _D(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=gD(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?hD(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 vD(){let e=[],t=process.env.CLAUDE_CONFIG_DIR;if(t&&t.split(`,`).forEach(t=>{let n=t.trim();a(n)&&e.push(n)}),e.length===0){let t=p(),n=d(t,`.config`,`claude`),r=d(t,`.claude`);a(n)&&e.push(n),a(r)&&e.push(r)}return e}async function yD(e){let t=[];for(let n of e){let e=d(n,`projects`);if(a(e))try{let n=await lD(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=d(e,r.name);t.push(n)}}catch(t){D(`Failed to read projects directory ${e}:`,t)}}return t}async function bD(e,t,n){let r=[],i=d(t,e,`subagents`);try{let t=(await lD(i)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let a of t){let t=d(i,a);if(n?.has(t)){r.push(t);continue}try{let n=(await uD(t,`utf-8`)).split(`
177
- `)[0];n&&JSON.parse(n).sessionId===e&&r.push(t)}catch{D(`Failed to check agent file ${t}`)}}}catch(e){D(`Failed to read subagents directory ${i}:`,e)}return r}function xD(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 SD=new Map;async function CD(e){try{let t=await dD(e),n=t.size,r=SD.get(e);if(r&&r.mtime===t.mtimeMs&&r.size===n)return D(`[parse-cache] hit ${e}`),SD.delete(e),SD.set(e,r),r.entries;let i;return n>1048576?(D(`Using streaming parser for large file ${e} (${Math.round(n/1024)}KB)`),i=await OD(e)):i=await ED(e),D(`Parsed ${i.length} entries from ${e}`),n>5242880?i:(SD.delete(e),SD.size>=16&&SD.delete(SD.keys().next().value),SD.set(e,{mtime:t.mtimeMs,size:n,entries:i}),i)}catch(t){if(t.code===`ENOENT`)return D(`Transcript not present yet: ${e}`),[];throw t}}function wD(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:_D(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 TD(e){let t=[];for(let n of e.split(`
178
- `))if(n.trim())try{let e=wD(JSON.parse(n));e&&t.push(e)}catch(e){D(`Failed to parse JSONL line: ${e}`);continue}return t}async function ED(e){return TD(await uD(e,`utf-8`))}async function DD(e,t){let n=await fD(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:TD(r.subarray(0,c+1).toString(`utf-8`)),cursor:{offset:i+c+1,mtimeMs:a,ino:o},reset:s})}async function OD(e){return new Promise((t,n)=>{let r=[],a=i(e,{encoding:`utf8`}),o=oe({input:a,crlfDelay:1/0});o.on(`line`,e=>{let t=e.trim();if(t)try{let e=wD(JSON.parse(t));e&&r.push(e)}catch(e){D(`Failed to parse JSONL line: ${e}`)}}),o.on(`close`,()=>{t(r)}),o.on(`error`,t=>{D(`Streaming parser error for ${e}:`,t),n(t)}),a.on(`error`,t=>{D(`File stream error for ${e}:`,t),n(t)})})}var kD=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 AD(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 jD={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},MD={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function ND(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function PD(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function FD(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}async function ID(e,t,n,r){let i=ND(new Date(PD())),a=e&&!t?e:void 0,o=a?.entries??0,s=a?.cost??0,c=a?{...a.breakdown}:FD(),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 aD.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=ND(new Date(e.timestamp));if(r<i)continue;let a=l.get(r)??{...jD};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 LD(e){let t=0,n=0,r=FD(),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)??{...jD};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:MD,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 RD(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 zD=class{entries=new Map;flight=new kD;seeded=new Map;speedRings=new Map;speedFlight=new kD;maxEntries;staleAgeMs;hits=0;misses=0;sweeps=0;seeds=0;sweepTimer=null;constructor(e={}){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:MD,i=t?.cost?.total_cost_usd??null;return J({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e){let t=ND(new Date);try{await this.ensureSeeded(t)}catch(e){return X(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let n=await this.ingest(e?.session_id??``,e?.transcript_path);if(n.kind===`failed`)return n;let r={...jD},i=!1;for(let e of this.entries.values()){i||=e.days.has(t);let n=e.days.get(t)??jD;r.cost+=n.cost,r.input+=n.input,r.output+=n.output,r.cacheCreation+=n.cacheCreation,r.cacheRead+=n.cacheRead}return i?J({cost:r.cost,tokens:r.input+r.output+r.cacheCreation+r.cacheRead,tokenBreakdown:{input:r.input,output:r.output,cacheCreation:r.cacheCreation,cacheRead:r.cacheRead},date:t}):Y}async observeSpeed(e,t,n){let r=oD(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,r);if(i.kind===`failed`)return i;let a=AD(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??oD(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 bD(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 DD(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 ID(r,l,s,c)),e===t&&(a=c.mtimeMs)}return J({files:i,...LD(i),mainMtime:a})}ensureSeeded(e){let t=this.seeded.get(e);if(t)return t;this.seeded.clear();let n=this.seed(e);return this.seeded.set(e,n),n.catch(()=>{this.seeded.get(e)===n&&this.seeded.delete(e)}),n}async seed(e){let t=PD(),n=await yD(vD()),r=[];for(let e of n){let n;try{n=await lD(e)}catch{continue}for(let i of n){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a;try{a=(await dD(n)).mtimeMs}catch{continue}a<t||r.push({sessionId:i.slice(0,-6),path:n,mtime:a})}}await RD(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,e.mtime);t.kind===`failed`&&Q(`warn`,`usageStore seed: ${t.reason}`)}),this.seeds++,Q(`info`,`usageStore seed sessions=${r.length}`)}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++,Q(`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),Q(`info`,`usageStore evict ${e}`)}}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.entries.clear(),this.seeded.clear(),this.speedRings.clear()}};const BD=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function VD(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 HD(e){let t=await UD(e);return t.kind===`ok`?J(Math.floor((t.value+36e5)/1e3)):t}async function UD(e){for(let t of[65536,1048576]){let n=await pD(e,t);if(n.kind!==`ok`)return n;let r=WD(n.value.buf,n.value.fromStart);if(r!=null)return J(r);if(n.value.fromStart)return Y}return Y}function WD(e,t){let n=e.toString(`utf8`).split(`
179
- `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!BD.test(t))continue;let r=VD(t);if(r!=null)return r}return null}const GD=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,KD=`{{ \$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 (${GD}) (basename .project_dir) (ne (${GD}) "") }}{{ end }}{{ end }}{{ abbreviatePath \$dir }}`,qD={globals:{palette:`tokyo-night`},variables:{...Lv,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},"session.budget.amount":{kind:`literal`,value:0},"session.budget.warningThreshold":{kind:`literal`,value:80},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"today.budget.amount":{kind:`literal`,value:50},"today.budget.warningThreshold":{kind:`literal`,value:80},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"block.budget.warningThreshold":{kind:`literal`,value:80},"block.budget.heatThreshold":{kind:`literal`,value:50},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"weekly.budget.warningThreshold":{kind:`literal`,value:80},"weekly.budget.heatThreshold":{kind:`literal`,value:50},"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},"burn.eta.warnMinutes":{kind:`literal`,value:60},"burn.eta.errorMinutes":{kind:`literal`,value:30},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``}},segments:{directory:{description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project.",template:KD},model:{description:`The active model's display name.`,template:`✱ {{ formatModelName .model.display_name }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{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:`{{ readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3 }}`,when:`{{ ne .git.branch "" }}`},gitPr:{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:{description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:Wy(``).template},themeSwitcher:{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:{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" .session.budget.amount "warn" .session.budget.warningThreshold) }}`},today:{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" .today.budget.amount "warn" .today.budget.warningThreshold) }}`},block:{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) .block.budget.heatThreshold "warning" .block.budget.warningThreshold "error" }}`,when:`{{ gt .block.resetsAt 0 }}`},weekly:{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) .weekly.budget.heatThreshold "warning" .weekly.budget.warningThreshold "error" }}`,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{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" .burn.eta.errorMinutes "warning" .burn.eta.warnMinutes (tint) }}`,when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{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:{description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,when:`{{ ne .speed.history "" }}`},cacheTimer:{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) ${Qi} }}`,when:`{{ gt .cache.expiresAt 0 }}`},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 }}`},metrics:{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:{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:`segment`,name:`context`},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...Wy(``).actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]}},looks:{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:`segment`,name:`context`},{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`}]}]}}},editGlobals:{style:`plain`,default_separator:` | `},helpers:{gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Qi}) .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 ne .git.repoName "" }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if ne .git.operation "" }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if ne .git.sha "" }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if 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 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 ne .git.upstream "" }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if gt .git.stash 0 }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ if gt .git.timeSinceCommit 0 }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:`{{ if ge . 1000000 }}{{ printf "%.1f" (divf . 1000000) }}M{{ else if ge . 1000 }}{{ printf "%.1f" (divf . 1000) }}K{{ else }}{{ . }}{{ end }}`,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 .)) }}`}},JD=new Set([qD.globals.palette,...Object.values(qD.segments).map(e=>e.palette)].filter(e=>e!==void 0)),YD=Ys(AS(`<default>`,JSON.stringify(qD),JD),qD),XD=Yv(YD.presets);function ZD(e){return XD.includes(e)}function QD(e,t,n){let r=Xv(t(`preset`),e.globals.preset,e.presets),i=$v(e,r),a=t(`edit.mode`)===`open`?e.editGlobals:{};return{preset:r,presetCustomized:n(r),theme:Zx(a.palette,t(`theme`),i.palette),look:ja(a.look,t(`look`),i.look,e.looks),style:Pa(a.style,t(`style`),i.style),progression:Ka(a.progression,t(`progression`),i.progression),separator:a.default_separator??i.default_separator,autoWrap:$a(a.autoWrap,t(`autoWrap`),i.autoWrap),padding:eo(a.padding,t(`padding`),i.padding),charset:Ra(a.charset,t(`charset`),i.charset),updateNotice:a.updateNotice??i.updateNotice??!0,colorCompatibility:Ha(a.colorCompatibility,t(`colorCompatibility`),i.colorCompatibility)}}function $D(e,t){return{style:e.style,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,charset:e.charset,width:t}}function eO(e){return{theme:e.theme,look:e.look,preset:e.preset,progression:e.progression}}function tO(e){return{preset:{effective:e.preset,customized:e.presetCustomized,bundled:ZD(e.preset)},style:{effective:e.style},progression:{effective:e.progression},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding}}}const nO=10*1e3;function rO(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 iO(e,t){if(!(t<60))return e*3600/t}function aO(e,t,n,r){let i=r-t;if(i<50||i>nO)return;let a=n-e;if(!(a<=0))return a*1e3/i}function oO(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=aO(t.input,t.atMs,n.input,n.atMs),i=aO(t.output,t.atMs,n.output,n.atMs),a=aO(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 sO(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>nO)continue;let o=aO(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function cO(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function lO(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`,()=>cO(f.hostname())),i=n(`user`,()=>f.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function uO(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=>Dg(t,e.helpers).keys();for(let n of Qo(Qv(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 o=new Set;for(;r.length>0;){let e=r.pop();for(let t of fO(n,e)){if(i.has(t))continue;i.add(t);let e=n.get(t);if(e){if(e.kind===`input`)o.add(e.path);else if(e.kind===`template`)for(let t of a(e.template))r.push(t)}}}return o}function dO(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=uO(e,n);return t.set(n,i),i}}function fO(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 pO(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function mO(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 hO(e,t,n,r,i,a,o){let s=e=>pO(r,e),c=(t.clock??(()=>new Date))().getTime(),l=(e,t,n)=>t?n().catch(t=>X(`${e}: ${String(t)}`)):Promise.resolve(Y),[u,d,f,p,m,h,g,_,v]=await Promise.all([l(`git`,s(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,mO(r),e.workspace?.project_dir)),l(`session`,s(`session.cost`)||s(`session.tokens`)||s(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),l(`today`,s(`today`),()=>t.usageStore.getTodayInfo(e)),l(`context`,s(`context`),()=>t.contextProvider.getContextInfo(e)),l(`metrics`,s(`metrics`)||s(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),l(`activity`,s(`activity`),()=>t.activityProvider.getActivityInfo(e.session_id,e)),l(`tmux`,s(`tmux`),()=>t.tmuxService.getSessionId()),l(`cache`,s(`cache`),()=>HD(e.transcript_path)),l(`speed`,s(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,c))]),y=[],b=e=>{if(e.kind===`failed`){y.push(e.reason);return}return e.kind===`ok`?e.value:void 0},x=bO(u);y.push(...x.failures);let S=lO(a);y.push(...S.failures);let C=b(d),ee=b(f),te=b(p),w=b(m),ne=b(h),re=b(g),ie=b(_);for(let e of y)t.log(`warn`,`provider fetch failed: ${e}`);let T=e.rate_limits?.five_hour,E=e.rate_limits?.seven_day,ae=T?rO(T.used_percentage,T.resets_at,18e6,c):void 0,oe=E?rO(E.used_percentage,E.resets_at,6048e5,c):void 0,se=C?.session.cost,ce=w?.sessionDuration,le=s(`burn`)&&se!=null&&ce!=null?iO(se,ce):void 0,ue=b(v),de=ue===void 0?void 0:oO(ue),fe=ue===void 0?void 0:sO(ue),pe=de!==void 0||fe!==void 0?{...de,...fe!==void 0&&{history:fe}}:void 0,me=yO(process.env.HOME??process.env.USERPROFILE),he=e.workspace?{...e.workspace,current_dir:yO(e.workspace.current_dir)??``,project_dir:yO(e.workspace.project_dir)??``}:e.workspace,D=C===void 0?void 0:vO({cost:C.session.cost,tokens:C.session.tokens}),ge=ee===void 0?void 0:{cost:ee.cost,tokens:ee.tokens},_e=w===void 0?void 0:vO({lastResponseTime:w.lastResponseTime,responseTime:w.responseTime,sessionDuration:w.sessionDuration,messageCount:w.messageCount,linesAdded:w.linesAdded,linesRemoved:w.linesRemoved}),ve=ne===void 0?void 0:gO(ne);return{...e,...he!==void 0&&{workspace:he},...me!==void 0&&{home:me},...x.git!==void 0&&{git:x.git},...re!==void 0&&{tmux:{session:re}},host:S.host,...tO(i),history:t.history(e.session_id),unsaved:o,...D!==void 0&&{session:D},...ge!==void 0&&{today:ge},...le!==void 0&&{burn:{costPerHour:le}},...pe!==void 0&&{speed:pe},...s(`block`)&&T!==void 0&&{block:{nativeUtilization:T.used_percentage,resetsAt:T.resets_at,...ae!==void 0&&{etaMinutes:ae}}},...E!==void 0&&{weekly:{percentage:E.used_percentage,resetsAt:E.resets_at,...oe!==void 0&&{etaMinutes:oe}}},...ie!==void 0&&{cache:{expiresAt:ie}},...te!==void 0&&{context:{totalTokens:te.totalTokens,contextLeft:te.contextLeftPercentage}},..._e!==void 0&&{metrics:_e},...ve!==void 0&&{activity:ve}}}function gO(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=_O(e.running),i=_O(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 _O(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function vO(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 yO(e){return e===void 0||e.length===0||c.sep!==`\\`?e:e.replace(/\\/g,`/`)}function bO(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}}function xO(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function SO(e,t){let n=H.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function CO(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:n.truncateMarker}):e.cellLength<t&&e.align(n.justify,t)}function wO({text:e,trail:t}){if(t===void 0)return e;let n=SO([e,t]);return n.style=e.style,n}function TO(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s,trail:c=[]}=t;if(e.length===0)return[];let l=SO(e,o).pad(s),u=c.length===0?{}:{trail:SO([...c,new H(` `.repeat(s))],o)};if(n===`auto`)return[{text:l,...u}];let d={justify:r,truncate:i,truncateMarker:a};return n===`fill`?[{text:l,fill:d,...u}]:(CO(l,n,d),[{text:l,...u}])}const EO=RegExp(`\\x1b\\[[0-9;]*m|${Jr.source}`,`g`);function DO(e){return k(e.replace(EO,``))}function OO(e,t){let n=e.map(wO),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=LT(n,t).split(`
180
- `);if(i.length>1)return n;let a=Math.max(0,t.width-DO(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];CO(l,l.cellLength+c,i),n[t]=wO(e[t])}),n}function kO(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=AO(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(MO(a.style).link){i();let e=AO([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function AO(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>jO(e,t)):e,r=H.fromFragments(n);return r.end=``,r.noWrap=!0,n.length===1?r.style=n[0].style:t!==void 0&&!t.isNull&&(r.style=t),r}function jO(e,t){let n=e.copy();return n.style=t.add(MO(e.style)),n}function MO(e){return e instanceof B?e:B.parse(e)}var NO=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function PO(e,t,n,r,i){let{palette:a,tint:o}=e,s=FO(n,i),c=s===void 0?o:IO(a,s,`bg`);e.bg=c;let l=FO(r,i),u=l===void 0?$i(a,c,t):IO(a,l,`fg`);return new B({bgcolor:P.fromRgba(c),color:P.fromRgba(u)})}function FO(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function IO(e,t,n){try{return Vn(e,t)}catch(e){throw e instanceof Rn?new NO(t,n,e.message):e}}function LO(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,RO(e,t,o,n,r,i));return i}function RO(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=iS(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf}}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=Bv.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=iS(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf}}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=iS(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:BO(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:BO(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(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:BO(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 zO(e){return e.kind===`do`?zO(e.head):e}function BO(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function VO(e,t){return e.has(t)?Bg(e.read(t)):``}function HO(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function UO(e,t,n,r){let i=new H(e,{style:B.combine([r,new B({link:t,bold:n})])});return i.noWrap=!0,i.end=``,i}function WO(e,t){return Math.max(e.members.indexOf(VO(t,e.stateVar)),0)}function GO(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=VO(r,e.stateVar);return{effects:[{verb:GC,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=VO(r,e.stateVar);return{effects:[{verb:GC,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=VO(r,e.stateVar);return{effects:[{verb:GC,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(WO(e,r)+1)%e.members.length];return{effects:[{verb:GC,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:KC,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:qC,args:[HO(e.text,j_(r))]}],active:!1};case`open`:return{effects:[{verb:JC,args:[HO(e.target,j_(r))]}],active:!1};case`persist-literal`:{let t=VO(r,e.stateVar);return{effects:[{verb:QC,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=VO(r,e.stateVar);return{effects:[{verb:QC,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(WO(e,r)+1)%e.members.length];return{effects:[{verb:QC,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:$C,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:rw,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:aw,args:[i]}],active:!1};case`redo`:return{effects:[{verb:ow,args:[i]}],active:!1};case`save`:return{effects:[{verb:ew,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:tw,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:nw,args:[i,HO(e.name,j_(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:cw,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:lw,args:[i,e.check]}],active:!1};case`layout-op`:return{effects:[{verb:iw,args:[i,e.key,Wv(e.op)]}],active:!1};case`do`:{let a=GO(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>GO(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:iw,args:[i,e.key,Wv(r)]}],active:!1}}}}function KO(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:tc(`action "${e}"`,n,t.members.length,WO(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 qO(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}=KO(e,zO(r),t,i),{effects:s,active:c}=GO(r,a,o,i,VO(i,`session.id`));return UO(a,fw(s),c)}function JO(e){return{action:{fn:(t,...n)=>qO(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function YO(e,t){return UO(`✕`,fw([{verb:GC,args:[VO(e,`session.id`),t,Qs]}]),!1)}function XO(e,t,n){return new B({bgcolor:P.fromRgba(t),color:P.fromRgba($i(e,t,n))})}function ZO(e,t,n){return XO(e.palette,fa(e.palette,e.disclosure,[t],n),n)}function QO(e,t,n,r,i){return r===void 0?n=>ZO(e,{...n,distribution:t},i):(e,t)=>$O(r(t,n),i)}function $O(e,t){let n=Ui(e,`background`);return new B({bgcolor:P.fromRgba(n),color:P.fromRgba(Jn(Ui(e,`primary`),n,4.5,t))})}function ek(e){return{current:null,drawnAt:e}}function tk(e,t,n,r,i){let a={segName:t,palette:n,disclosure:r,tint:i,bg:void 0,drops:[]};return e.current=a,a}function nk(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 rk(e){return new H(e).cellLength}function ik(e){return Math.max(1,e.width-e.chromeCols-2*e.padding)}function ak(e){return Math.max(1,ik(e)-(rk(`✕`)+2*e.padding+e.seamCols))}function ok(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 sk(e,t){let n=[];for(let t of e)n.length>0&&n.push(new H(` `)),n.push(t);let r=H.fromFragments(n);return r.noWrap=t,r.end=``,r}function ck(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 lk(e,t,n){let r=e.compiled.get(t),i=r&&zO(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 uk(e,t,n,r,i,a,o){let s=lk(a,e,`picker`),c=a.compiled.get(e),l=a.store,u=VO(l,`session.id`),d=`stateVar`in s?VO(l,s.stateVar):void 0,f=s.options.map(rk),p=i?ik(a):1/0,m=rk(`✕`)+1,h=rk(`←`)+1+rk(`→`)+1,g=ok(f,p,m),_=g.length>1?ok(f,p,m+h):g,v=parseInt(VO(l,t.stateVar),10),y=Number.isInteger(v)?Math.max(0,Math.min(v,_.length-1)):0,b=_[y]??[],x=e=>fw([{verb:GC,args:[u,t.key,String(e)]}]),S=n.flatMap(([e,t])=>[e,t]),C=fw([{verb:GC,args:[u,...S]}]),ee=r?[{verb:GC,args:[u,...S]}]:[],te=e=>fw([...GO(c,e,e,l,u).effects,...ee]),w=[UO(`✕`,C,!1)];y>0&&w.push(UO(`←`,x(y-1),!1));for(let e of b){let t=s.options[e];w.push(UO(t,te(t),t===d,o({index:e,count:s.options.length},t)))}return y<_.length-1&&w.push(UO(`→`,x(y+1),!1)),sk(w,i)}function dk(e,t){return{picker:{fn:(n,r,i,a)=>{let o=ck(e,r,`set-int`,`an int action ({ set, int: true })`);return uk(n,{key:o.key,stateVar:o.stateVar},[[o.key,`-1`]],i===!0,a===!0,e,QO(nk(t,`{{ picker }}`),Li(void 0),e.basePalette,lk(e,n,`picker`).paletteOf,t.drawnAt()))},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}function fk(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+rk(e(-(s+1)))+1+rk(e(s+1))+1;if(t>r)break;o=t,s+=1}return s}function pk(e,t,n,r,i){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let a=n.store;if(!a.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let o=n.compiled.get(e),s=VO(a,`session.id`),{options:c}=t,l=c.length,u=VO(a,t.stateVar),d=Math.max(c.indexOf(u),0),f=e=>((d+e)%l+l)%l,p=e=>c[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let n=fw(GO(o,p(e),p(e),a,s).effects);return m.set(e,n),n},g=e=>UO(p(e),h(e),p(e)===u,r({index:f(e),count:l},p(e))),_=fk(p,l,rk(`◀`)+1+rk(p(0))+1+rk(`▶`),ak(n),i),v=e=>Array.from({length:_},(t,n)=>g(e*(n+1)));return sk([...v(-1).reverse(),UO(`◀`,h(-1),!1),g(0),UO(`▶`,h(1),!1),...v(1)],!0)}function mk(e,t){return{carousel:{fn:(n,r,...i)=>{if(i.length>0)throw Error(`carousel "${n}": takes at most one neighbours count after the action name, got ${1+i.length}`);if(r!==void 0&&!(Number.isInteger(r)&&r>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(r)}`);let a=r??1/0,o=lk(e,n,`carousel`);return pk(n,o,e,QO(nk(t,`{{ carousel }}`),Li(void 0),e.basePalette,o.paletteOf,t.drawnAt()),a)},argTypes:[`string`,`float`],returnType:`T`}}}const hk=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function gk(e,t,n){let r=aa(e,{hue:Ai,depth:0},n);return[U(t).map((t,n)=>({text:hk[n%hk.length],colour:Wi(e,t)})),[{text:`▾ open`,colour:r.state},{text:`menu`,colour:r.plane}],[{text:`warn`,colour:Ui(e,`warning`)},{text:`error`,colour:Ui(e,`error`)}]]}function _k(e,t,n,r){let i=gk(e,t,n).flatMap((t,r)=>t.map(({text:t,colour:i},a)=>({gap:r>0&&a===0?` `:``,cell:new H(` ${t} `,{style:XO(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 H(e)),a.push(t)}let s=H.fromFragments(a);return s.noWrap=!0,s.end=``,s}function vk(e,t){return{themePreview:{fn:()=>_k(e.palette,e.progression,t.drawnAt(),ak(e)),argTypes:[],returnType:`T`}}}const yk=e=>e.slice(e.lastIndexOf(`.`)+1),bk=(e,t)=>{let n=new H(yk(e));return n.truncate(t,{marker:`…`}),n.plain};function xk(e,t){let n=e.map(e=>e.map(({name:e})=>rk(yk(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 Sk(e,t,n,r){let i=xk(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new H(` ${bk(s,i)} `,{style:XO(l,ga(l,{kind:`bar`,progression:t,address:c},n).tint,n)});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=H.fromFragments(a.flatMap((e,t)=>t===0?e:[new H(`
181
- `),...e]));return o.noWrap=!0,o.end=``,o}function Ck(e,t){return{layoutPreview:{fn:()=>Sk(e.layout(),e.progression,t.drawnAt(),ak(e)),argTypes:[],returnType:`T`}}}function wk(e,t,n,r){let i=nk(r.activeSegment,`{{ menu }}`),a=r.action,o=Uh(i.segName,e,n.key),s=Kh(o),c=Hh(e),l=VO(a.store,o)===c,u=VO(a.store,`session.id`),d=l?Qs:c,f=UO(tc(`{{ menu "${e}" }}`,t,2,+!!l),fw([{verb:GC,args:[u,o,d,s,`0`]}]),!1);return i.drops.push(...l?[uk(e,{key:s,stateVar:s},[[o,Qs],[s,`0`]],n.closeOnPick,n.paged,a,QO(i,n.distribution,a.basePalette,lk(a,e,`menu`).paletteOf,r.activeSegment.drawnAt()))]:[]),f}const Tk=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Ek(e,t){let n=t[t.length-1],r=Tk(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:Xh(r??{})}}function Dk(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=Ek(t,n);return wk(t,r,i,e)},argTypes:[`string`,`value`],returnType:`T`}}}function Ok(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=kk(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 H(t?i:a,{style:l===void 0?void 0:new B({color:l})}))}let l=H.fromFragments(c);return l.end=``,l.noWrap=!0,l}function kk(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 Ak(e){let t={fn:(()=>{let t=nk(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:[],returnType:`string`},n={fn:(()=>nk(e,`{{ tint }}`).tint.hex),argTypes:[],returnType:`string`},r=f_(()=>nk(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),i={fn:((e,t,n,i,a,o,...s)=>Ok({value:e,max:t,width:n,filled:i,empty:a,colourAt:o===void 0||s.length===0?void 0:e=>String(r.ramp.fn(e,o,...jk(s)))})),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`,`string`],returnType:`T`};return{...r,bgOf:t,tint:n,gauge:i}}function jk(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 Mk(e){let t=[],n=[];for(let r of e){if(!r.contains(`
170
+ Tip: every bar carries a settings menu — click it (${$s} by\n default) for quick actions, preset switching, edit mode, and clickable\n theme/look/style/wrap/padding controls.\n`}async function Qw(e){let t=e.includes(`--force`),n=e.filter(e=>e!==`--force`),r=n.length>0?n:[...Aw],i=Ww();process.platform===`darwin`?Kw(i.distPath):process.stdout.write(`Skipping URL handler (cmd-click verbs are macOS-only).
171
+ `),$w(i.binPath,r,t),process.stdout.write(Zw());let a=Ow(Tw,Dw(yw,await Ew(Tw,fetch,`https://registry.npmjs.org`)));process[a.stream].write(a.text)}function $w(e,t,n,i){let a=i??bw();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,Mw(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:Nw(e,t)},ke(a,JSON.stringify(o,null,2)),process.stdout.write(`Updated ${a}\n`)}function eT(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 tT(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 nT(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 rT(e,t){let n=tT(e);if(n.kind===`owned`&&n.pid===t)try{r.unlinkSync(e)}catch{}}function iT(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 aT(e,t,n,r){let i=oT(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 oT(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 sT(e){let t=!1;function n(){let n=aT(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 cT(e,t=Ee){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 lT(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 uT(e,t=cT){let n=t(e);return n.kind===`start`?n.token:null}const dT=`CC_CANDYBAR_PARENT_PID`;function fT(e){let t=e[dT];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${dT} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function pT(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 mT(e){try{return t.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function hT(){let e=Number(process.env.CC_CANDYBAR_DAEMON_CEILING??``);return Number.isInteger(e)&&e>0?e:16}function gT(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 _T(e){try{return r.readdirSync(e).filter(e=>e.endsWith(`.json`)).map(t=>c.join(e,t))}catch{return[]}}function vT(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 yT(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 bT(e){if(!e.isolated)return{decision:gT(!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=gT(!0,yT(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 xT(e,t,n,r){let i=n(e);if(i!==null&&i.pid===t)try{r(e)}catch{}}function ST(e,t={}){return{isolated:!!process.env.CC_CANDYBAR_SOCKET,registryDir:Be(),ceiling:hT(),pid:process.pid,startTime:e,isSameLiveProcess:(e,t)=>lT(e,t,{readStartTime:cT,pidAlive:mT}),listFiles:_T,readEntry:vT,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?Pe:e=>{Pe(c.dirname(e)),Pe(e)},...t}}function CT(e){return e<32||e===127||e>=128&&e<=159}function wT(e){let t=``;for(let n of e)t+=CT(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function TT(e,t){let n=wT(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const ET=`\x1B[38;2;255;255;255m`,DT=`\x1B[48;2;200;40;40m`;function OT(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 kT={fg:OT(ET),bg:OT(DT)},AT={fg:OT(`\x1B[38;2;0;0;0m`),bg:OT(`\x1B[48;2;220;160;40m`)},jT={unicode:hi,ascii:{glyph:`>`,divider:`|`,lead:`<`,tail:`>`}},MT={unicode:{},ascii:{left:`(`,right:`)`}};function NT(e,t,n){switch(e){case`capsule`:return new _i(MT[t]);case`plain`:return new vi(n===void 0?{}:{separator:n});case`powerline`:return new gi(jT[t]);default:return e}}const PT=new Map;function FT(e){let t=JSON.stringify([e.style,e.charset,e.separator??null]),n=PT.get(t);if(n!==void 0)return n;let r=NT(e.style,e.charset,e.separator),i=e=>new H(`x`,{end:``,noWrap:!0,style:new B({bgcolor:e})}),a=e=>new H(xi(new oi(e,r),{colorSystem:null}).replace(/\n$/,``)).cellLength,o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return PT.set(t,s),s}function IT(e){return FT(e).chrome}function LT(e){return FT(e).seam}function RT(e,t){if(e.length===0)return``;let n=NT(t.style,t.charset,t.separator),r=t.colorCompatibility,i=t.wrap&&Number.isFinite(t.width)?xi(new Di([...e],{joiner:n}),{width:t.width,colorSystem:r}):xi(new oi([...e],n),{colorSystem:r});if(!i.endsWith(`
172
+ `))throw Error(`renderStripCells: rich-js strip output did not end its last line`);return i.slice(0,-1)}function zT(e){return Math.min(20,e??20)}const BT={heading:`ERROR`,glyph:`⚠`,colors:kT},VT={heading:`WARNING`,glyph:`⚠`,colors:AT},HT={heading:`UPDATE`,glyph:`⬆`,colors:AT};function UT(e,t){return{text:wT(e),link:t}}function WT(e,t,n){let[r,...i]=[GT(e,BT,ZC),t,GT(n,VT,QC)].flat();return r===void 0?null:{channels:[r,...i]}}function GT(e,t,n){let r=pw([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>UT(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function KT(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
173
+ `)}function qT(e,t,n,r){if(t===null)return e;let i=JT(r),a=t.channels.flatMap(e=>YT(e,i)),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[XT(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
174
+ `);return e?`${l}\n${e}`:l}function JT(e){return{style:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function YT(e,t){let n=new B({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=Lt(Math.max(2,t.width-1)),i=(e,t)=>new H(`${e} `,{style:t,end:``,noWrap:!0});return e.lines.flatMap((a,o)=>RT([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=>Bt(e,r)).map(e=>i(e,t))})],t).split(`
175
+ `))}function XT(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new B({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new H(e,{style:t,end:``,noWrap:!0}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(ne(a.path).href)):c(`full text unavailable: ${wT(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(wT(o),s.withLink(ne(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=H.fromFragments([...d,...p]).truncate(r.width);return m.noWrap=!0,RT([m],r)}const ZT=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function QT(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function $T(e,t){return r.readdirSync(t).filter(ZT).sort().flatMap(n=>{let i=c.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?$T(e,i):[[c.relative(e,i).split(c.sep).join(`/`),QT(i,a)]]})}function eE(e){let t=ie.createHash(`sha256`);for(let[n,r]of $T(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const tE=e=>e.slice(0,7);function nE(e){return c.dirname(c.dirname(e))}function rE(){return{version:yw,digest:`711c2c9f1ca4eab1b48e6740714e4503a93fd750d31c58729131c56d4be48372`}}function iE(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 aE(e,t){try{let n=nE(w(e)),i=c.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=eE(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:iE(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var $=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};const oE=/^-?\d+$/;function sE(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 cE(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!oE.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 lE(e,t,n){return r=>r?oE.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 uE(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=>!oE.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 dE(e){return e===`config`?`set-config`:`set-state`}function fE(e,t,n){return t.kind===`int`?cE(`menu page "${e}"`):t.kind===`range`?lE(t.min,t.max,`${n} stepper "${e}"`):sE(t.allowed,`${n} "${e}"`,dE(n))}function pE(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:uE(e,n,t)}))}function mE(e,t=`state`){let n=new Map(Object.entries(e).map(([e,t])=>[e,{validator:t,permanent:!0}]));function r(){let e=[];for(let[t,r]of n)r.permanent&&e.push(t);return e}return{register(e,i){if(!e)throw Error(`register: key is required`);if(e.includes(`/`))throw Error(`register: key "${e}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);let a=n.get(e);if(a){if(a.permanent)throw Error(`register: key "${e}" is a built-in ${t} key and cannot be re-claimed (built-in keys: ${[...r()].join(`, `)})`);let n=uE(e,[...a.specs,i],t);a.specs.push(i),a.merged=n,a.validator=fE(e,n,t)}else{let r=uE(e,[i],t);n.set(e,{permanent:!1,specs:[i],merged:r,validator:fE(e,r,t)})}let o=!0;return()=>{if(!o)return;o=!1;let r=n.get(e);if(!r||r.permanent)return;let a=r.specs.indexOf(i);a>=0&&r.specs.splice(a,1),r.specs.length===0?n.delete(e):(r.merged=uE(e,r.specs,t),r.validator=fE(e,r.merged,t))}},validate(e,r){let i=n.get(e);return i?i.validator(r):{ok:!1,reason:`unknown ${t} key "${e}" (have: ${[...n.keys()].join(`, `)})`}},listKeys(){return[...n.keys()]},listBaselineKeys(){return r()},rangeParamsFor(e){let t=n.get(e);if(!t||t.permanent||t.merged.kind!==`range`)return null;let{min:r,max:i}=t.merged;return{min:r,max:i}}}}const hE=mE({},`config`);function gE(){return hE.listKeys()}function _E(e,t){return hE.validate(e,t)}function vE(e){return hE.rangeParamsFor(e)}function yE(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:aS(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:[Gv({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Gv({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:aS(e.insertSegmentFrom,t).members.map(t=>Gv({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function bE(e,t){let n=jc(e.globals).get(t);return n===void 0?null:String(n)}function xE(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?oy(n.persist):null;e?.scope===`preset-root`&&t.add(iy(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function SE(e){let t=new Map([...rS(e),...wy(e)]);return[...xE(e),...Object.values(e.actions).flatMap(e=>yE(e,t))]}function CE(e){return pE(SE(e),`config`)}function wE(e,t){return hE.register(e,t)}const TE=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,EE=`{{ \$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 (${TE}) (basename .project_dir) (ne (${TE}) "") }}{{ end }}{{ end }}{{ abbreviatePath \$dir }}`,DE={globals:{palette:`tokyo-night`},variables:{...Lv,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},"session.budget.amount":{kind:`literal`,value:0},"session.budget.warningThreshold":{kind:`literal`,value:80},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"today.budget.amount":{kind:`literal`,value:50},"today.budget.warningThreshold":{kind:`literal`,value:80},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"block.budget.warningThreshold":{kind:`literal`,value:80},"block.budget.heatThreshold":{kind:`literal`,value:50},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"weekly.budget.warningThreshold":{kind:`literal`,value:80},"weekly.budget.heatThreshold":{kind:`literal`,value:50},"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},"burn.eta.warnMinutes":{kind:`literal`,value:60},"burn.eta.errorMinutes":{kind:`literal`,value:30},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``}},segments:{directory:{description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project.",template:EE},model:{description:`The active model's display name.`,template:`✱ {{ formatModelName .model.display_name }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{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:`{{ readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3 }}`,when:`{{ ne .git.branch "" }}`},gitPr:{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:{description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:Gy(``).template},themeSwitcher:{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:{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" .session.budget.amount "warn" .session.budget.warningThreshold) }}`},today:{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" .today.budget.amount "warn" .today.budget.warningThreshold) }}`},block:{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) .block.budget.heatThreshold "warning" .block.budget.warningThreshold "error" }}`,when:`{{ gt .block.resetsAt 0 }}`},weekly:{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) .weekly.budget.heatThreshold "warning" .weekly.budget.warningThreshold "error" }}`,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{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" .burn.eta.errorMinutes "warning" .burn.eta.warnMinutes (tint) }}`,when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{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:{description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,when:`{{ ne .speed.history "" }}`},cacheTimer:{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) ${Qi} }}`,when:`{{ gt .cache.expiresAt 0 }}`},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 }}`},metrics:{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:{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:`segment`,name:`context`},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...Gy(``).actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]}},looks:{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:`segment`,name:`context`},{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`}]}]}}},editGlobals:{style:`plain`,default_separator:` | `},helpers:{gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Qi}) .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 ne .git.repoName "" }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if ne .git.operation "" }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if ne .git.sha "" }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if 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 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 ne .git.upstream "" }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if gt .git.stash 0 }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ if gt .git.timeSinceCommit 0 }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:`{{ if ge . 1000000 }}{{ printf "%.1f" (divf . 1000000) }}M{{ else if ge . 1000 }}{{ printf "%.1f" (divf . 1000) }}K{{ else }}{{ . }}{{ end }}`,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 .)) }}`}},OE=new Set([DE.globals.palette,...Object.values(DE.segments).map(e=>e.palette)].filter(e=>e!==void 0)),kE=Ys(jS(`<default>`,JSON.stringify(DE),OE),DE),AE=Xv(kE.presets);function jE(e){return AE.includes(e)}function ME(e){if(!e)return 0;try{return o(e).mtimeMs}catch{return 0}}const NE=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 PE(e){return((...t)=>NE.run(()=>e(...t)))}const FE=PE(y),IE=PE(v),LE=PE(b);async function RE(e,t){return NE.run(async()=>{let n=null;try{n=await _(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=>{D(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}async function zE(e,t){return NE.run(async()=>{let n=null;try{n=await _(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=>{D(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}const BE=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function VE(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 HE(e){let t=await UE(e);return t.kind===`ok`?J(Math.floor((t.value+36e5)/1e3)):t}async function UE(e){for(let t of[65536,1048576]){let n=await zE(e,t);if(n.kind!==`ok`)return n;let r=WE(n.value.buf,n.value.fromStart);if(r!=null)return J(r);if(n.value.fromStart)return Y}return Y}function WE(e,t){let n=e.toString(`utf8`).split(`
176
+ `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!BE.test(t))continue;let r=VE(t);if(r!=null)return r}return null}function GE(e,t,n){let r=Zv(t(`preset`),e.globals.preset,e.presets),i=ey(e,r),a=t(`edit.mode`)===`open`?e.editGlobals:{};return{preset:r,presetCustomized:n(r),theme:Qx(a.palette,t(`theme`),i.palette),look:ja(a.look,t(`look`),i.look,e.looks),style:Pa(a.style,t(`style`),i.style),progression:Ka(a.progression,t(`progression`),i.progression),separator:a.default_separator??i.default_separator,autoWrap:$a(a.autoWrap,t(`autoWrap`),i.autoWrap),padding:eo(a.padding,t(`padding`),i.padding),charset:Ra(a.charset,t(`charset`),i.charset),updateNotice:a.updateNotice??i.updateNotice??!0,colorCompatibility:Ha(a.colorCompatibility,t(`colorCompatibility`),i.colorCompatibility)}}function KE(e,t){return{style:e.style,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,charset:e.charset,width:t}}function qE(e){return{theme:e.theme,look:e.look,preset:e.preset,progression:e.progression}}function JE(e){return{preset:{effective:e.preset,customized:e.presetCustomized,bundled:jE(e.preset)},style:{effective:e.style},progression:{effective:e.progression},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding}}}const YE=10*1e3;function XE(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 ZE(e,t){if(!(t<60))return e*3600/t}function QE(e,t,n,r){let i=r-t;if(i<50||i>YE)return;let a=n-e;if(!(a<=0))return a*1e3/i}function $E(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=QE(t.input,t.atMs,n.input,n.atMs),i=QE(t.output,t.atMs,n.output,n.atMs),a=QE(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 eD(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>YE)continue;let o=QE(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function tD(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function nD(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`,()=>tD(f.hostname())),i=n(`user`,()=>f.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function rD(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=>Dg(t,e.helpers).keys();for(let n of Qo($v(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 o=new Set;for(;r.length>0;){let e=r.pop();for(let t of aD(n,e)){if(i.has(t))continue;i.add(t);let e=n.get(t);if(e){if(e.kind===`input`)o.add(e.path);else if(e.kind===`template`)for(let t of a(e.template))r.push(t)}}}return o}function iD(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=rD(e,n);return t.set(n,i),i}}function aD(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 oD(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function sD(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 cD(e,t,n,r,i,a,o){let s=e=>oD(r,e),c=(t.clock??(()=>new Date))().getTime(),l=(e,t,n)=>t?n().catch(t=>X(`${e}: ${String(t)}`)):Promise.resolve(Y),[u,d,f,p,m,h,g,_,v]=await Promise.all([l(`git`,s(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,sD(r),e.workspace?.project_dir)),l(`session`,s(`session.cost`)||s(`session.tokens`)||s(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),l(`today`,s(`today`),()=>t.usageStore.getTodayInfo(e)),l(`context`,s(`context`),()=>t.contextProvider.getContextInfo(e)),l(`metrics`,s(`metrics`)||s(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),l(`activity`,s(`activity`),()=>t.activityProvider.getActivityInfo(e.session_id,e)),l(`tmux`,s(`tmux`),()=>t.tmuxService.getSessionId()),l(`cache`,s(`cache`),()=>HE(e.transcript_path)),l(`speed`,s(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,c))]),y=[],b=e=>{if(e.kind===`failed`){y.push(e.reason);return}return e.kind===`ok`?e.value:void 0},x=pD(u);y.push(...x.failures);let S=nD(a);y.push(...S.failures);let C=b(d),ee=b(f),te=b(p),w=b(m),ne=b(h),re=b(g),ie=b(_);for(let e of y)t.log(`warn`,`provider fetch failed: ${e}`);let T=e.rate_limits?.five_hour,E=e.rate_limits?.seven_day,ae=T?XE(T.used_percentage,T.resets_at,18e6,c):void 0,oe=E?XE(E.used_percentage,E.resets_at,6048e5,c):void 0,se=C?.session.cost,ce=w?.sessionDuration,le=s(`burn`)&&se!=null&&ce!=null?ZE(se,ce):void 0,ue=b(v),de=ue===void 0?void 0:$E(ue),fe=ue===void 0?void 0:eD(ue),pe=de!==void 0||fe!==void 0?{...de,...fe!==void 0&&{history:fe}}:void 0,me=fD(process.env.HOME??process.env.USERPROFILE),he=e.workspace?{...e.workspace,current_dir:fD(e.workspace.current_dir)??``,project_dir:fD(e.workspace.project_dir)??``}:e.workspace,D=C===void 0?void 0:dD({cost:C.session.cost,tokens:C.session.tokens}),ge=ee===void 0?void 0:{cost:ee.cost,tokens:ee.tokens},_e=w===void 0?void 0:dD({lastResponseTime:w.lastResponseTime,responseTime:w.responseTime,sessionDuration:w.sessionDuration,messageCount:w.messageCount,linesAdded:w.linesAdded,linesRemoved:w.linesRemoved}),ve=ne===void 0?void 0:lD(ne);return{...e,...he!==void 0&&{workspace:he},...me!==void 0&&{home:me},...x.git!==void 0&&{git:x.git},...re!==void 0&&{tmux:{session:re}},host:S.host,...JE(i),history:t.history(e.session_id),unsaved:o,...D!==void 0&&{session:D},...ge!==void 0&&{today:ge},...le!==void 0&&{burn:{costPerHour:le}},...pe!==void 0&&{speed:pe},...s(`block`)&&T!==void 0&&{block:{nativeUtilization:T.used_percentage,resetsAt:T.resets_at,...ae!==void 0&&{etaMinutes:ae}}},...E!==void 0&&{weekly:{percentage:E.used_percentage,resetsAt:E.resets_at,...oe!==void 0&&{etaMinutes:oe}}},...ie!==void 0&&{cache:{expiresAt:ie}},...te!==void 0&&{context:{totalTokens:te.totalTokens,contextLeft:te.contextLeftPercentage}},..._e!==void 0&&{metrics:_e},...ve!==void 0&&{activity:ve}}}function lD(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=uD(e.running),i=uD(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 uD(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function dD(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 fD(e){return e===void 0||e.length===0||c.sep!==`\\`?e:e.replace(/\\/g,`/`)}function pD(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 mD={theme:e=>e.theme.kind===`decided`?e.theme.name:null,preset:e=>e.preset,look:e=>e.look.kind===`decided`?e.look.name:null,style:e=>e.style,progression:e=>e.progression,charset:e=>e.charset,colorCompatibility:e=>e.colorCompatibility,autoWrap:e=>e.autoWrap?qa:Ja,padding:e=>String(e.padding)},hD=Object.entries(Rv),gD=new Set(zv.map(e=>e.sessionKey)),_D=()=>!1;function vD(e,t){return GE(e,e=>gD.has(e)?t(e):null,_D)}function yD(e,t,n,r){return e.flatMap(([e,i])=>{let a=mD[e](t);return a===null||a===mD[e](n(e))?[]:[{...i,value:a,target:r(i)}]})}function bD(e,t,n){return mD[n](vD(e,t))}function xD(e,t){let n=vD(e,t),r=GE(e,()=>null,_D),i=GE(e,e=>e===Rv.preset.sessionKey?n.preset:null,_D),a=Qv(e.presets,n.preset).globals??{};return yD(hD,n,e=>e===`preset`?r:i,e=>e.configKey in a?ay(n.preset,e.configKey):e.configKey)}function SD(e,t){let n=vD(e,t),r=GE(e,e=>e===Rv.preset.sessionKey?n.preset:null,_D);return{from:n.preset,globals:Qv(e.presets,n.preset).globals??{},picks:yD(hD.filter(([e])=>e!==`preset`),n,()=>r,e=>e.configKey)}}function CD(e){return{sessionKeys:zv.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...xc(e)?AE.map(t=>ay(t,e)):[]]}}const wD=Sa(),TD=new Set(wD),ED=new Set(Ma),DD=e=>e?TD.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${wD.join(`, `)})`}:{ok:!1,reason:`theme name is required`},OD=e=>e?ED.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${Ma.join(`, `)})`}:{ok:!1,reason:`style name is required`},kD=new Set([`1`,`true`]),AD=new Set([`0`,`false`]),jD=mE({style:OD,theme:DD,"toolbar-expanded":e=>kD.has(e)?{ok:!0,value:`1`}:AD.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function MD(){return jD.listKeys()}function ND(e,t){return jD.register(e,t)}function PD(e,t){return jD.validate(e,t)}function FD(e){return jD.rangeParamsFor(e)}function ID(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:aS(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 LD(e){let t=new Set(jD.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function RD(e,t,n){let r=Hv.get(n);if(r!==void 0)return bD(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 zD(e){let t=rS(e);return LD(Object.values(e.actions).flatMap(e=>ID(e,t)))}function BD(e){return pE(zD(e))}const VD=`update.dismissed`,HD=`updateNotice`;function UD(e){return e.kind===`source`?e.newer.digest:Cw(e.newer)}const WD=e=>`${e.version} [${tE(e.digest)}]`;function GD(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:WD(e.newer),running:WD(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:Cw(e.newer),running:Cw(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${Tw}@${Cw(e.newer)}`,`install`]}}}}const KD={kind:`idle`},qD={kind:`running`};function JD(e,t,n){if(e===null)return[];let r=UD(e);if(!n.enabled||n.dismissed===r)return[];let i=GD(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(`
177
+ `),c=pw([{verb:QC,args:[s]}]),l=t.kind===`running`?UT(`[${i.busy}]`,c):UT(`[${i.act}]`,pw([{verb:cw,args:[n.sessionId]}]));return[{severity:HT,message:s,lines:[[UT(a,c),l,UT(`[dismiss]`,pw([{verb:KC,args:[n.sessionId,VD,r]}])),UT(`[disable]`,pw([{verb:$C,args:[n.sessionId,HD,`false`]}]))],...o.map(e=>[UT(e,c)])]}]}function YD(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 XD(e){switch(e.kind){case`current`:return[`info`,`build: current ${WD(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${WD(e.source)}, running ${WD(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function ZD(e){switch(e.kind){case`current`:return[`info`,`release: current ${Cw(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${Cw(e.latest)}, running ${Cw(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${Cw(e.installed)}, latest ${Cw(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function QD(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const $D=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function eO(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=$D(e.stderr)??e.error??$D(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function tO(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=KD,d=null,f=QD(s),p=QD(s),m=()=>YD(c,l);function h(){let e=m(),t=e===null?null:UD(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:ND(VD,{kind:`allow-list`,allowed:[t]})})}function g(){c=aE(t,rE),f(XD(c)),h()}async function _(){l=Dw(yw,await Ew(Tw,a,i)),p(ZD(l)),h()}return{arm(){wE(HD,{kind:`allow-list`,allowed:[`false`]}),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>JD(m(),u,e),act(){let e=m();if(e===null)throw new $(`apply-update: nothing newer is known to apply`);let t=GD(e);if(u.kind===`running`)throw new $(`apply-update: already ${t.busy}`);u=qD,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),Te({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=KD,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=eO(n);u={kind:`failed`,identity:UD(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}var nO=class{static CACHE_DIR=O();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 D(`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`?(D(`Removing stale lock file ${e} for dead process ${i}`),r.unlinkSync(t),!1):(D(`Error checking process ${i} for lock ${e}:`,n),!0)}}catch(t){return D(`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`}),D(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await ae(50);else throw e}return D(`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),D(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&D(`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){D(`Failed to create cache directories:`,e)}}static createProjectHash(e){return T(`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)){D(`Cache for ${e} is locked, waiting...`),await ae(75);continue}try{let i=await r.promises.readFile(n,`utf-8`),a=JSON.parse(i);return!t||a.timestamp>=t?(D(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(a.data)):(D(`${e} cache outdated: cache=${a.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return D(`No shared ${e} usage cache found`),null;D(`Attempt ${a+1} failed to read ${e} cache: ${t.message}. Retrying...`),await ae(75)}}return D(`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)){D(`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`),D(`[CACHE-SET] ${e} disk cache stored`)}catch(t){D(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(i)}}};const rO={"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 iO=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 nO.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await nO.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new ee(this.GITHUB_PRICING_URL),n=E({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){D(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let r=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){D(`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)?(D(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),D(`Pricing last updated: ${n?.updated||`unknown`}`),e(i)):(D(`Invalid pricing data structure`),e(null))}catch(t){D(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{D(`Response error:`,t),e(null)})});n.on(`error`,t=>{D(`Request error:`,t),e(null)}),n.on(`timeout`,()=>{D(`Request timeout`),n.destroy(),e(null)}),n.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return D(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return D(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),D(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(D(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(rO).length} models`),this.executionCache=rO,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(rO).length} models`),rO)}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 D(`[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),D(`[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 aO=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function oO(e){if(typeof e==`string`)return aO.exec(e)?.[1]}function sO(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 cO(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=sO(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?oO(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 lO(){let e=[],t=process.env.CLAUDE_CONFIG_DIR;if(t&&t.split(`,`).forEach(t=>{let n=t.trim();a(n)&&e.push(n)}),e.length===0){let t=p(),n=d(t,`.config`,`claude`),r=d(t,`.claude`);a(n)&&e.push(n),a(r)&&e.push(r)}return e}async function uO(e){let t=[];for(let n of e){let e=d(n,`projects`);if(a(e))try{let n=await FE(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=d(e,r.name);t.push(n)}}catch(t){D(`Failed to read projects directory ${e}:`,t)}}return t}async function dO(e,t,n){let r=[],i=d(t,e,`subagents`);try{let t=(await FE(i)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let a of t){let t=d(i,a);if(n?.has(t)){r.push(t);continue}try{let n=(await IE(t,`utf-8`)).split(`
178
+ `)[0];n&&JSON.parse(n).sessionId===e&&r.push(t)}catch{D(`Failed to check agent file ${t}`)}}}catch(e){D(`Failed to read subagents directory ${i}:`,e)}return r}function fO(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 pO=new Map;async function mO(e){try{let t=await LE(e),n=t.size,r=pO.get(e);if(r&&r.mtime===t.mtimeMs&&r.size===n)return D(`[parse-cache] hit ${e}`),pO.delete(e),pO.set(e,r),r.entries;let i;return n>1048576?(D(`Using streaming parser for large file ${e} (${Math.round(n/1024)}KB)`),i=await yO(e)):i=await _O(e),D(`Parsed ${i.length} entries from ${e}`),n>5242880?i:(pO.delete(e),pO.size>=16&&pO.delete(pO.keys().next().value),pO.set(e,{mtime:t.mtimeMs,size:n,entries:i}),i)}catch(t){if(t.code===`ENOENT`)return D(`Transcript not present yet: ${e}`),[];throw t}}function hO(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:cO(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 gO(e){let t=[];for(let n of e.split(`
179
+ `))if(n.trim())try{let e=hO(JSON.parse(n));e&&t.push(e)}catch(e){D(`Failed to parse JSONL line: ${e}`);continue}return t}async function _O(e){return gO(await IE(e,`utf-8`))}async function vO(e,t){let n=await RE(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:gO(r.subarray(0,c+1).toString(`utf-8`)),cursor:{offset:i+c+1,mtimeMs:a,ino:o},reset:s})}async function yO(e){return new Promise((t,n)=>{let r=[],a=i(e,{encoding:`utf8`}),o=oe({input:a,crlfDelay:1/0});o.on(`line`,e=>{let t=e.trim();if(t)try{let e=hO(JSON.parse(t));e&&r.push(e)}catch(e){D(`Failed to parse JSONL line: ${e}`)}}),o.on(`close`,()=>{t(r)}),o.on(`error`,t=>{D(`Streaming parser error for ${e}:`,t),n(t)}),a.on(`error`,t=>{D(`File stream error for ${e}:`,t),n(t)})})}var bO=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 xO(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 SO={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},CO={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function wO(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function TO(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function EO(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}async function DO(e,t,n,r){let i=wO(new Date(TO())),a=e&&!t?e:void 0,o=a?.entries??0,s=a?.cost??0,c=a?{...a.breakdown}:EO(),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 iO.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=wO(new Date(e.timestamp));if(r<i)continue;let a=l.get(r)??{...SO};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 OO(e){let t=0,n=0,r=EO(),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)??{...SO};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:CO,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 kO(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 AO=class{entries=new Map;flight=new bO;seeded=new Map;speedRings=new Map;speedFlight=new bO;maxEntries;staleAgeMs;hits=0;misses=0;sweeps=0;seeds=0;sweepTimer=null;constructor(e={}){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:CO,i=t?.cost?.total_cost_usd??null;return J({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e){let t=wO(new Date);try{await this.ensureSeeded(t)}catch(e){return X(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let n=await this.ingest(e?.session_id??``,e?.transcript_path);if(n.kind===`failed`)return n;let r={...SO},i=!1;for(let e of this.entries.values()){i||=e.days.has(t);let n=e.days.get(t)??SO;r.cost+=n.cost,r.input+=n.input,r.output+=n.output,r.cacheCreation+=n.cacheCreation,r.cacheRead+=n.cacheRead}return i?J({cost:r.cost,tokens:r.input+r.output+r.cacheCreation+r.cacheRead,tokenBreakdown:{input:r.input,output:r.output,cacheCreation:r.cacheCreation,cacheRead:r.cacheRead},date:t}):Y}async observeSpeed(e,t,n){let r=ME(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,r);if(i.kind===`failed`)return i;let a=xO(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??ME(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 dO(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 vO(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 DO(r,l,s,c)),e===t&&(a=c.mtimeMs)}return J({files:i,...OO(i),mainMtime:a})}ensureSeeded(e){let t=this.seeded.get(e);if(t)return t;this.seeded.clear();let n=this.seed(e);return this.seeded.set(e,n),n.catch(()=>{this.seeded.get(e)===n&&this.seeded.delete(e)}),n}async seed(e){let t=TO(),n=await uO(lO()),r=[];for(let e of n){let n;try{n=await FE(e)}catch{continue}for(let i of n){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a;try{a=(await LE(n)).mtimeMs}catch{continue}a<t||r.push({sessionId:i.slice(0,-6),path:n,mtime:a})}}await kO(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,e.mtime);t.kind===`failed`&&Q(`warn`,`usageStore seed: ${t.reason}`)}),this.seeds++,Q(`info`,`usageStore seed sessions=${r.length}`)}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++,Q(`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),Q(`info`,`usageStore evict ${e}`)}}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.entries.clear(),this.seeded.clear(),this.speedRings.clear()}};function jO(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function MO(e,t){let n=H.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function NO(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:n.truncateMarker}):e.cellLength<t&&e.align(n.justify,t)}function PO({text:e,trail:t}){if(t===void 0)return e;let n=MO([e,t]);return n.style=e.style,n}function FO(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s,trail:c=[]}=t;if(e.length===0)return[];let l=MO(e,o).pad(s),u=c.length===0?{}:{trail:MO([...c,new H(` `.repeat(s))],o)};if(n===`auto`)return[{text:l,...u}];let d={justify:r,truncate:i,truncateMarker:a};return n===`fill`?[{text:l,fill:d,...u}]:(NO(l,n,d),[{text:l,...u}])}const IO=RegExp(`\\x1b\\[[0-9;]*m|${Jr.source}`,`g`);function LO(e){return k(e.replace(IO,``))}function RO(e,t){let n=e.map(PO),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=RT(n,t).split(`
180
+ `);if(i.length>1)return n;let a=Math.max(0,t.width-LO(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];NO(l,l.cellLength+c,i),n[t]=PO(e[t])}),n}function zO(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=BO(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(HO(a.style).link){i();let e=BO([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function BO(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>VO(e,t)):e,r=H.fromFragments(n);return r.end=``,r.noWrap=!0,n.length===1?r.style=n[0].style:t!==void 0&&!t.isNull&&(r.style=t),r}function VO(e,t){let n=e.copy();return n.style=t.add(HO(e.style)),n}function HO(e){return e instanceof B?e:B.parse(e)}var UO=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function WO(e,t,n,r,i){let{palette:a,tint:o}=e,s=GO(n,i),c=s===void 0?o:KO(a,s,`bg`);e.bg=c;let l=GO(r,i),u=l===void 0?$i(a,c,t):KO(a,l,`fg`);return new B({bgcolor:P.fromRgba(c),color:P.fromRgba(u)})}function GO(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function KO(e,t,n){try{return Vn(e,t)}catch(e){throw e instanceof Rn?new UO(t,n,e.message):e}}function qO(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,JO(e,t,o,n,r,i));return i}function JO(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=aS(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf}}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=Bv.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=aS(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf}}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=aS(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:XO(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:XO(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(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:XO(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 YO(e){return e.kind===`do`?YO(e.head):e}function XO(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function ZO(e,t){return e.has(t)?Bg(e.read(t)):``}function QO(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function $O(e,t,n,r){let i=new H(e,{style:B.combine([r,new B({link:t,bold:n})])});return i.noWrap=!0,i.end=``,i}function ek(e,t){return Math.max(e.members.indexOf(ZO(t,e.stateVar)),0)}function tk(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=ZO(r,e.stateVar);return{effects:[{verb:KC,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=ZO(r,e.stateVar);return{effects:[{verb:KC,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=ZO(r,e.stateVar);return{effects:[{verb:KC,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(ek(e,r)+1)%e.members.length];return{effects:[{verb:KC,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:qC,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:JC,args:[QO(e.text,j_(r))]}],active:!1};case`open`:return{effects:[{verb:YC,args:[QO(e.target,j_(r))]}],active:!1};case`persist-literal`:{let t=ZO(r,e.stateVar);return{effects:[{verb:$C,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=ZO(r,e.stateVar);return{effects:[{verb:$C,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(ek(e,r)+1)%e.members.length];return{effects:[{verb:$C,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:ew,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:iw,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ow,args:[i]}],active:!1};case`redo`:return{effects:[{verb:sw,args:[i]}],active:!1};case`save`:return{effects:[{verb:tw,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:nw,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:rw,args:[i,QO(e.name,j_(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:lw,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:uw,args:[i,e.check]}],active:!1};case`layout-op`:return{effects:[{verb:aw,args:[i,e.key,Gv(e.op)]}],active:!1};case`do`:{let a=tk(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>tk(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:aw,args:[i,e.key,Gv(r)]}],active:!1}}}}function nk(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:tc(`action "${e}"`,n,t.members.length,ek(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 rk(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}=nk(e,YO(r),t,i),{effects:s,active:c}=tk(r,a,o,i,ZO(i,`session.id`));return $O(a,pw(s),c)}function ik(e){return{action:{fn:(t,...n)=>rk(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function ak(e,t){return $O(`✕`,pw([{verb:KC,args:[ZO(e,`session.id`),t,Qs]}]),!1)}function ok(e,t,n){return new B({bgcolor:P.fromRgba(t),color:P.fromRgba($i(e,t,n))})}function sk(e,t,n){return ok(e.palette,fa(e.palette,e.disclosure,[t],n),n)}function ck(e,t,n,r,i){return r===void 0?n=>sk(e,{...n,distribution:t},i):(e,t)=>lk(r(t,n),i)}function lk(e,t){let n=Ui(e,`background`);return new B({bgcolor:P.fromRgba(n),color:P.fromRgba(Jn(Ui(e,`primary`),n,4.5,t))})}function uk(e){return{current:null,drawnAt:e}}function dk(e,t,n,r,i){let a={segName:t,palette:n,disclosure:r,tint:i,bg:void 0,drops:[]};return e.current=a,a}function fk(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 pk(e){return new H(e).cellLength}function mk(e){return Math.max(1,e.width-e.chromeCols-2*e.padding)}function hk(e){return Math.max(1,mk(e)-(pk(`✕`)+2*e.padding+e.seamCols))}function gk(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 _k(e,t){let n=[];for(let t of e)n.length>0&&n.push(new H(` `)),n.push(t);let r=H.fromFragments(n);return r.noWrap=t,r.end=``,r}function vk(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 yk(e,t,n){let r=e.compiled.get(t),i=r&&YO(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 bk(e,t,n,r,i,a,o){let s=yk(a,e,`picker`),c=a.compiled.get(e),l=a.store,u=ZO(l,`session.id`),d=`stateVar`in s?ZO(l,s.stateVar):void 0,f=s.options.map(pk),p=i?mk(a):1/0,m=pk(`✕`)+1,h=pk(`←`)+1+pk(`→`)+1,g=gk(f,p,m),_=g.length>1?gk(f,p,m+h):g,v=parseInt(ZO(l,t.stateVar),10),y=Number.isInteger(v)?Math.max(0,Math.min(v,_.length-1)):0,b=_[y]??[],x=e=>pw([{verb:KC,args:[u,t.key,String(e)]}]),S=n.flatMap(([e,t])=>[e,t]),C=pw([{verb:KC,args:[u,...S]}]),ee=r?[{verb:KC,args:[u,...S]}]:[],te=e=>pw([...tk(c,e,e,l,u).effects,...ee]),w=[$O(`✕`,C,!1)];y>0&&w.push($O(`←`,x(y-1),!1));for(let e of b){let t=s.options[e];w.push($O(t,te(t),t===d,o({index:e,count:s.options.length},t)))}return y<_.length-1&&w.push($O(`→`,x(y+1),!1)),_k(w,i)}function xk(e,t){return{picker:{fn:(n,r,i,a)=>{let o=vk(e,r,`set-int`,`an int action ({ set, int: true })`);return bk(n,{key:o.key,stateVar:o.stateVar},[[o.key,`-1`]],i===!0,a===!0,e,ck(fk(t,`{{ picker }}`),Li(void 0),e.basePalette,yk(e,n,`picker`).paletteOf,t.drawnAt()))},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}function Sk(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+pk(e(-(s+1)))+1+pk(e(s+1))+1;if(t>r)break;o=t,s+=1}return s}function Ck(e,t,n,r,i){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let a=n.store;if(!a.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let o=n.compiled.get(e),s=ZO(a,`session.id`),{options:c}=t,l=c.length,u=ZO(a,t.stateVar),d=Math.max(c.indexOf(u),0),f=e=>((d+e)%l+l)%l,p=e=>c[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let n=pw(tk(o,p(e),p(e),a,s).effects);return m.set(e,n),n},g=e=>$O(p(e),h(e),p(e)===u,r({index:f(e),count:l},p(e))),_=Sk(p,l,pk(`◀`)+1+pk(p(0))+1+pk(`▶`),hk(n),i),v=e=>Array.from({length:_},(t,n)=>g(e*(n+1)));return _k([...v(-1).reverse(),$O(`◀`,h(-1),!1),g(0),$O(`▶`,h(1),!1),...v(1)],!0)}function wk(e,t){return{carousel:{fn:(n,r,...i)=>{if(i.length>0)throw Error(`carousel "${n}": takes at most one neighbours count after the action name, got ${1+i.length}`);if(r!==void 0&&!(Number.isInteger(r)&&r>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(r)}`);let a=r??1/0,o=yk(e,n,`carousel`);return Ck(n,o,e,ck(fk(t,`{{ carousel }}`),Li(void 0),e.basePalette,o.paletteOf,t.drawnAt()),a)},argTypes:[`string`,`float`],returnType:`T`}}}const Tk=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function Ek(e,t,n){let r=aa(e,{hue:Ai,depth:0},n);return[U(t).map((t,n)=>({text:Tk[n%Tk.length],colour:Wi(e,t)})),[{text:`▾ open`,colour:r.state},{text:`menu`,colour:r.plane}],[{text:`warn`,colour:Ui(e,`warning`)},{text:`error`,colour:Ui(e,`error`)}]]}function Dk(e,t,n,r){let i=Ek(e,t,n).flatMap((t,r)=>t.map(({text:t,colour:i},a)=>({gap:r>0&&a===0?` `:``,cell:new H(` ${t} `,{style:ok(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 H(e)),a.push(t)}let s=H.fromFragments(a);return s.noWrap=!0,s.end=``,s}function Ok(e,t){return{themePreview:{fn:()=>Dk(e.palette,e.progression,t.drawnAt(),hk(e)),argTypes:[],returnType:`T`}}}const kk=e=>e.slice(e.lastIndexOf(`.`)+1),Ak=(e,t)=>{let n=new H(kk(e));return n.truncate(t,{marker:`…`}),n.plain};function jk(e,t){let n=e.map(e=>e.map(({name:e})=>pk(kk(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 Mk(e,t,n,r){let i=jk(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new H(` ${Ak(s,i)} `,{style:ok(l,ga(l,{kind:`bar`,progression:t,address:c},n).tint,n)});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=H.fromFragments(a.flatMap((e,t)=>t===0?e:[new H(`
181
+ `),...e]));return o.noWrap=!0,o.end=``,o}function Nk(e,t){return{layoutPreview:{fn:()=>Mk(e.layout(),e.progression,t.drawnAt(),hk(e)),argTypes:[],returnType:`T`}}}function Pk(e,t,n,r){let i=fk(r.activeSegment,`{{ menu }}`),a=r.action,o=Uh(i.segName,e,n.key),s=Kh(o),c=Hh(e),l=ZO(a.store,o)===c,u=ZO(a.store,`session.id`),d=l?Qs:c,f=$O(tc(`{{ menu "${e}" }}`,t,2,+!!l),pw([{verb:KC,args:[u,o,d,s,`0`]}]),!1);return i.drops.push(...l?[bk(e,{key:s,stateVar:s},[[o,Qs],[s,`0`]],n.closeOnPick,n.paged,a,ck(i,n.distribution,a.basePalette,yk(a,e,`menu`).paletteOf,r.activeSegment.drawnAt()))]:[]),f}const Fk=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Ik(e,t){let n=t[t.length-1],r=Fk(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:Xh(r??{})}}function Lk(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=Ik(t,n);return Pk(t,r,i,e)},argTypes:[`string`,`value`],returnType:`T`}}}function Rk(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=zk(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 H(t?i:a,{style:l===void 0?void 0:new B({color:l})}))}let l=H.fromFragments(c);return l.end=``,l.noWrap=!0,l}function zk(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 Bk(e){let t={fn:(()=>{let t=fk(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:[],returnType:`string`},n={fn:(()=>fk(e,`{{ tint }}`).tint.hex),argTypes:[],returnType:`string`},r=f_(()=>fk(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),i={fn:((e,t,n,i,a,o,...s)=>Rk({value:e,max:t,width:n,filled:i,empty:a,colourAt:o===void 0||s.length===0?void 0:e=>String(r.ramp.fn(e,o,...Vk(s)))})),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`,`string`],returnType:`T`};return{...r,bgOf:t,tint:n,gauge:i}}function Vk(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 Hk(e){let t=[],n=[];for(let r of e){if(!r.contains(`
182
182
  `)){n.push(r);continue}let e=r.split(`
183
- `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}const Nk=({text:e,trail:t})=>t===void 0?[e]:[e,t];function Pk(e,t){switch(e){case`vertical`:return Ik(t.flatMap(e=>e));case`horizontal`:{let e=t.find(e=>e[0]?.span===`row`);return e===void 0?t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`,span:`shared`},...t.flatMap(e=>e.slice(1))]:Ik(e)}}}function Fk(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r}],band:`own`,span:`shared`}]:Pk(e.direction,e.children.map((t,i)=>n(t,[...r,Lk(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function Ik(e){return e.map(e=>e.span===`row`?{...e,span:`shared`}:e)}function Lk(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:Xo[e.direction]}}const Rk={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Li(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,$o(t.path,n)))}},render(e,t){return Pk(e.direction,e.children.map((n,r)=>t.renderChild(n,t.visible,Lk(e,r))))}},zk={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,...e.opens!==void 0&&{opens:{open:t.parse(ic(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,es(t.path)),key:e.opens.ref.key,placement:e.opens.placement}},...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[];try{if(!xO(i.when,t.scope))return[];let n=i.palette??t.palette,{styles:a,fragments:o,trail:s,drops:c}=t.evaluateSegment(e.name,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,trail:e.trail}),l=e.opens!==void 0&&xO(e.opens.open,t.scope),u=c.length>0||l?a.trigger:a.closed,d={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:u,padding:t.padding},f=e.opens===void 0?[]:t.renderBody(e.opens.body,l,a.disclosure),p=f.slice(0,+(e.opens?.placement===`inline`)),m=f.slice(p.length),h=e.opens!==void 0&&m.some(e=>e.band===`own`)?TO(kO([t.closeDisclosure(e.opens.key)],a.trigger),{...d,width:`auto`,baseStyle:a.trigger}):[],g=e=>e.band===`own`?h:[],_=m.map(e=>({cells:[...g(e),...e.cells],band:`deeper`,span:`shared`})),v=Mk(kO(o,u)).map((e,t)=>({cells:TO(e,{...d,trail:t===0?kO(s,u):[]}),band:`own`,span:`shared`})),y=c.map(e=>({cells:TO(kO([e],a.band),{...d,baseStyle:a.band}),band:`deeper`,span:`shared`})),b=[...v,...y];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.name,[...b.flatMap(e=>e.cells),...m.flatMap(g)].flatMap(Nk)),[...b.map((e,t)=>t===0&&p.length>0?{cells:[...e.cells,...p.flatMap(e=>e.cells)],band:`own`,span:`row`}:e),..._]}catch(n){let r=n.message??String(n);t.onSegmentError?.(e.name,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:TO([new H(`⚠ ${e.name}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,trail:Bk(e,t)}),band:`own`,span:`shared`}]}}};function Bk(e,t){if(e.trail===void 0)return[];try{return t.evaluateSegment(e.name,t.palette,t.region,{bg:void 0,fg:void 0,body:e.trail,trail:void 0}).fragments}catch(n){return t.onSegmentError?.(e.name,n.message??String(n)),[]}}const Vk={container:Rk,segment:zk};function Hk(e){return Vk[e]}function Uk(e){if(`ttl`in e)return{kind:`ttl`,durationMs:yv(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 Wk(e,t){switch(rs(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 Gk(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:Uk(n.cache),parse:Wk(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cache:Uk(n.cache),parse:Wk(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?yv(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 Kk(e,t){let n=Au.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 qk=e=>Ka(void 0,null,e.globals.progression);function Jk(e,t,n){let r=n?.cwd??process.cwd(),i=$x(e.globals.palette),a={store:t.variableStore,compiled:new Map,chromeCols:FT({style:`powerline`,charset:Ia}),width:80,basePalette:i,palette:i,progression:ki[qk(e)],padding:1,seamCols:IT({style:`powerline`,charset:Ia}),layout:()=>[]},o=ek(t.drawnAt),s={action:a,activeSegment:o},c=Object.keys(e.looks),l=Yv(e.presets),u=new Map([...nS(e),...Cy(e)]),d=A_({...JO(a),...dk(a,o),...mk(a,o),...vk(a,o),...Ck(a,o),...Dk(s),...Ak(o),looks:{fn:()=>c,argTypes:[]},presets:{fn:()=>l,argTypes:[]}},n?.clock,t.drawnAt),f=Kk(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 Vv)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=LO(p,e.actions,g,u);let _=[];for(let[n,i]of Object.entries(e.variables))try{Gk(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{Gk(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`),palette:n.palette===void 0?void 0:Kx(n.palette)}}let y=(e,t,n)=>{try{return h(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},b=(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:b};return Hk(e.kind).compile(e,n)},x=new Map;for(let t of l){let{node:n,path:r}=Qv(e,t);x.set(t,b(n,r))}let S=new Map;for(let t of wa){let n=e.globals[t];Ta(n)&&S.set(t,Yk(p,t,n))}return{segments:v,roots:x,activeSegment:o,menuRuntime:s,globalExpressions:S,loadWarnings:_}}function Yk(e,t,n){try{return e(n)}catch(e){throw Error(`globals.${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function Xk(e,t,n){let r=e.globalExpressions.get(t);if(r===void 0)throw Error(`globals.${t} is an expression but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r.evaluate(n).map(e=>e.plain).join(``)}function Zk(e,t){return e.kind===`decided`?e.name:t}function Qk(e,t,n,r,i,a,o,s){let{perSegmentSink:c,onSegmentError:l,onRenderWarning:u}=o??{};r.drawAt(Ua(a.colorCompatibility));let{preset:d=qv}=s??{},f=ki[s?.progression??qk(e)];t.menuRuntime.action.progression=f;let p=s?.look??Aa(`none`,e.looks),m=s?.theme??Zx(void 0,null,e.globals.palette),h=(e,t)=>({...i,term:{cols:a.width},theme:{effective:e},look:{effective:t}});r.applyInput(h(Zk(m,ya),Zk(p,Oa))),t.menuRuntime.action.chromeCols=FT(a),t.menuRuntime.action.padding=a.padding,t.menuRuntime.action.width=a.width,t.menuRuntime.action.seamCols=IT(a);let g=j_(n),_=Da(m,()=>Xk(t,`palette`,g),e=>Xx(e,e=>u?.(e))),v=Da(p,()=>Xk(t,`look`,g),t=>Aa(t,e.looks));(_!==m||v!==p)&&r.applyInput(h(_.name,v.name));let y=_.value;t.menuRuntime.action.basePalette=y;let b=Jx(y,v.value);t.menuRuntime.action.palette=b,c?.clear();let x=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},S=(e,n,i,a)=>{try{let o=r.drawnAt(),{tint:s,disclosure:c}=ga(n,i,o),l=tk(t.activeSegment,e,n,c,s),u=PO(l,o,a.bg,a.fg,g),d=a.body.evaluate(g),f=a.trail?.evaluate(g)??[];return{styles:{closed:u,get trigger(){return XO(n,aa(n,c,o).state,o)},get band(){return XO(n,aa(n,c,o).plane,o)},disclosure:c},fragments:d,trail:f,drops:l.drops}}finally{t.activeSegment.current=null}},C=(e,t,r)=>{let i=t&&xO(e.when,g),o={scope:g,palette:b,visible:i,padding:a.padding,region:r,perSegmentSink:c,onSegmentError:l,evaluateSegment:S,lookupSegment:x,renderChild:(e,t,n)=>C(e,t,ma(r,n)),renderBody:(e,t,n)=>C(e,i&&t,ha(n)),closeDisclosure:e=>YO(n,e)};return Hk(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 "${qv}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let te=e=>{if(!xO(e.when,g))return!1;if(e.kind===`container`)return!0;if(Dy(e.name)===void 0)return!1;try{return xO(t.segments[e.name].when,g)}catch{return!0}};return t.menuRuntime.action.layout=()=>Fk(ee,te).map(e=>e.flatMap(e=>{let n=Dy(e.name);return n===void 0?[]:[{...e,name:n,palette:t.segments[n].palette??b}]})),C(ee,!0,pa(f)).map(e=>LT(OO(e.cells,a),a)).join(`
184
- `)}var $k=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,aA(e,t,n,`initial value`),this.cell=Lg.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){aA(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}},eA=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,Lg.computed)(()=>{let e=n();return aA(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},tA=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=Lg.observable.box(iA(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=iA(e);rA(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function nA(e){return JSON.stringify(e)}function rA(e,t){return nA(e)===nA(t)}function iA(e){return e.kind===`ok`?{kind:`ok`,value:Rg(e.value)}:e}function aA(e,t,n,r){let i=zg(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var oA=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new $k(e,t,n))}defineDocument(e,t){this.assertNotDefined(e),this.nodes.set(e,new tA(e,t))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new eA(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,Lg.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,Lg.runInAction)(()=>n.set(t))}runInAction(e){(0,Lg.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 nA(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 sA(e,t,n){return e+`\0`+t+`\0`+(n??``)}function cA(e,t){return new Set(Yv(e.presets).filter(n=>Qv(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function lA(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 uA(e,t){let n=new Map;for(let t of yS(e.projectDir,e.cwd,e.configFile)){let{dir:e,name:r}=lA(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 dA(e){return e.filter(Boolean).join(`
185
- `)||null}var fA=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=sA(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.loadFromDisk(e,t,n),o={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:a.error,lastWarning:a.warning,state:a.state??this.buildState(t,null,[]),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.state.validatorDisposers.forEach(e=>e()),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=this.loadFromDisk(e.projectDir,e.cwd,e.configFile);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(e.state.registry.dispose(),e.state.validatorDisposers.forEach(e=>e()),e.state=t.state),this.refreshWatcher(e,t.resolvedPath),this.observers.onReload?.(e)}loadFromDisk(e,t,n){let r=xS(e,t,n),i=r.kind===`file`?r.path:null,a=[TS(e,t),CS(r)],o;try{o=this.buildState(t,i,a)}catch(e){return e instanceof Wo&&a.push(...e.warnings),{resolvedPath:i,warning:dA(a),state:null,error:e instanceof Wo||e instanceof Error?e.message:String(e)}}return{resolvedPath:i,warning:dA(a),state:o,error:null}}buildState(e,t,n){let r=ES(t,YD),{config:i,raw:a}=r;n.push(...r.warnings);let o=kS(r,t??`<default>`),s=new oA,c=new Iv(s,o.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),l,u=[];try{l=Jk(o,c,{cwd:e}),n.push(...l.loadWarnings);for(let{key:e,spec:t}of VE(o))u.push(PE(e,t));for(let{key:e,spec:t}of CE(o))u.push(wE(e,t))}catch(e){for(let e of u)e();throw c.dispose(),e}return{config:o,store:s,registry:c,compiled:l,neededInputPaths:dO(o),lastRenderCellsBySegment:new Map,validatorDisposers:u,authoredRoots:cA(i,a)}}refreshWatcher(e,t){e.configFilePath=t;let n=uA(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){Q(`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 pA=16384;var mA=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<pA){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%pA}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:vw,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}}};const hA={load:()=>({}),save:()=>{},flush:()=>{}};function gA(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var _A=class{sessions;storage;atom=(0,Lg.createAtom)(`SessionState`);constructor(e=hA,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=gA(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,Lg.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,Lg.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,Lg.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}};const vA=(e,t)=>D(t);function yA(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 bA=class{timer=null;pending=null;constructor(e,t=500,n=vA){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 yA(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 xA={default_bg:`string`,default_fg:`string`,default_empty_value:`string`,default_separator:`string`,default_truncate_marker:`string`,palette:`string`,look:`string`,preset:`string`,style:`string`,progression:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,updateNotice:`boolean`,colorCompatibility:`string`,menuGlyph:`string`},SA=new Set([`1`,`true`]),CA=new Set([`0`,`false`,``]);function wA(e,t){let n=YA(e),r=n.scope===`segment-palette`?`string`:xA[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(SA.has(t))return`true`;if(CA.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function TA(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function EA(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(c.dirname(e),{recursive:!0}),ke(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function DA(e){return/^\s*$/.test(e)?null:so(e)}function OA(e,t){return e!==null&&lo(e,t)!==void 0}function kA(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(kA),...i}}return e}function AA(e){if(!Vs(e))return kA(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,kA(t)])),...n}}const jA=qD,MA=jA.segments,NA=jA.presets,PA=jA.root;function FA(e,t,n,r){if(!OA(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function IA(e,t){let n=oy(t);return t.scope===`segment-palette`&&FA(e,[`segments`,t.segment],MA[t.segment],n.join(`.`)),n}function LA(e){return so(vo(e))}function RA(){return Object.entries(PA.rows).map(([e,t])=>{let n=kA(t);return{path:[`root`],fragment:LA({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function zA(e,t){let n=e===null?void 0:lo(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function BA(e,t){if(t===void 0)return null;let n=AA(t);return{path:e,fragment:LA(n),unit:{path:e,value:n}}}function VA(e,t){let n=[`presets`,t],r=[...n,`root`],i=NA[t];FA(e,n,i,r.join(`.`));let a=zA(e,r)??BA(r,i?.root);return a!==null&&Ro(a.fragment)?a:null}function HA(e,t){let n=Lo(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 UA(e,t){return[...RA(),zA(e,[`root`]),VA(e,t)].filter(e=>e!==null).reduce(HA,new Map)}function WA(e,t,n){for(let{node:r,...i}of UA(e,t).values())if(Bo(r,n))return i;throw new $(`${GA(e,t).join(`.`)} holds no segment "${n}" — the bar you clicked is stale; it reloads on the next render`)}function GA(e,t){return VA(e,t)?.path??[`root`]}function KA(e,t){return t.scope===`preset-root`?GA(e,t.preset):oy(t)}function qA(e,{unit:t}){return t===null?e:Mo(e,t.path,vo(t.value),go)}function JA(e){let t=ay(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function YA(e){let t=JA(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function XA(e,t,n,r){try{kS(DS(t,r,YD),t)}catch(e){throw e instanceof Wo?new $(`refused: the config file would not load after this click — ${e.message}`):e}EA(t,r,e.logger),e.record(t,n,r)}function ZA(e,t){let n=YA(t),r=DA(TA(e)??``),i=r===null?void 0:lo(r,oy(n));return i!==void 0&&`value`in i?i.value:void 0}function QA(e,t,n){let r=TA(t);XA(e,t,r,n.reduce((e,[t,n])=>Mo(e,IA(DA(e),YA(t)),wA(t,n),go),r??``))}function $A(e,t){return No(e,t,t[0]===`presets`&&t.length>2&&!ZD(t[1])?2:0)}function ej(e,t,n){let r=n.map(JA),i=TA(t);if(i===null)return;let a=r.reduce((e,t)=>$A(e,KA(DA(e),t)),i);a!==i&&XA(e,t,i,a)}function tj(e){let t=e===null?void 0:lo(e,[`presets`]),n=new Set([...XD,...t?.kind===`object`?t.entries.map(e=>e.key):[]].map(ml));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(ml(e)))}function nj(e,t,n,r,i){let a=TA(t),o=DA(a??``),s=tj(o),c=[`presets`,s],l=VA(o,n),u=[...l===null?[]:[[[...c,`root`],l.unit===null?fo(a??``,l.fragment):vo(l.unit.value)]],...Object.keys(r).length===0?[]:[[[...c,`globals`],vo(r)]]],d=i.map(([e,t])=>{let n=iy(s,e);return[IA(o,YA(n)),wA(n,t)]});return XA(e,t,a,[...u,...d].reduce((e,[t,n])=>Mo(e,t,n,go),Mo(a??``,c,`{}`,go))),s}function rj(e,t,n){if(ZD(n))throw new $(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=TA(t),a=DA(i??``);if(i===null||a===null||lo(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=lo(a,[`globals`,`preset`]);XA(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>$A(e,t),i))}function ij(e,t,n,r){let i=JA(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=TA(t),o=r.op===`remove`?r.target:r.anchor,s=WA(DA(a??``),i.preset,o),c=qA(a??``,s),l=r.op===`remove`?Ho(c,s.path,r.target):Uo(c,s.path,r.segment,r.anchor,r.relation);if(l===null)throw new $(`${s.path.join(`.`)} in ${t} has no segment "${o}" — the bar you clicked is stale; it reloads on the next render`);XA(e,t,a,l)}const aj={load:()=>({}),save:()=>{}},oj=new Set(zv.map(e=>e.sessionKey)),sj={past:[],future:[]},cj=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var lj=class{state=new Map;constructor(e,t,n=aj){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}=this.state.get(e)??sj;return{undo:t.length,redo:n.length}}history(e){return this.state.get(e)??sj}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(cj(n));r.set(cj(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=this.sessionState,r=(e,r,i)=>{let a=r.filter(e=>oj.has(e)).map(t=>({key:t,before:n.get(e,t)}));i();for(let{key:r,before:i}of a)t(e,{kind:`session`,key:r,before:i,after:n.get(e,r)})};return{sessionState:{get:(e,t)=>n.get(e,t),set:(e,t,i)=>r(e,[t],()=>n.set(e,t,i)),setBatch:(e,t)=>r(e,t.map(e=>e.key),()=>n.setBatch(e,t)),clear:(e,t)=>r(e,[t],()=>n.clear(e,t))},file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=[...e];e.clear();for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length!==0&&this.put(e,{past:fj([...this.history(e).past,t]),future:[]})}}}}undo(e){let{past:t,future:n}=this.history(e),r=t.at(-1);if(r===void 0)throw new $(`undo: nothing to undo`);return this.apply(e,r,`before`,`undo`,{past:t.slice(0,-1),future:fj([...n,r])}),r}redo(e){let{past:t,future:n}=this.history(e),r=n.at(-1);if(r===void 0)throw new $(`redo: nothing to redo`);return this.apply(e,r,`after`,`redo`,{past:fj([...t,r]),future:n.slice(0,-1)}),r}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(cj));throw this.put(e,{past:pj(this.history(e).past,t),future:pj(this.history(e).future,t)}),new $(`${r}: ${o.map(hj).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):TA(t.file)}write(e,t,n){t.kind===`file`?EA(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)&&n.set(e,t);n.size>32||uj(n)>8388608;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):n.set(e,dj(t))}this.storage.save(Object.fromEntries(n)),this.state=n}};function uj(e){let t=0;for(let{past:n,future:r}of e.values())for(let e of[...n,...r])for(let n of e)t+=(n.before?.length??0)+(n.after?.length??0);return t}function dj({past:e,future:t}){return e.length>0?{past:e.slice(1),future:t}:{past:e,future:t.slice(1)}}function fj(e){return e.slice(-50)}function pj(e,t){return e.map(e=>e.filter(e=>!t.has(cj(e)))).filter(e=>e.length>0)}function mj(e){return e.map(hj).join(`, `)}function hj(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function gj(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 _j(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(gj))}function vj(e){if(typeof e!=`object`||!e)return!1;let t=e;return _j(t.past)&&_j(t.future)}function yj(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(vj))return e}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{r.mkdirSync(c.dirname(e),{recursive:!0}),ke(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 bj={theme:e=>e.theme.kind===`decided`?e.theme.name:null,preset:e=>e.preset,look:e=>e.look.kind===`decided`?e.look.name:null,style:e=>e.style,progression:e=>e.progression,charset:e=>e.charset,colorCompatibility:e=>e.colorCompatibility,autoWrap:e=>e.autoWrap?qa:Ja,padding:e=>String(e.padding)},xj=Object.entries(Rv),Sj=new Set(zv.map(e=>e.sessionKey)),Cj=()=>!1;function wj(e,t){return QD(e,e=>Sj.has(e)?t(e):null,Cj)}function Tj(e,t,n,r){return e.flatMap(([e,i])=>{let a=bj[e](t);return a===null||a===bj[e](n(e))?[]:[{...i,value:a,target:r(i)}]})}function Ej(e,t){let n=wj(e,t),r=QD(e,()=>null,Cj),i=QD(e,e=>e===Rv.preset.sessionKey?n.preset:null,Cj),a=Zv(e.presets,n.preset).globals??{};return Tj(xj,n,e=>e===`preset`?r:i,e=>e.configKey in a?iy(n.preset,e.configKey):e.configKey)}function Dj(e,t){let n=wj(e,t),r=QD(e,e=>e===Rv.preset.sessionKey?n.preset:null,Cj);return{from:n.preset,globals:Zv(e.presets,n.preset).globals??{},picks:Tj(xj.filter(([e])=>e!==`preset`),n,()=>r,e=>e.configKey)}}function Oj(e){return{sessionKeys:zv.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...xc(e)?XD.map(t=>iy(t,e)):[]]}}function kj(e){let t=Ee({bin:`tmux`,args:[`-S`,e.socket,`display`,`-p`,`-t`,e.pane,`#{client_termfeatures}`],timeoutMs:2e3,category:`doctor.tmux`});return t.ok?{kind:`ok`,value:t.stdout.trim().split(`,`).filter(e=>e!==``)}:{kind:`failed`,reason:`tmux display -p failed (${t.error??[t.reason,t.stderr.trim()].filter(e=>e!==``).join(`: `)})`}}function Aj(){return{probeTmux:kj,claudeSettingsPath:yw()}}function jj(e){return r.existsSync(e.claudeSettingsPath)?r.readFileSync(e.claudeSettingsPath,`utf8`):``}function Mj(e){if(/^\s*$/.test(e))return{};let t=_o.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`not a JSON object`);let n=t.env;if(n===void 0)return{};if(typeof n!=`object`||!n||Array.isArray(n))throw Error("`env` is not an object");return n}function Nj(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function Pj(e){try{return Mj(jj(e))}catch(t){throw Error(`cannot read ${e.claudeSettingsPath}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}function Fj(e,t){return{tmux:Nj(e,t),claudeSettingsEnv:Pj(e)}}function Ij(e,t,n){switch(t.kind){case`claude-settings-env`:{let i=Mo(jj(e),[`env`,t.name],JSON.stringify(t.value),_o);return r.mkdirSync(c.dirname(e.claudeSettingsPath),{recursive:!0}),ke(e.claudeSettingsPath,i),{...n,claudeSettingsEnv:Pj(e)}}default:return t.kind}}function Lj(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function Rj(e){return zj(()=>decodeURIComponent(e))}function zj(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function Bj(e,t){let n=Ee({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 Vj=(e,t)=>Bj(Rj(e),t),Hj=(e,t)=>{let n=Ee({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,Rj(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`})`)}},Uj=(e,t)=>Bj(Rj(e),t),Wj=(e,t)=>Bj(Rj(e),t),Gj=(e,t)=>{let n=Lj(Rj(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},Kj=(e,t)=>{let[n=``,...r]=zj(()=>dw(e)),i=Lj(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${NE().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: ${NE().join(`, `)})`);let a=[];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=FE(t,n);if(!i.ok)throw new $(`set-state: pair ${e/2+1}: ${i.reason}`);a.push({key:t,value:i.value})}t.sessionState.setBatch(i,a);let o=a.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${o} (session=${i})`)},qj=/^-?\d+$/;function Jj(e,t,n){return e>n?t:e<t?n:e}const Yj=(e,t)=>{let[n=``,r=``,i=``]=zj(()=>dw(e)),a=Lj(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!qj.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=IE(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${NE().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&qj.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=Jj(l+o,s.min,s.max),d=FE(r,String(u));if(!d.ok)throw new $(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)},Xj=`render-origin`;function Zj(e){return JSON.stringify(e)}function Qj(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 $j(e,t){let n=e.sessionState.get(t,Xj);if(n===null)throw new $(`session ${t} has not rendered yet — no config file to write`);return Qj(n)}function eM(e){return SS(e.projectDir,e.cwd,e.configFile??void 0)}function tM(e,t){return eM($j(e,t))}function nM(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const rM=(e,t)=>{let[n=``,r=``,i=``]=zj(()=>dw(e)),a=Lj(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${gE().join(`, `)})`);let o=_E(r,i);if(!o.ok)throw new $(`set-config: ${o.reason}`);let s=tM(t,a);QA(nM(t,a),s,[[r,o.value]]),t.dlog(`info`,`set-config: ${r}=${o.value} → ${s} (session=${a})`)},iM=(e,t)=>{let[n=``,r=``,i=``]=zj(()=>dw(e)),a=Lj(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!qj.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=vE(r);if(!s)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${gE().join(`, `)})`);let c=tM(t,a),l=ZA(c,r),u=typeof l==`number`?Math.max(s.min,Math.min(s.max,l)):s.seed,d=Jj(u+o,s.min,s.max),f=_E(r,String(d));if(!f.ok)throw new $(`step-config: ${f.reason}`);QA(nM(t,a),c,[[r,f.value]]),t.dlog(`info`,`step-config: ${r} ${u}→${f.value} (by ${o}) → ${c} (session=${a})`)},aM=(e,t)=>{let[n=``]=zj(()=>dw(e)),r=Lj(n),i=$j(t,r),a=Ej(t.configFor(i),e=>t.sessionState.get(r,e));if(a.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let o=a.map(e=>{let t=FE(e.sessionKey,e.value);if(!t.ok)throw new $(`save: ${t.reason}`);return[e.target,t.value]}),s=eM(i);QA(nM(t,r),s,o),t.reloadConfig(i);for(let e of a)t.sessionState.clear(r,e.sessionKey);t.dlog(`info`,`save: ${o.map(([e,t])=>`${e}=${t}`).join(` `)} → ${s} (session=${r})`)},oM=(e,t)=>{let[n=``]=zj(()=>dw(e)),r=Lj(n),i=$j(t,r),a=Dj(t.configFor(i),e=>t.sessionState.get(r,e)),o=a.picks.map(e=>{let t=FE(e.sessionKey,e.value);if(!t.ok)throw new $(`save-preset: ${t.reason}`);return[e.configKey,t.value]}),s=eM(i),c=nj(nM(t,r),s,a.from,a.globals,o);t.reloadConfig(i);for(let e of zv)t.sessionState.clear(r,e.sessionKey);t.sessionState.set(r,Rv.preset.sessionKey,c),t.dlog(`info`,`save-preset: ${[`${c} from=${a.from}`,...o.map(([e,t])=>`${e}=${t}`)].join(` `)} → ${s} (session=${r})`)},sM=(e,t)=>{let[n=``,r=``]=zj(()=>dw(e)),i=Lj(n);if(!r)throw new $(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=$j(t,i),o=eM(a);rj(nM(t,i),o,r),t.reloadConfig(a);let s=Rv.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o} (session=${i})`)},cM=(e,t)=>{let[n=``,...r]=zj(()=>dw(e)),i=Lj(n),a=gE(),o=r.length===0?[``]:r.filter(e=>!a.includes(e));if(o.length>0)throw new $(`reset-config: unknown config key "${o.join(`", "`)}" (have: ${a.join(`, `)})`);let s=$j(t,i),c=eM(s),l=r.map(Oj),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);ej(nM(t,i),c,u),t.reloadConfig(s);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})`)},lM=(e,t)=>{let[n=``,r=``,i=``]=zj(()=>dw(e)),a=Lj(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${gE().join(`, `)})`);let o=_E(r,i);if(!o.ok)throw new $(`apply-layout-op: ${o.reason}`);let s=Gv(o.value);if(s===null)throw new $(`apply-layout-op: "${o.value}" is not a layout op token`);let c=tM(t,a);ij(nM(t,a),c,r,s),t.dlog(`info`,`apply-layout-op: ${r} ${o.value} → ${c} (session=${a})`)},uM=(e,t)=>{let[n=``]=zj(()=>dw(e)),r=Lj(n);t.journal.commit();let i=t.history.undo(r);t.dlog(`info`,`undo: restored ${mj(i)} (session=${r})`)},dM=(e,t)=>{let[n=``]=zj(()=>dw(e)),r=Lj(n);t.journal.commit();let i=t.history.redo(r);t.dlog(`info`,`redo: re-applied ${mj(i)} (session=${r})`)},fM=(e,t)=>{Lj(Rj(e)),t.applyUpdate()},pM=`client-hints`;function mM(e,t){let n=e.sessionState.get(t,pM);if(n===null)throw new $(`session ${t} has not rendered yet — no client facts to diagnose`);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 IS(r)}function hM(e,t,n){let r=zy(n);e.sessionState.setBatch(t,Hy(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed`}`).join(` `)} (session=${t})`)}const gM=(e,t)=>{let n=Lj(Rj(e));hM(t,n,Fj(t.doctor,mM(t,n).tmux))},_M=(e,t)=>{let[n=``,r=``]=zj(()=>dw(e)),i=Lj(n),a=By(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=Fj(t.doctor,mM(t,i).tmux),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=Ij(t.doctor,s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.name}=${s.fix.value} (session=${i})`),hM(t,i,c)},vM=`config-override`,yM=new Map([[qC,Vj],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=Lj(zj(()=>decodeURIComponent(e.slice(0,n)))),i=zj(()=>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,vM),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,vM,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[JC,Hj],[GC,Kj],[KC,Yj],[QC,rM],[$C,iM],[rw,cM],[ew,aM],[tw,oM],[nw,sM],[iw,lM],[aw,uM],[ow,dM],[XC,Uj],[ZC,Wj],[YC,Gj],[sw,fM],[cw,gM],[lw,_M]]),bM=new Set([GC,KC,QC,$C,rw,ew,tw,nw,iw,aw,ow,YC,sw,cw,lw]),xM=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of hw(pw(e))){if(!i&&bM.has(a)){let e=dw(o);e.length>0&&e[0]&&(i=e[0])}let e=yM.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(`
186
- `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}};function SM(e){return(t,n)=>{let r=n.history.begin(),i=[];try{e(t,{...n,sessionState:r.sessionState,journal:r})}catch(e){i.push(e)}try{r.commit()}catch(e){i.push(e)}if(i.length===1)throw i[0];if(i.length>1)throw Error(i.map(e=>String(e.message??e)).join(`; `))}}const CM=new Map([...yM,[WC,xM]].map(([e,t])=>[e,SM(t)]));Object.freeze([...CM.keys()]);const wM=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`]),TM=[[`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`]];function EM(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of TM){let i=OM(n,e);if(i==null)t.missingRequired.push(e);else{let n=DM(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))wM.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function DM(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function OM(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 kM(e,t){switch(e){case`vars`:return{what:e,vars:AM(t)};case`segments`:return{what:e,segments:FM(t)};case`config`:return{what:e,config:RM(t)}}}function AM(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=NM(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,...jM(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:MM(r.lastUpdatedMs())})}return o}function jM(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 MM(e){return e===null?null:Math.max(0,Date.now()-e)}function NM(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,PM(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}`,PM(i));return t}function PM(e){return e.kind}function FM(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=IM(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,description:t.description??null,template:t.template,referencedVars:LM(t.template,n.helpers,i),lastRender:r.get(e)??null})}return o}function IM(e){let t=[],n=new Set;for(let r of Qo(Ws(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 LM(e,t,n){let r=new Set;for(let i of Dg(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 RM(e){return e===null?null:e.config}const zM=[`vars`,`segments`,`config`];function BM(e){return typeof e==`string`&&zM.includes(e)}function VM(e){return Math.max(1,e-2)}var HM=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 D(`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);D(`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{D(`Calculating context tokens from transcript: ${e}`);let n=await CD(e);if(n.length===0)return D(`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,D(`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 D(`Most recent main chain context: ${n} tokens (limit: ${t})`),J({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return D(`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)}},UM=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=oD(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await DD(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 WM={messageCount:0,recent:[]};function GM(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +!!xD(t),recent:n.length>20?n.slice(-20):n}}function KM(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(xD(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 qM=class{fold=new UM(WM,GM);async getMetricsInfo(e,t){if(D(`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:KM(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 JM={command:null,todos:[],pending:[],done:[]};function YM(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 XM(e,t){if(t.isSidechain)return e;let n=xD(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=YM(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 ZM(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>YM(e,t.name),[]),done:e.done}}var QM=class{fold=new UM(JM,XM);async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?X(`activity (${e}): ${n.reason}`):J(ZM(n.value))}};const $M=new Map;function eN(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var tN=class{async getSessionId(){if(!process.env.TMUX_PANE)return Y;let e=eN(process.env.TMUX),t=$M.get(e);if(t!==void 0)return t;D(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await Te({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?J(n.stdout.trim()):Y:X(`tmux display-message: ${n.reason}`);return $M.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}},nN=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 rN=new mA;Ce(rN.launchStats);const iN=new av({counters:rN,logger:Q}),aN=new pv({watchers:iN,logger:Q}),oN=new zD,sN=new _A,cN=new lj(sN,Q),lN=new nN(We()),uN=new HM,dN=new qM,fN=new QM,pN=new tN,mN=new fA({gitService:aN,sessionState:sN,watchers:iN},{observers:{onReload:e=>Q(`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)}`)}}),hN=60*1e3;function gN(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(w(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){Q(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),MN(0);return}}catch(e){Q(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,hN),a.unref())},checkNow:o}}const _N=gN(),vN=nD({entryUrl:import.meta.url,intervalMs:hN,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>_N.checkNow(),log:Q});let yN=null,bN=null,xN=0;function SN(){t.on(`uncaughtException`,e=>{Q(`error`,`uncaughtException: ${e.stack||e.message}`),MN(1)}),t.on(`unhandledRejection`,e=>{Q(`error`,`unhandledRejection: ${String(e)}`),MN(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Q(`info`,`received ${e}, shutting down`),MN(0)});try{xN=gC(t.env)}catch(e){Q(`error`,`refusing to boot: ${e.message}`),MN(1);return}yN=lT(t.pid);let e=yT(xT(yN));if(!e.decision.allow){Q(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),MN(1);return}bN=e.registryPath,r.mkdirSync(Me(),{recursive:!0}),Fe(Ne()),sN.useStorage(new bA(Re(),500,Q)),cN.useStorage(yj(ze(),Q)),fT({anchor:dT(t.env),isAlive:pT,onOrphaned:e=>{Q(`info`,`parent watchdog: ${e}; shutting down`),MN(0)}}),CN(g.createServer({allowHalfOpen:!1},e=>{NN(e)}),Ne(),!1)}function CN(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Q(`error`,`server error: ${i.message}`),MN(1);return}if(r){Q(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}wN(e,n)}),e.listen(n,()=>TN(n))}function wN(e,n){let i=$w(eT(Ie(n)),(e,t)=>cT(e,t,{readStartTime:sT,pidAlive:pT}));if(i.kind===`attach-and-exit`){Q(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}Q(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){Q(`error`,`cannot unlink stale socket ${n}: ${e.message}`),MN(1);return}}CN(e,n,!0)}function TN(e){let n=rT(e);if(n.kind!==`present`){Q(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),MN(0);return}kN(e);try{r.chmodSync(e,384)}catch(e){Q(`warn`,`chmod socket failed: ${e.message}`)}Q(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(C.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(xN/1048576)}MB`),NC();let i=lN.reset();i!==null&&Q(`warn`,`diagnostic dump wipe failed: ${i}`),_N.arm(),vN.arm(),ON(),EN(e,n.identity)}function EN(e,n){oT({bound:n,myPid:t.pid,readIdentity:()=>rT(e),readLease:()=>eT(Ie(e)),shutdown:e=>MN(e),log:Q}).arm()}let DN=null;function ON(){DN=bC(wC(rN.startedAt.getTime(),e=>MN(e),{rssLimitBytes:xN})),DN.arm()}function kN(e){let n=tT(Ie(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:yN});n!==null&&Q(`warn`,`lease write failed: ${n}`)}let AN=0,jN=!1;function MN(e){if(!jN){jN=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{aN.close()}catch(e){Q(`warn`,`gitService close failed: ${e.message}`)}try{oN.close()}catch(e){Q(`warn`,`usageStore close failed: ${e.message}`)}try{iN.closeAll()}catch(e){Q(`warn`,`watcherRegistry close failed: ${e.message}`)}try{sN.flush()}catch(e){Q(`warn`,`sessionState flush failed: ${e.message}`)}nT(Le(),t.pid),bN!==null&&bT(bN,t.pid,_T,e=>r.unlinkSync(e)),t.exit(e)}}function NN(e){AN++,rN.inFlight=AN;let t=!1,n=(n,r)=>{if(t){r!==null&&Q(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>MN(r);try{e.end(US(n),i)}catch(e){Q(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{rN.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=WS(e=>{FN(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{Q(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{Q(`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=>{Q(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),AN=Math.max(0,AN-1),rN.inFlight=AN})}const PN=e=>({resp:e,exitAfterFlush:null});async function FN(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return PN({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?Q(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):Q(`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 PN({ok:!0,stats:rN.snapshot({gitCache:aN.getStats(),usageCache:oN.getStats(),renderCacheSize:mN.size,watchersActive:iN.size(),nextRestartReason:DN?.describeNextRestart()??null})});if(e.kind===`render`){rN.requestsTotal++;let t=Date.now();try{let{report:n}=EM(e.hookData);for(let e of n.unknownTopLevelFields)Q(`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 rN.requestsErrored++,Q(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),PN({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=IN(e.args),s=e.hookData.session_id,c=IS(e),l=JSON.stringify(c);sN.get(s,`client-hints`)!==l&&sN.set(s,pM,l);let u=sN.get(s,`config-override`)??a??c.configEnv,d=mN.getOrCreate(i,e.cwd,u),f=Zj({projectDir:i,cwd:e.cwd,configFile:u??null});sN.get(s,`render-origin`)!==f&&sN.set(s,Xj,f);let p=c.termCols,m=VM(p??120),h=RT(c.termRows),{authoredRoots:g}=d.state,_=t=>sN.get(e.hookData.session_id,t),v=QD(d.state.config,_,e=>g.has(e)),y=await hO(e.hookData,VN,e.cwd,d.state.neededInputPaths(v.preset),v,c,Ej(d.state.config,_).length),b=[],x=$D(v,m),S=Qk(d.state.config,d.state.compiled,d.state.store,d.state.registry,y,x,{perSegmentSink:d.state.lastRenderCellsBySegment,onRenderWarning:e=>b.push(e)},eO(v)),C=sN.get(e.hookData.session_id,`click.error`);C&&sN.clear(e.hookData.session_id,`click.error`);let ee=[o,d.lastError,C].filter(Boolean).join(`
187
- `),te=vN.notice({sessionId:s,dismissed:sN.get(s,HE),enabled:v.updateNotice}),w=d.lastError===null?null:d.configFilePath,ne=UT(ee,te,[d.lastWarning??``,...b].filter(Boolean).join(`
188
- `)),re=lN.sync(s,ne===null?null:GT(ne));re!==null&&Q(`warn`,`diagnostic dump failed: ${re}`);let ie=KT(S,ne,{fullText:re===null?{kind:`file`,path:lN.pathFor(s)}:{kind:`unavailable`,reason:re},failedConfigFile:w},{width:m,rowCap:h,colorCompatibility:v.colorCompatibility}),T=Date.now()-t,E=aN.getStats(),ae=oN.getStats();return Q(`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=${ee?`Y`:`N`} upd=${te.length} warn=${d.lastWarning?`Y`:`N`}`),PN({ok:!0,output:ie+`
189
- `})}catch(e){throw rN.requestsErrored++,e}}if(e.kind===`click`)return PN(await HN(e.verb,e.value));if(e.kind===`debug`){if(!BM(e.what))return PN({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${zM.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=mN.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?BN(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):zN};return PN({ok:!0,debug:kM(e.what,n)})}return PN({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function IN(e){let{values:t,tokens:n}=re({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:LS(t.config),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}const LN={sessionState:sN,dlog:Q,applyUpdate:()=>vN.act(),doctor:Aj(),history:cN,configFor:e=>mN.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>mN.reload(e.projectDir,e.cwd,e.configFile??void 0)},RN={style:`powerline`,colorCompatibility:Ba,wrap:!0,padding:1,charset:Ia,width:1/0},zN=new Map;function BN(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,LT(a,{...RN,charset:t,colorCompatibility:n}));return r}const VN={gitProvider:aN,usageStore:oN,contextProvider:uN,metricsProvider:dN,activityProvider:fN,tmuxService:pN,log:Q,clock:()=>new Date,history:e=>cN.depth(e)};function HN(e,t){let n=CM.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,LN),{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 UN={connectMs:200,budgetMs:500};async function WN(e){let n=e.includes(`--json`),r=await GN();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${QS(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
190
- `);return}t.stdout.write(YN(r.value))}function GN(){return KS({kind:`stats`},UN,e=>`stats`in e?e.stats:void 0)}function KN(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function qN(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function JN(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 YN(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 ${JN(e.uptimeSec)}`),t.push(` rss ${KN(e.rssBytes)}`),t.push(` heapUsed ${KN(e.heapUsedBytes)}`),t.push(` heapTotal ${KN(e.heapTotalBytes)}`),t.push(` external ${KN(e.externalBytes)}`),t.push(` arrayBuffers ${KN(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 ${qN(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 ${qN(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(`
183
+ `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}const Uk=({text:e,trail:t})=>t===void 0?[e]:[e,t];function Wk(e,t){switch(e){case`vertical`:return Kk(t.flatMap(e=>e));case`horizontal`:{let e=t.find(e=>e[0]?.span===`row`);return e===void 0?t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`,span:`shared`},...t.flatMap(e=>e.slice(1))]:Kk(e)}}}function Gk(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r}],band:`own`,span:`shared`}]:Wk(e.direction,e.children.map((t,i)=>n(t,[...r,qk(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function Kk(e){return e.map(e=>e.span===`row`?{...e,span:`shared`}:e)}function qk(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:Xo[e.direction]}}const Jk={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Li(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,$o(t.path,n)))}},render(e,t){return Wk(e.direction,e.children.map((n,r)=>t.renderChild(n,t.visible,qk(e,r))))}},Yk={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,...e.opens!==void 0&&{opens:{open:t.parse(ic(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,es(t.path)),key:e.opens.ref.key,placement:e.opens.placement}},...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[];try{if(!jO(i.when,t.scope))return[];let n=i.palette??t.palette,{styles:a,fragments:o,trail:s,drops:c}=t.evaluateSegment(e.name,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,trail:e.trail}),l=e.opens!==void 0&&jO(e.opens.open,t.scope),u=c.length>0||l?a.trigger:a.closed,d={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:u,padding:t.padding},f=e.opens===void 0?[]:t.renderBody(e.opens.body,l,a.disclosure),p=f.slice(0,+(e.opens?.placement===`inline`)),m=f.slice(p.length),h=e.opens!==void 0&&m.some(e=>e.band===`own`)?FO(zO([t.closeDisclosure(e.opens.key)],a.trigger),{...d,width:`auto`,baseStyle:a.trigger}):[],g=e=>e.band===`own`?h:[],_=m.map(e=>({cells:[...g(e),...e.cells],band:`deeper`,span:`shared`})),v=Hk(zO(o,u)).map((e,t)=>({cells:FO(e,{...d,trail:t===0?zO(s,u):[]}),band:`own`,span:`shared`})),y=c.map(e=>({cells:FO(zO([e],a.band),{...d,baseStyle:a.band}),band:`deeper`,span:`shared`})),b=[...v,...y];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.name,[...b.flatMap(e=>e.cells),...m.flatMap(g)].flatMap(Uk)),[...b.map((e,t)=>t===0&&p.length>0?{cells:[...e.cells,...p.flatMap(e=>e.cells)],band:`own`,span:`row`}:e),..._]}catch(n){let r=n.message??String(n);t.onSegmentError?.(e.name,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:FO([new H(`⚠ ${e.name}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,trail:Xk(e,t)}),band:`own`,span:`shared`}]}}};function Xk(e,t){if(e.trail===void 0)return[];try{return t.evaluateSegment(e.name,t.palette,t.region,{bg:void 0,fg:void 0,body:e.trail,trail:void 0}).fragments}catch(n){return t.onSegmentError?.(e.name,n.message??String(n)),[]}}const Zk={container:Jk,segment:Yk};function Qk(e){return Zk[e]}function $k(e){if(`ttl`in e)return{kind:`ttl`,durationMs:yv(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 eA(e,t){switch(rs(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 tA(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:$k(n.cache),parse:eA(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cache:$k(n.cache),parse:eA(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?yv(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 nA(e,t){let n=Au.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 rA=e=>Ka(void 0,null,e.globals.progression);function iA(e,t,n){let r=n?.cwd??process.cwd(),i=eS(e.globals.palette),a={store:t.variableStore,compiled:new Map,chromeCols:IT({style:`powerline`,charset:Ia}),width:80,basePalette:i,palette:i,progression:ki[rA(e)],padding:1,seamCols:LT({style:`powerline`,charset:Ia}),layout:()=>[]},o=uk(t.drawnAt),s={action:a,activeSegment:o},c=Object.keys(e.looks),l=Xv(e.presets),u=new Map([...rS(e),...wy(e)]),d=A_({...ik(a),...xk(a,o),...wk(a,o),...Ok(a,o),...Nk(a,o),...Lk(s),...Bk(o),looks:{fn:()=>c,argTypes:[]},presets:{fn:()=>l,argTypes:[]}},n?.clock,t.drawnAt),f=nA(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 Vv)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=qO(p,e.actions,g,u);let _=[];for(let[n,i]of Object.entries(e.variables))try{tA(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{tA(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`),palette:n.palette===void 0?void 0:qx(n.palette)}}let y=(e,t,n)=>{try{return h(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},b=(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:b};return Qk(e.kind).compile(e,n)},x=new Map;for(let t of l){let{node:n,path:r}=$v(e,t);x.set(t,b(n,r))}let S=new Map;for(let t of wa){let n=e.globals[t];Ta(n)&&S.set(t,aA(p,t,n))}return{segments:v,roots:x,activeSegment:o,menuRuntime:s,globalExpressions:S,loadWarnings:_}}function aA(e,t,n){try{return e(n)}catch(e){throw Error(`globals.${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function oA(e,t,n){let r=e.globalExpressions.get(t);if(r===void 0)throw Error(`globals.${t} is an expression but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r.evaluate(n).map(e=>e.plain).join(``)}function sA(e,t){return e.kind===`decided`?e.name:t}function cA(e,t,n,r,i,a,o,s){let{perSegmentSink:c,onSegmentError:l,onRenderWarning:u}=o??{};r.drawAt(Ua(a.colorCompatibility));let{preset:d=Jv}=s??{},f=ki[s?.progression??rA(e)];t.menuRuntime.action.progression=f;let p=s?.look??Aa(`none`,e.looks),m=s?.theme??Qx(void 0,null,e.globals.palette),h=(e,t)=>({...i,term:{cols:a.width},theme:{effective:e},look:{effective:t}});r.applyInput(h(sA(m,ya),sA(p,Oa))),t.menuRuntime.action.chromeCols=IT(a),t.menuRuntime.action.padding=a.padding,t.menuRuntime.action.width=a.width,t.menuRuntime.action.seamCols=LT(a);let g=j_(n),_=Da(m,()=>oA(t,`palette`,g),e=>Zx(e,e=>u?.(e))),v=Da(p,()=>oA(t,`look`,g),t=>Aa(t,e.looks));(_!==m||v!==p)&&r.applyInput(h(_.name,v.name));let y=_.value;t.menuRuntime.action.basePalette=y;let b=Yx(y,v.value);t.menuRuntime.action.palette=b,c?.clear();let x=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},S=(e,n,i,a)=>{try{let o=r.drawnAt(),{tint:s,disclosure:c}=ga(n,i,o),l=dk(t.activeSegment,e,n,c,s),u=WO(l,o,a.bg,a.fg,g),d=a.body.evaluate(g),f=a.trail?.evaluate(g)??[];return{styles:{closed:u,get trigger(){return ok(n,aa(n,c,o).state,o)},get band(){return ok(n,aa(n,c,o).plane,o)},disclosure:c},fragments:d,trail:f,drops:l.drops}}finally{t.activeSegment.current=null}},C=(e,t,r)=>{let i=t&&jO(e.when,g),o={scope:g,palette:b,visible:i,padding:a.padding,region:r,perSegmentSink:c,onSegmentError:l,evaluateSegment:S,lookupSegment:x,renderChild:(e,t,n)=>C(e,t,ma(r,n)),renderBody:(e,t,n)=>C(e,i&&t,ha(n)),closeDisclosure:e=>ak(n,e)};return Qk(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 "${Jv}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let te=e=>{if(!jO(e.when,g))return!1;if(e.kind===`container`)return!0;if(Oy(e.name)===void 0)return!1;try{return jO(t.segments[e.name].when,g)}catch{return!0}};return t.menuRuntime.action.layout=()=>Gk(ee,te).map(e=>e.flatMap(e=>{let n=Oy(e.name);return n===void 0?[]:[{...e,name:n,palette:t.segments[n].palette??b}]})),C(ee,!0,pa(f)).map(e=>RT(RO(e.cells,a),a)).join(`
184
+ `)}var lA=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,hA(e,t,n,`initial value`),this.cell=Lg.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){hA(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}},uA=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,Lg.computed)(()=>{let e=n();return hA(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},dA=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=Lg.observable.box(mA(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=mA(e);pA(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function fA(e){return JSON.stringify(e)}function pA(e,t){return fA(e)===fA(t)}function mA(e){return e.kind===`ok`?{kind:`ok`,value:Rg(e.value)}:e}function hA(e,t,n,r){let i=zg(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var gA=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new lA(e,t,n))}defineDocument(e,t){this.assertNotDefined(e),this.nodes.set(e,new dA(e,t))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new uA(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,Lg.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,Lg.runInAction)(()=>n.set(t))}runInAction(e){(0,Lg.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 fA(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 _A(e,t,n){return e+`\0`+t+`\0`+(n??``)}function vA(e,t){return new Set(Xv(e.presets).filter(n=>$v(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function yA(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 bA(e,t){let n=new Map;for(let t of bS(e.projectDir,e.cwd,e.configFile)){let{dir:e,name:r}=yA(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 xA(e){return e.filter(Boolean).join(`
185
+ `)||null}var SA=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=_A(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.loadFromDisk(e,t,n),o={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:a.error,lastWarning:a.warning,state:a.state??this.buildState(t,null,[]),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.state.validatorDisposers.forEach(e=>e()),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=this.loadFromDisk(e.projectDir,e.cwd,e.configFile);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(e.state.registry.dispose(),e.state.validatorDisposers.forEach(e=>e()),e.state=t.state),this.refreshWatcher(e,t.resolvedPath),this.observers.onReload?.(e)}loadFromDisk(e,t,n){let r=SS(e,t,n),i=r.kind===`file`?r.path:null,a=[ES(e,t),wS(r)],o;try{o=this.buildState(t,i,a)}catch(e){return e instanceof Wo&&a.push(...e.warnings),{resolvedPath:i,warning:xA(a),state:null,error:e instanceof Wo||e instanceof Error?e.message:String(e)}}return{resolvedPath:i,warning:xA(a),state:o,error:null}}buildState(e,t,n){let r=DS(t,kE),{config:i,raw:a}=r;n.push(...r.warnings);let o=AS(r,t??`<default>`),s=new gA,c=new Iv(s,o.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),l,u=[];try{l=iA(o,c,{cwd:e}),n.push(...l.loadWarnings);for(let{key:e,spec:t}of BD(o))u.push(ND(e,t));for(let{key:e,spec:t}of CE(o))u.push(wE(e,t))}catch(e){for(let e of u)e();throw c.dispose(),e}return{config:o,store:s,registry:c,compiled:l,neededInputPaths:iD(o),lastRenderCellsBySegment:new Map,validatorDisposers:u,authoredRoots:vA(i,a)}}refreshWatcher(e,t){e.configFilePath=t;let n=bA(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){Q(`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 CA=16384;var wA=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<CA){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%CA}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:yw,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}}};const TA={load:()=>({}),save:()=>{},flush:()=>{}};function EA(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var DA=class{sessions;storage;atom=(0,Lg.createAtom)(`SessionState`);constructor(e=TA,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=EA(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,Lg.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,Lg.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,Lg.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}};const OA=(e,t)=>D(t);function kA(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 AA=class{timer=null;pending=null;constructor(e,t=500,n=OA){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 kA(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 jA={default_bg:`string`,default_fg:`string`,default_empty_value:`string`,default_separator:`string`,default_truncate_marker:`string`,palette:`string`,look:`string`,preset:`string`,style:`string`,progression:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,updateNotice:`boolean`,colorCompatibility:`string`,menuGlyph:`string`},MA=new Set([`1`,`true`]),NA=new Set([`0`,`false`,``]);function PA(e,t){let n=aj(e),r=n.scope===`segment-palette`?`string`:jA[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(MA.has(t))return`true`;if(NA.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function FA(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function IA(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(c.dirname(e),{recursive:!0}),ke(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function LA(e){return/^\s*$/.test(e)?null:so(e)}function RA(e,t){return e!==null&&lo(e,t)!==void 0}function zA(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(zA),...i}}return e}function BA(e){if(!Vs(e))return zA(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,zA(t)])),...n}}const VA=DE,HA=VA.segments,UA=VA.presets,WA=VA.root;function GA(e,t,n,r){if(!RA(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function KA(e,t){let n=sy(t);return t.scope===`segment-palette`&&GA(e,[`segments`,t.segment],HA[t.segment],n.join(`.`)),n}function qA(e){return so(vo(e))}function JA(){return Object.entries(WA.rows).map(([e,t])=>{let n=zA(t);return{path:[`root`],fragment:qA({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function YA(e,t){let n=e===null?void 0:lo(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function XA(e,t){if(t===void 0)return null;let n=BA(t);return{path:e,fragment:qA(n),unit:{path:e,value:n}}}function ZA(e,t){let n=[`presets`,t],r=[...n,`root`],i=UA[t];GA(e,n,i,r.join(`.`));let a=YA(e,r)??XA(r,i?.root);return a!==null&&Ro(a.fragment)?a:null}function QA(e,t){let n=Lo(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 $A(e,t){return[...JA(),YA(e,[`root`]),ZA(e,t)].filter(e=>e!==null).reduce(QA,new Map)}function ej(e,t,n){for(let{node:r,...i}of $A(e,t).values())if(Bo(r,n))return i;throw new $(`${tj(e,t).join(`.`)} holds no segment "${n}" — the bar you clicked is stale; it reloads on the next render`)}function tj(e,t){return ZA(e,t)?.path??[`root`]}function nj(e,t){return t.scope===`preset-root`?tj(e,t.preset):sy(t)}function rj(e,{unit:t}){return t===null?e:Mo(e,t.path,vo(t.value),go)}function ij(e){let t=oy(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function aj(e){let t=ij(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function oj(e,t,n,r){try{AS(OS(t,r,kE),t)}catch(e){throw e instanceof Wo?new $(`refused: the config file would not load after this click — ${e.message}`):e}IA(t,r,e.logger),e.record(t,n,r)}function sj(e,t){let n=aj(t),r=LA(FA(e)??``),i=r===null?void 0:lo(r,sy(n));return i!==void 0&&`value`in i?i.value:void 0}function cj(e,t,n){let r=FA(t);oj(e,t,r,n.reduce((e,[t,n])=>Mo(e,KA(LA(e),aj(t)),PA(t,n),go),r??``))}function lj(e,t){return No(e,t,t[0]===`presets`&&t.length>2&&!jE(t[1])?2:0)}function uj(e,t,n){let r=n.map(ij),i=FA(t);if(i===null)return;let a=r.reduce((e,t)=>lj(e,nj(LA(e),t)),i);a!==i&&oj(e,t,i,a)}function dj(e){let t=e===null?void 0:lo(e,[`presets`]),n=new Set([...AE,...t?.kind===`object`?t.entries.map(e=>e.key):[]].map(ml));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(ml(e)))}function fj(e,t,n,r,i){let a=FA(t),o=LA(a??``),s=dj(o),c=[`presets`,s],l=ZA(o,n),u=[...l===null?[]:[[[...c,`root`],l.unit===null?fo(a??``,l.fragment):vo(l.unit.value)]],...Object.keys(r).length===0?[]:[[[...c,`globals`],vo(r)]]],d=i.map(([e,t])=>{let n=ay(s,e);return[KA(o,aj(n)),PA(n,t)]});return oj(e,t,a,[...u,...d].reduce((e,[t,n])=>Mo(e,t,n,go),Mo(a??``,c,`{}`,go))),s}function pj(e,t,n){if(jE(n))throw new $(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=FA(t),a=LA(i??``);if(i===null||a===null||lo(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=lo(a,[`globals`,`preset`]);oj(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>lj(e,t),i))}function mj(e,t,n,r){let i=ij(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=FA(t),o=r.op===`remove`?r.target:r.anchor,s=ej(LA(a??``),i.preset,o),c=rj(a??``,s),l=r.op===`remove`?Ho(c,s.path,r.target):Uo(c,s.path,r.segment,r.anchor,r.relation);if(l===null)throw new $(`${s.path.join(`.`)} in ${t} has no segment "${o}" — the bar you clicked is stale; it reloads on the next render`);oj(e,t,a,l)}const hj={load:()=>({}),save:()=>{}},gj=new Set(zv.map(e=>e.sessionKey)),_j={past:[],future:[]},vj=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var yj=class{state=new Map;constructor(e,t,n=hj){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}=this.state.get(e)??_j;return{undo:t.length,redo:n.length}}history(e){return this.state.get(e)??_j}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(vj(n));r.set(vj(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=this.sessionState,r=(e,r,i)=>{let a=r.filter(e=>gj.has(e)).map(t=>({key:t,before:n.get(e,t)}));i();for(let{key:r,before:i}of a)t(e,{kind:`session`,key:r,before:i,after:n.get(e,r)})};return{sessionState:{get:(e,t)=>n.get(e,t),set:(e,t,i)=>r(e,[t],()=>n.set(e,t,i)),setBatch:(e,t)=>r(e,t.map(e=>e.key),()=>n.setBatch(e,t)),clear:(e,t)=>r(e,[t],()=>n.clear(e,t))},file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=[...e];e.clear();for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length!==0&&this.put(e,{past:Sj([...this.history(e).past,t]),future:[]})}}}}undo(e){let{past:t,future:n}=this.history(e),r=t.at(-1);if(r===void 0)throw new $(`undo: nothing to undo`);return this.apply(e,r,`before`,`undo`,{past:t.slice(0,-1),future:Sj([...n,r])}),r}redo(e){let{past:t,future:n}=this.history(e),r=n.at(-1);if(r===void 0)throw new $(`redo: nothing to redo`);return this.apply(e,r,`after`,`redo`,{past:Sj([...t,r]),future:n.slice(0,-1)}),r}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(vj));throw this.put(e,{past:Cj(this.history(e).past,t),future:Cj(this.history(e).future,t)}),new $(`${r}: ${o.map(Tj).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):FA(t.file)}write(e,t,n){t.kind===`file`?IA(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)&&n.set(e,t);n.size>32||bj(n)>8388608;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):n.set(e,xj(t))}this.storage.save(Object.fromEntries(n)),this.state=n}};function bj(e){let t=0;for(let{past:n,future:r}of e.values())for(let e of[...n,...r])for(let n of e)t+=(n.before?.length??0)+(n.after?.length??0);return t}function xj({past:e,future:t}){return e.length>0?{past:e.slice(1),future:t}:{past:e,future:t.slice(1)}}function Sj(e){return e.slice(-50)}function Cj(e,t){return e.map(e=>e.filter(e=>!t.has(vj(e)))).filter(e=>e.length>0)}function wj(e){return e.map(Tj).join(`, `)}function Tj(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function Ej(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 Dj(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(Ej))}function Oj(e){if(typeof e!=`object`||!e)return!1;let t=e;return Dj(t.past)&&Dj(t.future)}function kj(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(Oj))return e}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{r.mkdirSync(c.dirname(e),{recursive:!0}),ke(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)}}}}function Aj(e){let t=Ee({bin:`tmux`,args:[`-S`,e.socket,`display`,`-p`,`-t`,e.pane,`#{client_termfeatures}`],timeoutMs:2e3,category:`doctor.tmux`});return t.ok?{kind:`ok`,value:t.stdout.trim().split(`,`).filter(e=>e!==``)}:{kind:`failed`,reason:`tmux display -p failed (${t.error??[t.reason,t.stderr.trim()].filter(e=>e!==``).join(`: `)})`}}function jj(){return{probeTmux:Aj,claudeSettingsPath:bw()}}function Mj(e){return r.existsSync(e.claudeSettingsPath)?r.readFileSync(e.claudeSettingsPath,`utf8`):``}function Nj(e){if(/^\s*$/.test(e))return{};let t=_o.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`not a JSON object`);let n=t.env;if(n===void 0)return{};if(typeof n!=`object`||!n||Array.isArray(n))throw Error("`env` is not an object");return n}function Pj(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function Fj(e){try{return Nj(Mj(e))}catch(t){throw Error(`cannot read ${e.claudeSettingsPath}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}function Ij(e,t){return{tmux:Pj(e,t),claudeSettingsEnv:Fj(e)}}function Lj(e,t,n){switch(t.kind){case`claude-settings-env`:{let i=Mo(Mj(e),[`env`,t.name],JSON.stringify(t.value),_o);return r.mkdirSync(c.dirname(e.claudeSettingsPath),{recursive:!0}),ke(e.claudeSettingsPath,i),{...n,claudeSettingsEnv:Fj(e)}}default:return t.kind}}function Rj(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function zj(e){return Bj(()=>decodeURIComponent(e))}function Bj(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function Vj(e,t){let n=Ee({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 Hj=(e,t)=>Vj(zj(e),t),Uj=(e,t)=>{let n=Ee({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,zj(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`})`)}},Wj=(e,t)=>Vj(zj(e),t),Gj=(e,t)=>Vj(zj(e),t),Kj=(e,t)=>{let n=Rj(zj(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},qj=(e,t)=>{let[n=``,...r]=Bj(()=>fw(e)),i=Rj(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${MD().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: ${MD().join(`, `)})`);let a=[];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=PD(t,n);if(!i.ok)throw new $(`set-state: pair ${e/2+1}: ${i.reason}`);a.push({key:t,value:i.value})}t.sessionState.setBatch(i,a);let o=a.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${o} (session=${i})`)},Jj=/^-?\d+$/;function Yj(e,t,n){return e>n?t:e<t?n:e}const Xj=(e,t)=>{let[n=``,r=``,i=``]=Bj(()=>fw(e)),a=Rj(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!Jj.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=FD(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${MD().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&Jj.test(c)?Zj(s,parseInt(c,10)):Qj(`step-state`,r,s,RD(t.configFor(nM(t,a)),e=>t.sessionState.get(a,e),r)),u=Yj(l+o,s.min,s.max),d=PD(r,String(u));if(!d.ok)throw new $(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)};function Zj(e,t){return Math.max(e.min,Math.min(e.max,t))}function Qj(e,t,n,r){if(r===null)return n.min;if(!Jj.test(r))throw new $(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return Zj(n,parseInt(r,10))}const $j=`render-origin`;function eM(e){return JSON.stringify(e)}function tM(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 nM(e,t){let n=e.sessionState.get(t,$j);if(n===null)throw new $(`session ${t} has not rendered yet — no config to act on`);return tM(n)}function rM(e){return CS(e.projectDir,e.cwd,e.configFile??void 0)}function iM(e,t){return rM(nM(e,t))}function aM(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const oM=(e,t)=>{let[n=``,r=``,i=``]=Bj(()=>fw(e)),a=Rj(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${gE().join(`, `)})`);let o=_E(r,i);if(!o.ok)throw new $(`set-config: ${o.reason}`);let s=iM(t,a);cj(aM(t,a),s,[[r,o.value]]),t.dlog(`info`,`set-config: ${r}=${o.value} → ${s} (session=${a})`)},sM=(e,t)=>{let[n=``,r=``,i=``]=Bj(()=>fw(e)),a=Rj(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!Jj.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=vE(r);if(!s)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${gE().join(`, `)})`);let c=nM(t,a),l=rM(c),u=sj(l,r),d=typeof u==`number`?Zj(s,u):Qj(`step-config`,r,s,bE(t.configFor(c),r)),f=Yj(d+o,s.min,s.max),p=_E(r,String(f));if(!p.ok)throw new $(`step-config: ${p.reason}`);cj(aM(t,a),l,[[r,p.value]]),t.dlog(`info`,`step-config: ${r} ${d}→${p.value} (by ${o}) → ${l} (session=${a})`)},cM=(e,t)=>{let[n=``]=Bj(()=>fw(e)),r=Rj(n),i=nM(t,r),a=xD(t.configFor(i),e=>t.sessionState.get(r,e));if(a.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let o=a.map(e=>{let t=PD(e.sessionKey,e.value);if(!t.ok)throw new $(`save: ${t.reason}`);return[e.target,t.value]}),s=rM(i);cj(aM(t,r),s,o),t.reloadConfig(i);for(let e of a)t.sessionState.clear(r,e.sessionKey);t.dlog(`info`,`save: ${o.map(([e,t])=>`${e}=${t}`).join(` `)} → ${s} (session=${r})`)},lM=(e,t)=>{let[n=``]=Bj(()=>fw(e)),r=Rj(n),i=nM(t,r),a=SD(t.configFor(i),e=>t.sessionState.get(r,e)),o=a.picks.map(e=>{let t=PD(e.sessionKey,e.value);if(!t.ok)throw new $(`save-preset: ${t.reason}`);return[e.configKey,t.value]}),s=rM(i),c=fj(aM(t,r),s,a.from,a.globals,o);t.reloadConfig(i);for(let e of zv)t.sessionState.clear(r,e.sessionKey);t.sessionState.set(r,Rv.preset.sessionKey,c),t.dlog(`info`,`save-preset: ${[`${c} from=${a.from}`,...o.map(([e,t])=>`${e}=${t}`)].join(` `)} → ${s} (session=${r})`)},uM=(e,t)=>{let[n=``,r=``]=Bj(()=>fw(e)),i=Rj(n);if(!r)throw new $(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=nM(t,i),o=rM(a);pj(aM(t,i),o,r),t.reloadConfig(a);let s=Rv.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o} (session=${i})`)},dM=(e,t)=>{let[n=``,...r]=Bj(()=>fw(e)),i=Rj(n),a=gE(),o=r.length===0?[``]:r.filter(e=>!a.includes(e));if(o.length>0)throw new $(`reset-config: unknown config key "${o.join(`", "`)}" (have: ${a.join(`, `)})`);let s=nM(t,i),c=rM(s),l=r.map(CD),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);uj(aM(t,i),c,u),t.reloadConfig(s);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})`)},fM=(e,t)=>{let[n=``,r=``,i=``]=Bj(()=>fw(e)),a=Rj(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${gE().join(`, `)})`);let o=_E(r,i);if(!o.ok)throw new $(`apply-layout-op: ${o.reason}`);let s=Kv(o.value);if(s===null)throw new $(`apply-layout-op: "${o.value}" is not a layout op token`);let c=iM(t,a);mj(aM(t,a),c,r,s),t.dlog(`info`,`apply-layout-op: ${r} ${o.value} → ${c} (session=${a})`)},pM=(e,t)=>{let[n=``]=Bj(()=>fw(e)),r=Rj(n);t.journal.commit();let i=t.history.undo(r);t.dlog(`info`,`undo: restored ${wj(i)} (session=${r})`)},mM=(e,t)=>{let[n=``]=Bj(()=>fw(e)),r=Rj(n);t.journal.commit();let i=t.history.redo(r);t.dlog(`info`,`redo: re-applied ${wj(i)} (session=${r})`)},hM=(e,t)=>{Rj(zj(e)),t.applyUpdate()},gM=`client-hints`;function _M(e,t){let n=e.sessionState.get(t,gM);if(n===null)throw new $(`session ${t} has not rendered yet — no client facts to diagnose`);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 LS(r)}function vM(e,t,n){let r=By(n);e.sessionState.setBatch(t,Uy(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed`}`).join(` `)} (session=${t})`)}const yM=(e,t)=>{let n=Rj(zj(e));vM(t,n,Ij(t.doctor,_M(t,n).tmux))},bM=(e,t)=>{let[n=``,r=``]=Bj(()=>fw(e)),i=Rj(n),a=Vy(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=Ij(t.doctor,_M(t,i).tmux),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=Lj(t.doctor,s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.name}=${s.fix.value} (session=${i})`),vM(t,i,c)},xM=`config-override`,SM=new Map([[JC,Hj],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=Rj(Bj(()=>decodeURIComponent(e.slice(0,n)))),i=Bj(()=>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,xM),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,xM,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[YC,Uj],[KC,qj],[qC,Xj],[$C,oM],[ew,sM],[iw,dM],[tw,cM],[nw,lM],[rw,uM],[aw,fM],[ow,pM],[sw,mM],[ZC,Wj],[QC,Gj],[XC,Kj],[cw,hM],[lw,yM],[uw,bM]]),CM=new Set([KC,qC,$C,ew,iw,tw,nw,rw,aw,ow,sw,XC,cw,lw,uw]),wM=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of gw(mw(e))){if(!i&&CM.has(a)){let e=fw(o);e.length>0&&e[0]&&(i=e[0])}let e=SM.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(`
186
+ `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}};function TM(e){return(t,n)=>{let r=n.history.begin(),i=[];try{e(t,{...n,sessionState:r.sessionState,journal:r})}catch(e){i.push(e)}try{r.commit()}catch(e){i.push(e)}if(i.length===1)throw i[0];if(i.length>1)throw Error(i.map(e=>String(e.message??e)).join(`; `))}}const EM=new Map([...SM,[GC,wM]].map(([e,t])=>[e,TM(t)]));Object.freeze([...EM.keys()]);const DM=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`]),OM=[[`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`]];function kM(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of OM){let i=jM(n,e);if(i==null)t.missingRequired.push(e);else{let n=AM(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))DM.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function AM(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function jM(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 MM(e,t){switch(e){case`vars`:return{what:e,vars:NM(t)};case`segments`:return{what:e,segments:RM(t)};case`config`:return{what:e,config:VM(t)}}}function NM(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=IM(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,...PM(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:FM(r.lastUpdatedMs())})}return o}function PM(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 FM(e){return e===null?null:Math.max(0,Date.now()-e)}function IM(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,LM(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}`,LM(i));return t}function LM(e){return e.kind}function RM(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=zM(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,description:t.description??null,template:t.template,referencedVars:BM(t.template,n.helpers,i),lastRender:r.get(e)??null})}return o}function zM(e){let t=[],n=new Set;for(let r of Qo(Ws(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 BM(e,t,n){let r=new Set;for(let i of Dg(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 VM(e){return e===null?null:e.config}const HM=[`vars`,`segments`,`config`];function UM(e){return typeof e==`string`&&HM.includes(e)}function WM(e){return Math.max(1,e-2)}var GM=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 D(`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);D(`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{D(`Calculating context tokens from transcript: ${e}`);let n=await mO(e);if(n.length===0)return D(`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,D(`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 D(`Most recent main chain context: ${n} tokens (limit: ${t})`),J({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return D(`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)}},KM=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=ME(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await vO(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 qM={messageCount:0,recent:[]};function JM(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +!!fO(t),recent:n.length>20?n.slice(-20):n}}function YM(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(fO(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 XM=class{fold=new KM(qM,JM);async getMetricsInfo(e,t){if(D(`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:YM(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 ZM={command:null,todos:[],pending:[],done:[]};function QM(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 $M(e,t){if(t.isSidechain)return e;let n=fO(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=QM(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 eN(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>QM(e,t.name),[]),done:e.done}}var tN=class{fold=new KM(ZM,$M);async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?X(`activity (${e}): ${n.reason}`):J(eN(n.value))}};const nN=new Map;function rN(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var iN=class{async getSessionId(){if(!process.env.TMUX_PANE)return Y;let e=rN(process.env.TMUX),t=nN.get(e);if(t!==void 0)return t;D(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await Te({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?J(n.stdout.trim()):Y:X(`tmux display-message: ${n.reason}`);return nN.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}},aN=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 oN=new wA;Ce(oN.launchStats);const sN=new av({counters:oN,logger:Q}),cN=new pv({watchers:sN,logger:Q}),lN=new AO,uN=new DA,dN=new yj(uN,Q),fN=new aN(We()),pN=new GM,mN=new XM,hN=new tN,gN=new iN,_N=new SA({gitService:cN,sessionState:uN,watchers:sN},{observers:{onReload:e=>Q(`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)}`)}}),vN=60*1e3;function yN(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(w(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){Q(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),FN(0);return}}catch(e){Q(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,vN),a.unref())},checkNow:o}}const bN=yN(),xN=tO({entryUrl:import.meta.url,intervalMs:vN,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>bN.checkNow(),log:Q});let SN=null,CN=null,wN=0;function TN(){t.on(`uncaughtException`,e=>{Q(`error`,`uncaughtException: ${e.stack||e.message}`),FN(1)}),t.on(`unhandledRejection`,e=>{Q(`error`,`unhandledRejection: ${String(e)}`),FN(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Q(`info`,`received ${e}, shutting down`),FN(0)});try{wN=_C(t.env)}catch(e){Q(`error`,`refusing to boot: ${e.message}`),FN(1);return}SN=uT(t.pid);let e=bT(ST(SN));if(!e.decision.allow){Q(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),FN(1);return}CN=e.registryPath,r.mkdirSync(Me(),{recursive:!0}),Fe(Ne()),uN.useStorage(new AA(Re(),500,Q)),dN.useStorage(kj(ze(),Q)),pT({anchor:fT(t.env),isAlive:mT,onOrphaned:e=>{Q(`info`,`parent watchdog: ${e}; shutting down`),FN(0)}}),EN(g.createServer({allowHalfOpen:!1},e=>{IN(e)}),Ne(),!1)}function EN(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Q(`error`,`server error: ${i.message}`),FN(1);return}if(r){Q(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}DN(e,n)}),e.listen(n,()=>ON(n))}function DN(e,n){let i=eT(tT(Ie(n)),(e,t)=>lT(e,t,{readStartTime:cT,pidAlive:mT}));if(i.kind===`attach-and-exit`){Q(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}Q(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){Q(`error`,`cannot unlink stale socket ${n}: ${e.message}`),FN(1);return}}EN(e,n,!0)}function ON(e){let n=iT(e);if(n.kind!==`present`){Q(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),FN(0);return}MN(e);try{r.chmodSync(e,384)}catch(e){Q(`warn`,`chmod socket failed: ${e.message}`)}Q(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(C.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(wN/1048576)}MB`),PC();let i=fN.reset();i!==null&&Q(`warn`,`diagnostic dump wipe failed: ${i}`),bN.arm(),xN.arm(),jN(),kN(e,n.identity)}function kN(e,n){sT({bound:n,myPid:t.pid,readIdentity:()=>iT(e),readLease:()=>tT(Ie(e)),shutdown:e=>FN(e),log:Q}).arm()}let AN=null;function jN(){AN=xC(TC(oN.startedAt.getTime(),e=>FN(e),{rssLimitBytes:wN})),AN.arm()}function MN(e){let n=nT(Ie(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:SN});n!==null&&Q(`warn`,`lease write failed: ${n}`)}let NN=0,PN=!1;function FN(e){if(!PN){PN=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{cN.close()}catch(e){Q(`warn`,`gitService close failed: ${e.message}`)}try{lN.close()}catch(e){Q(`warn`,`usageStore close failed: ${e.message}`)}try{sN.closeAll()}catch(e){Q(`warn`,`watcherRegistry close failed: ${e.message}`)}try{uN.flush()}catch(e){Q(`warn`,`sessionState flush failed: ${e.message}`)}rT(Le(),t.pid),CN!==null&&xT(CN,t.pid,vT,e=>r.unlinkSync(e)),t.exit(e)}}function IN(e){NN++,oN.inFlight=NN;let t=!1,n=(n,r)=>{if(t){r!==null&&Q(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>FN(r);try{e.end(WS(n),i)}catch(e){Q(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{oN.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=GS(e=>{RN(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{Q(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{Q(`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=>{Q(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),NN=Math.max(0,NN-1),oN.inFlight=NN})}const LN=e=>({resp:e,exitAfterFlush:null});async function RN(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return LN({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?Q(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):Q(`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 LN({ok:!0,stats:oN.snapshot({gitCache:cN.getStats(),usageCache:lN.getStats(),renderCacheSize:_N.size,watchersActive:sN.size(),nextRestartReason:AN?.describeNextRestart()??null})});if(e.kind===`render`){oN.requestsTotal++;let t=Date.now();try{let{report:n}=kM(e.hookData);for(let e of n.unknownTopLevelFields)Q(`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 oN.requestsErrored++,Q(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),LN({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=zN(e.args),s=e.hookData.session_id,c=LS(e),l=JSON.stringify(c);uN.get(s,`client-hints`)!==l&&uN.set(s,gM,l);let u=uN.get(s,`config-override`)??a??c.configEnv,d=_N.getOrCreate(i,e.cwd,u),f=eM({projectDir:i,cwd:e.cwd,configFile:u??null});uN.get(s,`render-origin`)!==f&&uN.set(s,$j,f);let p=c.termCols,m=WM(p??120),h=zT(c.termRows),{authoredRoots:g}=d.state,_=t=>uN.get(e.hookData.session_id,t),v=GE(d.state.config,_,e=>g.has(e)),y=await cD(e.hookData,WN,e.cwd,d.state.neededInputPaths(v.preset),v,c,xD(d.state.config,_).length),b=[],x=KE(v,m),S=cA(d.state.config,d.state.compiled,d.state.store,d.state.registry,y,x,{perSegmentSink:d.state.lastRenderCellsBySegment,onRenderWarning:e=>b.push(e)},qE(v)),C=uN.get(e.hookData.session_id,`click.error`);C&&uN.clear(e.hookData.session_id,`click.error`);let ee=[o,d.lastError,C].filter(Boolean).join(`
187
+ `),te=xN.notice({sessionId:s,dismissed:uN.get(s,VD),enabled:v.updateNotice}),w=d.lastError===null?null:d.configFilePath,ne=WT(ee,te,[d.lastWarning??``,...b].filter(Boolean).join(`
188
+ `)),re=fN.sync(s,ne===null?null:KT(ne));re!==null&&Q(`warn`,`diagnostic dump failed: ${re}`);let ie=qT(S,ne,{fullText:re===null?{kind:`file`,path:fN.pathFor(s)}:{kind:`unavailable`,reason:re},failedConfigFile:w},{width:m,rowCap:h,colorCompatibility:v.colorCompatibility}),T=Date.now()-t,E=cN.getStats(),ae=lN.getStats();return Q(`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=${ee?`Y`:`N`} upd=${te.length} warn=${d.lastWarning?`Y`:`N`}`),LN({ok:!0,output:ie+`
189
+ `})}catch(e){throw oN.requestsErrored++,e}}if(e.kind===`click`)return LN(await GN(e.verb,e.value));if(e.kind===`debug`){if(!UM(e.what))return LN({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${HM.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=_N.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?UN(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):HN};return LN({ok:!0,debug:MM(e.what,n)})}return LN({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function zN(e){let{values:t,tokens:n}=re({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:RS(t.config),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}const BN={sessionState:uN,dlog:Q,applyUpdate:()=>xN.act(),doctor:jj(),history:dN,configFor:e=>_N.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>_N.reload(e.projectDir,e.cwd,e.configFile??void 0)},VN={style:`powerline`,colorCompatibility:Ba,wrap:!0,padding:1,charset:Ia,width:1/0},HN=new Map;function UN(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,RT(a,{...VN,charset:t,colorCompatibility:n}));return r}const WN={gitProvider:cN,usageStore:lN,contextProvider:pN,metricsProvider:mN,activityProvider:hN,tmuxService:gN,log:Q,clock:()=>new Date,history:e=>dN.depth(e)};function GN(e,t){let n=EM.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,BN),{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 KN={connectMs:200,budgetMs:500};async function qN(e){let n=e.includes(`--json`),r=await JN();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${$S(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
190
+ `);return}t.stdout.write(QN(r.value))}function JN(){return qS({kind:`stats`},KN,e=>`stats`in e?e.stats:void 0)}function YN(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function XN(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function ZN(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 QN(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 ${ZN(e.uptimeSec)}`),t.push(` rss ${YN(e.rssBytes)}`),t.push(` heapUsed ${YN(e.heapUsedBytes)}`),t.push(` heapTotal ${YN(e.heapTotalBytes)}`),t.push(` external ${YN(e.externalBytes)}`),t.push(` arrayBuffers ${YN(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 ${XN(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 ${XN(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(`
191
191
  `)+`
192
- `}const XN={connectMs:200,budgetMs:500};async function ZN(e,n){let r=n.includes(`--json`),i=await QN(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${QS(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
193
- `);return}t.stdout.write($N(i.value))}function QN(e){return KS({kind:`debug`,what:e},XN,e=>`debug`in e?e.debug:void 0)}function $N(e){switch(e.what){case`vars`:return eP(e.vars);case`segments`:return tP(e.segments);case`config`:return nP(e.config);default:return e}}function eP(e){if(e.length===0)return`no variables (DSL not active)
194
- `;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?``:` ${iP(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${rP(a.value)}${e}${o}`)}return t.join(`
192
+ `}const $N={connectMs:200,budgetMs:500};async function eP(e,n){let r=n.includes(`--json`),i=await tP(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${$S(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
193
+ `);return}t.stdout.write(nP(i.value))}function tP(e){return qS({kind:`debug`,what:e},$N,e=>`debug`in e?e.debug:void 0)}function nP(e){switch(e.what){case`vars`:return rP(e.vars);case`segments`:return iP(e.segments);case`config`:return aP(e.config);default:return e}}function rP(e){if(e.length===0)return`no variables (DSL not active)
194
+ `;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?``:` ${sP(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${oP(a.value)}${e}${o}`)}return t.join(`
195
195
  `)+`
196
- `}function tP(e){if(e.length===0)return`no segments (DSL not active)
196
+ `}function iP(e){if(e.length===0)return`no segments (DSL not active)
197
197
  `;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(`, `)}`),n.lastRender!==null&&t.push(` last ${n.lastRender}`);return t.join(`
198
198
  `)+`
199
- `}function nP(e){return e===null?`config: DSL not active
199
+ `}function aP(e){return e===null?`config: DSL not active
200
200
  `:JSON.stringify(e,null,2)+`
201
- `}function rP(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function iP(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function aP(){let e=sP();return e===null?null:r.readFileSync(e,`utf-8`)}function oP(){let e;try{e=aP()}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 sP(){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 cP(e){let t=e.CC_CANDYBAR_CONFIG??``;return t===``?void 0:t}const lP=5e3;function uP(e){let t=`/home/tester`,n=Math.floor(Date.now()/1e3);return{hook_event_name:`Status`,session_id:`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,version:`1.15.0`,home:t,cwd:`${t}/code/cc-candybar/src`,transcript_path:`${t}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:{current_dir:`${t}/code/cc-candybar/src`,project_dir:`${t}/code/cc-candybar`},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:n+2*3600},weekly:{percentage:21,resetsAt:n+5*86400},cache:{expiresAt:n+900},tmux:{session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},...tO(e),history:{undo:1,redo:1},unsaved:1}}function dP(e,t){let n=xS(e,e),r=CS(n);return r!==null&&t.push(r),n.kind===`file`?n.path:null}async function fP(e,n=t.cwd()){let i=[],a=e===void 0?dP(n,i):c.resolve(vS(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=TS(n,n);o!==null&&i.push(o);try{return{kind:`clean`,configPath:a,warnings:i,rendered:await hP(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 Wo&&i.push(...e.warnings),{kind:`fatal`,configPath:a,message:e instanceof Wo||e instanceof Error?e.message:String(e),warnings:i})}}async function pP(e,t,n){let r=ES(e,YD);n.push(...r.warnings);let i=kS(r,e??`<default>`),a=new oA,o=new Iv(a,i.globals.default_empty_value??``,void 0,new _A);try{let e=Jk(i,o,{cwd:t});n.push(...e.loadWarnings);let r=await o.settled(lP);return r.length>0&&n.push(`source${r.length===1?``:`s`} still running after ${lP} ms, rendered with fallback values: ${r.join(`, `)}`),{config:i,compiled:e,store:a,registry:o}}catch(e){throw o.dispose(),e}}function mP({config:e,compiled:t,store:n,registry:r},i,a){let o=new Map;return{rendered:Qk(e,t,n,r,uP(i),$D(i,a),{onSegmentError:(e,t)=>o.set(`segment "${e}"`,t),onRenderWarning:e=>o.set(`globals.palette`,e)},eO(i)),failures:o}}async function hP(e,t,n){let r=await pP(e,t,n),{config:i}=r;try{VE(i);let e=QD(i,()=>null,()=>!1),t=e=>mP(r,e,200),n=t(e),a=t({...e,presetCustomized:!0}),o=[...[...n.failures].map(([e,t])=>`${e}: ${t}`),...[...a.failures].filter(([e])=>!n.failures.has(e)).map(([e,t])=>`${e}: ${t} (under .preset.customized = true)`)];if(o.length>0)throw Error(`config renders with ${o.length} render error${o.length===1?``:`s`} (the daemon would show them on the bar):\n`+o.map(e=>` ${e}`).join(`
202
- `));return n.rendered}finally{r.registry.dispose()}}function gP(e){return e.map(e=>`warning: ${e}\n`).join(``)}function _P(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:gP(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:gP(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 vP=`--render`,yP=`Usage: cc-candybar check [${vP}] [config-file]\n`;function bP(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==vP);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${yP}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${yP}`}:{kind:`run`,target:n[0],render:t.includes(vP)}}async function xP(e){let n=bP(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:_P(await fP(n.target??cP(t.env)),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const SP=`${ET}${TT}`;function CP(e){return`${SP}⚠ cc-candybar: ${wP(e)}\n`}function wP(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: ${wT(e.message,60)}`;case`render_failed`:return`render failed: ${wT(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${wT(e.message,60)}`}}function TP(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
203
- `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:CP(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function EP(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 DP=` (fix: click the settings menu (${$s} by default) › 🧰 tools ▸ 🩺 doctor, then [fix] on the bar)`;function OP({check:e,verdict:t}){return t.ok?`✓ ${e.label}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:DP}\n`}function kP(e,t){let n;try{n=Fj(e,Iy(t))}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let r=zy(n);return{stdout:r.map(OP).join(``),stderr:``,code:+!r.every(e=>e.verdict.ok)}}function AP(e){e.length>0&&(t.stderr.write(`doctor: takes no arguments
201
+ `}function oP(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function sP(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function cP(){let e=uP();return e===null?null:r.readFileSync(e,`utf-8`)}function lP(){let e;try{e=cP()}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 uP(){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 dP(e){let t=e.CC_CANDYBAR_CONFIG??``;return t===``?void 0:t}const fP=5e3;function pP(e){let t=`/home/tester`,n=Math.floor(Date.now()/1e3);return{hook_event_name:`Status`,session_id:`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,version:`1.15.0`,home:t,cwd:`${t}/code/cc-candybar/src`,transcript_path:`${t}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:{current_dir:`${t}/code/cc-candybar/src`,project_dir:`${t}/code/cc-candybar`},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:n+2*3600},weekly:{percentage:21,resetsAt:n+5*86400},cache:{expiresAt:n+900},tmux:{session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},...JE(e),history:{undo:1,redo:1},unsaved:1}}function mP(e,t){let n=SS(e,e),r=wS(n);return r!==null&&t.push(r),n.kind===`file`?n.path:null}async function hP(e,n=t.cwd()){let i=[],a=e===void 0?mP(n,i):c.resolve(yS(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=ES(n,n);o!==null&&i.push(o);try{return{kind:`clean`,configPath:a,warnings:i,rendered:await vP(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 Wo&&i.push(...e.warnings),{kind:`fatal`,configPath:a,message:e instanceof Wo||e instanceof Error?e.message:String(e),warnings:i})}}async function gP(e,t,n){let r=DS(e,kE);n.push(...r.warnings);let i=AS(r,e??`<default>`),a=new gA,o=new Iv(a,i.globals.default_empty_value??``,void 0,new DA);try{let e=iA(i,o,{cwd:t});n.push(...e.loadWarnings);let r=await o.settled(fP);return r.length>0&&n.push(`source${r.length===1?``:`s`} still running after ${fP} ms, rendered with fallback values: ${r.join(`, `)}`),{config:i,compiled:e,store:a,registry:o}}catch(e){throw o.dispose(),e}}function _P({config:e,compiled:t,store:n,registry:r},i,a){let o=new Map;return{rendered:cA(e,t,n,r,pP(i),KE(i,a),{onSegmentError:(e,t)=>o.set(`segment "${e}"`,t),onRenderWarning:e=>o.set(`globals.palette`,e)},qE(i)),failures:o}}async function vP(e,t,n){let r=await gP(e,t,n),{config:i}=r;try{BD(i);let e=GE(i,()=>null,()=>!1),t=e=>_P(r,e,200),n=t(e),a=t({...e,presetCustomized:!0}),o=[...[...n.failures].map(([e,t])=>`${e}: ${t}`),...[...a.failures].filter(([e])=>!n.failures.has(e)).map(([e,t])=>`${e}: ${t} (under .preset.customized = true)`)];if(o.length>0)throw Error(`config renders with ${o.length} render error${o.length===1?``:`s`} (the daemon would show them on the bar):\n`+o.map(e=>` ${e}`).join(`
202
+ `));return n.rendered}finally{r.registry.dispose()}}function yP(e){return e.map(e=>`warning: ${e}\n`).join(``)}function bP(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:yP(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:yP(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 xP=`--render`,SP=`Usage: cc-candybar check [${xP}] [config-file]\n`;function CP(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==xP);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${SP}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${SP}`}:{kind:`run`,target:n[0],render:t.includes(xP)}}async function wP(e){let n=CP(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:bP(await hP(n.target??dP(t.env)),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const TP=`${DT}${ET}`;function EP(e){return`${TP}⚠ cc-candybar: ${DP(e)}\n`}function DP(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: ${TT(e.message,60)}`;case`render_failed`:return`render failed: ${TT(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${TT(e.message,60)}`}}function OP(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
203
+ `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:EP(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function kP(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 AP=` (fix: click the settings menu (${$s} by default) › 🧰 tools ▸ 🩺 doctor, then [fix] on the bar)`;function jP({check:e,verdict:t}){return t.ok?`✓ ${e.label}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:AP}\n`}function MP(e,t){let n;try{n=Ij(e,Ly(t))}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let r=By(n);return{stdout:r.map(jP).join(``),stderr:``,code:+!r.every(e=>e.verdict.ok)}}function NP(e){e.length>0&&(t.stderr.write(`doctor: takes no arguments
204
204
  Usage: cc-candybar doctor
205
- `),t.exit(2));let n=kP(Aj(),t.env);t.stdout.write(n.stdout),t.stderr.write(n.stderr),t.exit(n.code)}function jP(){return EP(t.env.COLUMNS,t.stderr.columns)}function MP(){return EP(t.env.LINES,t.stderr.rows)}const NP=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`],PP=e=>e.some(e=>t.argv.includes(e));function FP(){return NP.some(e=>(t.env[e]??``)!==``)}function IP(){console.log(fy)}async function LP(){try{PP(uy.help)&&(IP(),t.exit(0)),PP(uy.version)&&(console.log(`cc-candybar ${vw}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await Zw(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(Kw(),t.exit(0)),e===`url-handle`){await Jw(t.argv[3]);return}if(e===`daemon`){SN();return}if(e===`daemon-stats`&&(await WN(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){await xP(t.argv.slice(3));return}if(e===`schema`){oP();return}if(e===`doctor`){AP(t.argv.slice(3));return}BM(e)&&(await ZN(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
205
+ `),t.exit(2));let n=MP(jj(),t.env);t.stdout.write(n.stdout),t.stderr.write(n.stderr),t.exit(n.code)}function PP(){return kP(t.env.COLUMNS,t.stderr.columns)}function FP(){return kP(t.env.LINES,t.stderr.rows)}const IP=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`],LP=e=>e.some(e=>t.argv.includes(e));function RP(){return IP.some(e=>(t.env[e]??``)!==``)}function zP(){console.log(py)}async function BP(){try{LP(dy.help)&&(zP(),t.exit(0)),LP(dy.version)&&(console.log(`cc-candybar ${yw}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await Qw(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(qw(),t.exit(0)),e===`url-handle`){await Yw(t.argv[3]);return}if(e===`daemon`){TN();return}if(e===`daemon-stats`&&(await qN(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){await wP(t.argv.slice(3));return}if(e===`schema`){lP();return}if(e===`doctor`){NP(t.argv.slice(3));return}UM(e)&&(await eP(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
206
206
 
207
207
  cc-candybar is designed to be used as a Claude Code statusLine command.
208
208
  It reads hook data from stdin and outputs formatted statusline.
@@ -218,4 +218,4 @@ Add to ~/.claude/settings.json:
218
218
  Run with --help for more options.
219
219
 
220
220
  To test output manually:
221
- 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)),D(`Working directory: ${t.cwd()}`),D(`Process args:`,t.argv);let r=await n(t.stdin);D(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),IP(),t.exit(1));let i=TP(await nC(r,t.argv,t.cwd(),{termCols:jP(),termRows:MP(),ssh:FP(),tmux:Iy(t.env),configEnv:cP(t.env)}));i.debug!==null&&D(i.debug),i.kick&&TC(),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)}}LP();export{};
221
+ 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)),D(`Working directory: ${t.cwd()}`),D(`Process args:`,t.argv);let r=await n(t.stdin);D(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),zP(),t.exit(1));let i=OP(await rC(r,t.argv,t.cwd(),{termCols:PP(),termRows:FP(),ssh:RP(),tmux:Ly(t.env),configEnv:dP(t.env)}));i.debug!==null&&D(i.debug),i.kick&&EC(),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)}}BP();export{};