@promptctl/cc-candybar 1.119.0 → 1.119.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 +45 -45
  2. package/package.json +5 -5
package/dist/index.mjs CHANGED
@@ -160,26 +160,26 @@ Config tooling:
160
160
  running daemon; none spawn one.)
161
161
 
162
162
  `,DS=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`,OS={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function kS(e){let t=e[OS.socket]??``,n=e[OS.pane]??``;if(t===``||n===``)return null;let r=e[OS.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}function AS(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const jS=OS.truecolor,MS={name:`tmuxTruecolor`,label:`tmux truecolor`,probe:({tmux:e,claudeSettings:t})=>{switch(e.kind){case`unreported`:return{ok:!1,reason:"the client reported no tmux facts — re-run `cc-candybar install` to stage a current client"};case`outside`:return{ok:!0};case`inside`:{if(e.termfeatures.kind===`failed`)return{ok:!1,reason:`tmux could not be asked: ${e.termfeatures.reason}`};if(!e.termfeatures.value.includes(`RGB`)||e.hint.truecolor!==null)return{ok:!0};let n=t.env[jS];return typeof n==`string`&&n!==``?{ok:!1,reason:`${jS} is set in ${t.path} — restart Claude Code to apply`}:{ok:!1,reason:`Claude Code renders the bar in 256 colours inside tmux`,fix:{kind:`claude-settings-env`,name:jS,value:`1`}}}}}},NS={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},PS={name:`config`,label:`config`,probe:({config:e})=>{switch(e.kind){case`failed`:{let[t=`the config failed to load`,...n]=[...e.error.split(`
163
- `).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return AS([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${NS[e]}`)])}}},FS="re-run `cc-candybar install`";function IS(e){if(e.kind===`failed`)return[`Launch Services could not be asked which app opens cc-candybar:// — ${e.reason}`];if(e.value===null)return[`no app is registered for cc-candybar:// — ${FS}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${FS}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${FS}`)}const LS=[PS,{name:`urlHandler`,label:`URL handler`,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${FS}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${FS}`};case`lost`:return AS([...IS(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}},MS];function RS(e){return LS.map(t=>({check:t,verdict:t.probe(e)}))}function zS(e){return LS.find(t=>t.name===e)}const BS=`${ad}doctor.`;function VS(e){let t=`${BS}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`}}function HS(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function US(e){return e.flatMap(({check:e,verdict:t})=>{let n=VS(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:``},{key:n.fixable,value:rs}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:HS(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?rs:ns}]})}const WS={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function GS(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries(WS).map(([t,n])=>[`${e}${t}`,n]))}}const KS=`armed`,qS=`disarmed`,JS=`.armed`,YS=e=>e.endsWith(JS);function XS(e,t,n){let r=`${e}${JS}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${KS}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:KS},[a]:{set:r,to:qS},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:qS}},disarm:a}}const ZS=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function QS(e){return typeof e==`string`&&ZS.test(e)?{kind:`line`,line:e}:{kind:`refused`,reason:`a slash command is "/" then its name, e.g. "/compact" or "/model opus", on one line with no control characters, got ${JSON.stringify(e)}`}}function $S(e){let t=QS(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const eC=[`/compact`,`/model`],tC=`/clear`;function nC(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=XS(`${e}clear`,{arm:tC,confirm:`${tC} ✓ confirm`},[n]);return{template:eC.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${Dx} }}`,actions:{...Object.fromEntries(eC.map(e=>[t(e),{slash:$S(e)}])),...r.actions,[n]:{slash:$S(tC)}},variables:r.variables,disarm:r.disarm}}function rC(e,t){let n=(e.CLAUDE_CONFIG_DIR??``).split(`,`)[0].trim();return n===``?void 0:l.resolve(t,n)}function iC(e){return e??l.join(h.homedir(),`.claude`)}function aC(e){return l.join(e,`settings.json`)}function oC(e){return l.join(e,`plugins`,`installed_plugins.json`)}function sC(e){return r.existsSync(e)?r.readFileSync(e,`utf8`):``}function cC(e){let t;try{let n=sC(e);if(/^\s*$/.test(n))return{};t=Ds.parse(n)}catch(t){throw Error(`cannot read ${e}: ${lC(t)}`,{cause:t})}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`cannot read ${e}: not a JSON object`);return t}const lC=e=>e instanceof Error?e.message:String(e),uC=Array.from({length:10},(e,t)=>(t+1)*1e5),dC=uC[0],fC=uC[uC.length-1];function pC(e){let t;try{t=cC(e)}catch(e){return X(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?J(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=dC&&n<=fC?J(n):X(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${dC}–${fC} tokens)`)}function mC(e,t){let n=Math.min(t??fC,fC),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:uC.filter(e=>e<r).at(-1)??0,higher:uC.find(e=>e>r&&e<=n)??0}}function hC(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${Dx} }}{{ if gt .autocompact.lower 0 }} {{ action (printf "${e}%d" .autocompact.lower) "−" }}{{ end }}{{ if gt .autocompact.higher 0 }} {{ action (printf "${e}%d" .autocompact.higher) "+" }}{{ end }}{{ if gt .autocompact.window 0 }} {{ action "${e}auto" "↺" }}{{ end }}{{ end }}{{ end }}`,bg:`{{ if ne .autocompact.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .autocompact.window 0) (ne .autocompact.error "") }}`,actions:{[`${e}auto`]:{slash:$S(`/autocompact auto`)},...Object.fromEntries(uC.map(t=>[`${e}${t}`,{slash:$S(`/autocompact ${t}`)}]))}}}const gC=e=>`{{ if ge ${e} 1000000 }}{{ printf "%.1f" (divf ${e} 1000000) }}M{{ else if ge ${e} 1000 }}{{ printf "%.1f" (divf ${e} 1000) }}K{{ else }}{{ ${e} }}{{ end }}`,_C=`${ad}menu`,vC=`open`,yC=`${ad}edit`,bC=`${ad}toolbar`,xC=GS(ad),SC=`${ad}commands`,CC=nC(`${SC}.`),wC=`${ad}autocompact`,TC=hC(`${wC}.`,gC),EC=e=>({kind:`segment`,name:e}),DC=`${ad}tab`,OC=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],kC=e=>`${DC}.${e}`,AC=e=>`${kC(e)}.toggle`,jC=e=>({variable:DC,key:DC,member:e}),MC=`${ad}save`,NC=`${ad}preset.save`,PC=`${ad}preset.delete`,FC=`${ad}resetAll`,IC=`${_C}.toggle`,LC={variable:_C,key:_C,member:vC},RC=`${ad}undo`,zC=`${ad}back`,BC=`${zC}.step`,VC=`${ad}navigation.back`,HC=zC,UC={template:`{{ if gt .${VC} 0 }}{{ action "${zC}" "◁" }}{{ else }}{{ fg (${DS}) "◁" }}{{ end }}`},WC=`${ad}redo`,GC=`${ad}doctor`,KC=`${GC}.run`,qC=e=>`${GC}.fix.${e}`,JC=e=>`${GC}.${e}`,YC=rv(`${ad}pickers`),XC=[{template:`{{ themePreview }}`}],ZC={template:`{{ layoutPreview }}`},QC={preset:[ZC,{when:`{{ not .preset.bundled }}`,template:`{{ action "${PC}" (printf "🗑 delete %s" .${Ox.preset.effectiveVar}) }}`}],theme:XC,style:XC,variation:[ZC]},$C=e=>`${ad}${e}`,ew=e=>`${ad}apply.${e}`,tw=e=>`${ad}reset.${e}`,nw=e=>`${ad}list.${e}`,rw=(e,t)=>`${nw(e)}.${t}`,iw=e=>`${ad}resettable.${e}`,aw=e=>e.length===0?`false`:`(or ${e.map(e=>`.${iw(e)}`).join(` `)})`,ow=Object.keys(Ox).map(e=>{let t=Ox[e],n=Yl(t.configKey),r=sS({label:t.label,domain:n},t.sessionKey,t.effectiveVar,ew(e),YC);return{...t,name:e,control:r,beneath:QC[e]??[]}}),sw={preset:`door`,theme:`look`,style:`look`,variation:`look`,endcaps:`look`,autoWrap:`layout`,padding:`layout`,updateNotice:`config`},cw=e=>ow.filter(t=>sw[t.name]===e),lw=e=>cw(e).map(xw);new Set(ow.flatMap(e=>[e.sessionKey,e.configKey]));const uw=XS(FC,{arm:`⟲`,confirm:`⟲ reset all?`},ow.map(e=>tw(e.name))),dw=[`unsaved`,`history.undo`,`history.redo`],fw=e=>`${ad}${e}`,pw=fw(`unsaved`),mw=(e,t)=>({body:t,shown:`(gt .${fw(e)} 0)`}),hw=[mw(`unsaved`,`{{ action "${MC}" (printf "💾 save %d" .${pw}) }}`),mw(`history.undo`,`{{ action "${RC}" "↶" }}`),mw(`history.redo`,`{{ action "${WC}" "↷" }}`),{body:uw.template,shown:`(or ${aw(ow.map(e=>e.name))} ${uw.armed})`}],gw={when:`{{ or ${hw.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+hw.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},_w=[{step:uw,place:`door`},{step:CC,place:`session`}],vw=e=>e.map(e=>e.step.disarm),yw=vw(_w),bw=vw(_w.filter(e=>e.place!==`door`));function xw(e){let t=$C(e.name);return e.control.kind===`inline`?EC(t):Al(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[EC(nw(e.name)),...e.beneath.map((t,n)=>EC(rw(e.name,n)))]},`drop`)}function Sw(e){return e===_C}function Cw(e){let t=EC(_C);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[Cw(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 ww(e){return Tw(e)>0?e:Cw(e)}function Tw(e){let t=0;for(let n of pc(e))n.kind===`segment`&&Sw(n.name)&&(t+=1);return t}function Ew(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&Sw(e.name)||e.opens!==void 0&&Ew(e.opens.body,!0):e.children.some(e=>Ew(e,n))}const Dw={session:{direction:`vertical`,content:[EC(bC),{kind:`container`,direction:`horizontal`,children:[EC(SC),EC(wC)]}]},look:{direction:`horizontal`,content:[]},layout:{direction:`horizontal`,content:[EC(NC),EC(yC)]},config:{direction:`horizontal`,content:[]},tools:{direction:`vertical`,content:[EC(GC),...LS.map(e=>EC(JC(e.name)))]}},Ow=e=>({kind:`container`,direction:Dw[e].direction,children:[...Dw[e].content,...lw(e)]});function kw(e){return e.kind===`segment`?Sw(e.name)?Al(e.name,LC,jw,`above`):e:Nw(e)}function Aw(){return{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[EC(HC),...lw(`door`),EC(MC)]},{kind:`container`,direction:`horizontal`,children:OC.map(({member:e})=>Al(kC(e),jC(e),Ow(e),`drop`))}]}}const jw=Aw();function Mw(e){let t=new Map;for(let e of pc(jw))e.kind===`segment`&&e.opens!==void 0&&t.set(e.opens.ref.key,e.opens.ref.variable);return[...t].map(([t,n])=>{let r=e.variables[n];if(r?.kind!==`state`||r.default===void 0)throw Error(`settings menu: the door folds "${t}", but "${n}" is not a state variable the menu declares with a default`);let i=`${_C}.fold.${td(t)}`;return e.actions[i]={set:t,to:r.default},i})}function Nw(e){return{...e,children:e.children.map(e=>kw(e))}}function Pw(e){let t={variables:{[_C]:Il(_C,Tl)},actions:{[IC]:Ll(_C,vC),[KC]:{doctor:`run`},[yC]:{do:[...Pv]},...xC.actions,...CC.actions,...TC.actions,[MC]:{save:!0},[RC]:{undo:!0},[BC]:{back:!0},[zC]:{do:[BC,...yw]},[WC]:{redo:!0},[NC]:{preset:`save`},[PC]:{preset:`delete`,name:`{{ .${Ox.preset.effectiveVar} }}`}},segments:{[_C]:{template:`{{ $door := ${Pl(_C,Fl(e),Fl(`✖`))} }}{{ if ${Ml(LC)} }}{{ fg (color "error") $door }}{{ else }}{{ $door }}{{ end }}`},[bC]:{template:xC.template},[SC]:{template:CC.template,when:CC.when},[wC]:{template:TC.template,bg:TC.bg,when:TC.when},[HC]:UC,[MC]:gw,[NC]:{template:`{{ action "${NC}" "+ preset" }}`},[GC]:{template:`{{ action "${KC}" "🩺 doctor" }}`},[yC]:{template:`{{ action "${yC}" "✎ arrange" "✎ done" }}`}}};t.variables[VC]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of dw)t.variables[fw(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[DC]=Il(DC,`session`);for(let{member:e,label:n}of OC){t.actions[AC(e)]=Ll(DC,e),t.actions[kC(e)]={do:[AC(e),...bw]};let r=aw(cw(e).map(e=>e.name)),i=`(ternary ${Fl(` •`)} "" ${r})`,a=e=>`(print ${Fl(e)} ${i})`;t.segments[kC(e)]={template:`{{ ${Pl(kC(e),a(n),a(`▾ ${n}`))} }}`}}return Object.assign(t.variables,CC.variables,uw.variables),Iw(t),Fw(t),t.actions[_C]={do:[IC,...yw,...Mw(t)]},t}function Fw(e){for(let t of LS){let n=VS(t.name),r=qC(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[JC(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${ns}" }} {{ action "${r}" "[fix]" }}{{ end }}{{ end }}`}}}function Iw(e){for(let t of ow){Object.assign(e.actions,t.control.actions);let n=tw(t.name);e.actions[n]={reset:t.configKey},e.variables[iw(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${iw(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[$C(t.name)]={template:`${t.control.template}${r}`},t.control.kind===`picker`&&(e.segments[nw(t.name)]={template:t.control.list.template}),t.beneath.forEach((n,r)=>{e.segments[rw(t.name,r)]=n})}Object.assign(e.actions,uw.actions)}function Lw(e){let{variables:t,actions:n}=Uv();Object.assign(e.variables,t),Object.assign(e.actions,n)}function Rw(e){let t=Pw(e.globals.menuGlyph??`🍫`);Lw(t);let n={...e.presets},r=[];for(let t of fv(e.presets)){let{node:i}=hv(e,t),a=kw(ww(i));r.push(a),n[t]={...mv(e.presets,t),root:a}}let i=Lx(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const zw=`${id}live`,Bw=[`☐ live`,`☑ live`],Vw=`${id}done`,Hw=`${id}cancel`,Uw=`${id}rewind`,Ww=`${id}changes`,Gw=`(gt .${Ww} 0)`,Kw=`(or ${Gw} (gt .${pw} 0))`,qw={variable:zw,key:zw,member:`open`};function Jw(e){return`${id}configuring.p${e}`}function Yw(e){return`and ${Ml(Rv)} (not ${Ml(qw)}) (ne .${Jw(e)} "true")`}function Xw(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${jv} "${kl(e)}")`).join(` `)} false }}`}}function Zw(e,t,n){return`{{ if ${Yw(e)} }}${t}{{ else }}${n}{{ end }}`}const Qw=`{{ and ${Ml(Rv)} .preset.customized }}`,$w=sd;function eT(e){return new Map([...Qx(e),...nT(e)])}const tT=`${id}addable`;function nT(e){return new Map([[tT,{members:Object.keys(e.segments).filter(e=>!$w(e)),library:{groups:$u.map(e=>({id:e,label:ed[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function rT(e,t,n){return n.segments[e]={template:t,when:zv,bg:yS},{kind:`segment`,name:e}}function iT(e,t,n){let r=`${id}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${lo}`}) (action "${r}" "✖") }}`}function aT(e){return`{{ if ${Ml(Rv)} }}${e}{{ end }}`}function oT(e,t){return e.reduce((e,t)=>`{{ if and ${Ml(Rv)} ${Ml(t)} }}true{{ else }}${e}{{ end }}`,t)}function sT(e){return e.flatMap(e=>[...pc(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function cT(e,t,n){return`${Iv}${e}.${t}.${n}`}function lT(e,t,n,r){let i=lc(n),a=`${id}${e.presetIdent}`,o=Lv(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=rv(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:Tl},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:jv,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=cT(e.presetIdent,i,r),l=`${Iv}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Dc(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=sS(aS(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};let p=`${d}.list`;return e.artifacts.segments[d]={template:f.template},e.artifacts.segments[p]={template:f.list.template},Al(d,f.list.ref,{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:p}]},`drop`)});return{term:`{{ action "${s}" "⚙️" }}`,ref:{variable:jv,key:jv,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const uT=`${id}label:`;function dT(e){if(e.startsWith(uT)){let t=e.slice(uT.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function fT(e,t,n,r){let{artifacts:i}=n,a=lc(e),o=`${uT}${a}:${e.name}`;i.segments[o]={template:`{{ "${kl(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=e.settings?.[Sc];return{...Al(o,r.ref,r.body,`drop`,oT([r.ref],`{{ ${Yw(n.presetIdent)} }}`)),...s!==void 0&&{settings:{theme:s}},drafts:{[Sc]:r.drafts[Sc]}}}function pT(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${id}${i}.insert.${t}`,s=`${id}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:tT,anchor:n,relation:r};let c=tv(o),l=nv(s,o,void 0),u=av(l),d=iv(l,c);return a.variables[l]=Il(l,Tl),a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=Ll(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${Ml({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${lo}`}) $m }}{{ end }}`}}function mT(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!$w(e.name)),i=e=>mT(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=fc(o,i);if($w(o.name)){n.push(s);continue}let c=lc(o),l=a===r?[pT(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=pT(t,u,c,`after`),f=iT(t,u,c),p=t.segments[o.name],m=lT(t,u,o,Cc(p)),h=aT(f),g=aT(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>rT(e.host,e.template,t.artifacts)),{...fT(o,p,t,m),lead:h,trail:g},{...s,when:Zw(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},rT(d.host,d.template,t.artifacts)]};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[_]}:_)}return{...e,children:n,...e.when!==void 0&&{when:oT(sT(n),Zw(t.presetIdent,`true`,e.when))}}}function hT(e,t,n,r,i,a,o){let s=`${id}${t}.resetLayout`,c=`${id}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:Qw},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},gT(e,o)]}}function gT(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),gT(n,t)]}:{...e,children:[...e.children,t]}}function _T(e,t,n,r,i,a){let{node:o}=hv(e,t),s={presetIdent:td(t),rootKey:fS(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=mT(o,s);return n.variables[Jw(s.presetIdent)]=Xw(s.configured),hT(c,s.presetIdent,s.rootKey,n,r,i,a)}function vT(e){let t={variables:{},actions:{},segments:{}},n=_S(`${id}help`,TS,[Rv],t);t.variables[zw]=Il(zw,Tl),t.actions[zw]=Ll(zw,qw.member),t.segments[zw]={template:Nl(zw,...Bw),when:zv};let r={kind:`segment`,name:zw},i=n;t.variables[Ww]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[Vw]={do:[MC,...Pv]},t.segments[Vw]={template:`{{ if ${Kw} }}{{ action "${Vw}" "✓ save" }}{{ else }}{{ action "${Vw}" "✓ done" }}{{ end }}`,when:zv},t.actions[Uw]={rewind:!0},t.actions[Hw]={do:[Uw,...Pv]},t.segments[Hw]={template:`{{ action "${Hw}" "↩ cancel" }}`,when:`{{ and ${Ml(Rv)} ${Gw} }}`};let a=[{kind:`segment`,name:Vw},{kind:`segment`,name:Hw}],o={...e.presets},s=[];for(let n of fv(e.presets)){let c=_T(e,n,t,a,r,i);s.push(c),o[n]={...mv(e.presets,n),root:c}}let c=Lx(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}const yT=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`doctor`,`ceiling`,`slash`,`do`];function bT(e){return e.ceiling===`set`?[`set`,e.to]:[`clear`]}function xT(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function ST(e,t){if(t===void 0)return{};if(!Lc(t))return Q(e,`actions`,`actions must be an object, got ${Rc(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=CT(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Q(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function CT(e,t,n){if(!Lc(n))return Q(e,t,`${t} must be an action object, got ${Rc(n)}`),null;if(`persistWhen`in n)return Q(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let r=yT.filter(e=>e in n);return r.length===1?wT[r[0]](e,t,n):(Q(e,t,`action must declare exactly one of: ${yT.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const wT={set:(e,t,n)=>nE(e,t,n,`set`,QT),persist:(e,t,n)=>nE(e,t,n,`persist`,$T),copy:TT(`copy`),open:TT(`open`),reset:ET,undo:OT(`undo`),redo:OT(`redo`),back:OT(`back`),rewind:OT(`rewind`),save:OT(`save`),preset:kT,doctor:AT,ceiling:jT,slash:MT,do:NT};function TT(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Mc(t,n,r,e);return i===null?null:{[e]:i}}}function ET(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=PT(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 DT={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,back:`it steps the session's navigation history`,rewind:`it steps the session's settings history back to where edit mode opened`,save:`it saves the session's unsaved settings`};function OT(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Q(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${DT[e]}), got ${K(r[e])}`),null)}}function kT(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Q(e,`${t}.preset`,`preset must be "save" or "delete", got ${K(r)}`),null;if(r===`save`)return{preset:`save`};let a=Mc(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function AT(e,t,n){let r=n.doctor,i=r===`run`?[`doctor`]:[`doctor`,`check`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${i.join(`, `)}`);if(r!==`run`&&r!==`fix`)return Q(e,`${t}.doctor`,`doctor must be "run" or "fix", got ${K(r)}`),null;if(r===`run`)return{doctor:`run`};let a=n.check;return typeof a!=`string`||zS(a)===void 0?(Q(e,`${t}.check`,`doctor fix must name a check (have: ${LS.map(e=>e.name).join(`, `)}), got ${K(a)}`),null):{doctor:`fix`,check:a}}function jT(e,t,n){let r=n.ceiling,i=r===`clear`?[`ceiling`]:[`ceiling`,`to`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a ceiling action. Expected only: ${i.join(`, `)}`);if(r===`clear`)return{ceiling:`clear`};if(r!==`set`)return Q(e,`${t}.ceiling`,`ceiling must be "set" or "clear", got ${K(r)}`),null;let a=n.to;return typeof a!=`string`||a.trim()===``?(Q(e,`${t}.to`,`ceiling set needs \`to\`: a memento ceiling value such as "+100_000", "400000" or "off", got ${K(a)}`),null):{ceiling:`set`,to:a}}function MT(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=QS(n.slash);return r.kind===`refused`?(Q(e,`${t}.slash`,r.reason),null):{slash:r.line}}function NT(e,t,n){for(let r of Object.keys(n))r!==`do`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Q(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${K(r)}`),null):{do:r}}function PT(e,t,n,r,i,a){let o=Mc(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Q(e,s,i),null):o.includes(`/`)?(Q(e,s,a(o)),null):o}const FT={set:`the SessionState key to write`,persist:`the config globals field to write`};function IT(e,t,n,r){let i=FT[r],a=PT(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 LT(e){return e===`set`?`set-state`:`set-config`}const RT={to:rE(`set`)},zT={to:rE(`persist`)},BT={from:iE(`set`)},VT={from:iE(`persist`)},HT={min:lE(),max:lE(),by:lE()},UT={int:oE()},WT={cycle:aE(`set`)},GT={cycle:aE(`persist`)},KT={removeSegment:sE(`removeSegment`)},qT={insertSegment:sE(`insertSegment`),anchor:sE(`anchor`),relation:cE()},JT={insertSegmentFrom:iE(`persist`),anchor:sE(`anchor`),relation:cE()},YT={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},XT={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function ZT(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>Vc(e,t,n,r),c=al(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?Yc(s,...n):s}}const QT=[ZT(`set`,RT),ZT(`set`,BT),ZT(`set`,HT,[YT,XT]),ZT(`set`,UT),ZT(`set`,WT)],$T=[ZT(`persist`,zT),ZT(`persist`,VT),ZT(`persist`,HT,[YT,XT]),ZT(`persist`,GT),ZT(`persist`,KT),ZT(`persist`,qT,[],[`insertSegment`]),ZT(`persist`,JT,[],[`insertSegmentFrom`])];function eE(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"endcaps"/"styles", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function tE(e){let t=eE(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 nE(e,t,n,r,i){let a=IT(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Q(e,t,`${tE(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Q(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function rE(e){let t=LT(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>PT(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 iE(e){let t=LT(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Q(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Q(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Q(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Q(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Q(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Q(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${K(o)}`)}}}function aE(e){let t=LT(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Q(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${Rc(o)}`);return}let c=o;if(c.length<2){Q(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Q(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Q(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Q(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function oE(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Q(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${K(r[n])}`);return}return!0}}}function sE(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Mc(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Q(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Q(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function cE(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Q(e,`${t}.${n}`,`relation must be "before" or "after", got ${K(i)}`);return}return i}}}function lE(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Q(e,`${t}.${n}`,`${n} must be an integer, got ${K(i)}`);return}return i}}}function uE(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const dE={noun:`style key`,fields:{hueShift:$c(),chromaScale:$c({min:0}),lightnessScale:$c(),lightnessShift:$c()}};function fE(e,t){if(!Lc(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${Rc(t)}`,line:G(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:G(e.source,[`styles`,r])});continue}if(qo(r)){e.issues.push({path:`styles.${r}`,message:uE(`styles.${r}`,r,`globals.endcaps`),line:G(e.source,[`styles`,r])});continue}let t=zc(e,dE,`styles.${r}`,i);t!==null&&(n[r]={...cr,...t})}return n}const pE={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:Yd(e,`${t}.${n}`,r[n])},globals:{required:!1,json:cu(),parse:(e,t,n,r)=>r[n]===void 0?void 0:su(e,`${t}.${n}`,r[n])}}};function mE(e,t){if(!Lc(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${Rc(t)}`,line:G(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:G(e.source,[`presets`,r])});continue}let t=zc(e,pE,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function hE(e,t){if(t===void 0)return{};if(!Lc(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${Rc(t)}`,line:G(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${K(i)}`,line:G(e.source,[`helpers`,r])});continue}n[r]=i}return n}const gE=new Map([[`session.budget.amount`,{segment:`session`,setting:`budget`}],[`session.budget.warningThreshold`,{segment:`session`,setting:`warnAt`}],[`today.budget.amount`,{segment:`today`,setting:`budget`}],[`today.budget.warningThreshold`,{segment:`today`,setting:`warnAt`}],[`block.budget.heatThreshold`,{segment:`block`,setting:`warnAt`}],[`block.budget.warningThreshold`,{segment:`block`,setting:`errorAt`}],[`weekly.budget.heatThreshold`,{segment:`weekly`,setting:`warnAt`}],[`weekly.budget.warningThreshold`,{segment:`weekly`,setting:`errorAt`}],[`burn.eta.errorMinutes`,{segment:`burnrate`,setting:`errorWithin`}],[`burn.eta.warnMinutes`,{segment:`burnrate`,setting:`warnWithin`}]]);function _E(e){return`it became the "${e.setting}" setting of each "${e.segment}" placement — set it on the placement where a row places "${e.segment}" ({ seg: "${e.segment}", settings: { ${e.setting}: <value> } }), or redeclare segments.${e.segment}.settings.${e.setting} with the default every placement should start from`}function vE(e){let t=gE.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${_E(t)}`}function yE(e){let t=gE.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${_E(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}function bE(e,t){let n=new Map;for(let e of Object.keys(t)){let t=td(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:G(e.source,[`presets`])})}function xE(e,t,n){let r=[[[`globals`],t.globals.style],[[`editGlobals`],t.editGlobals.style],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style])];for(let[n,i]of r){if(i===void 0||zo(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:qo(i)?uE(r,i,`${n.join(`.`)}.endcaps`):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:G(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:G(e.source,[`globals`,`preset`])}),bE(e,t.presets);let i=eT(t),a=$x(i);for(let[n,r]of Object.entries(t.actions)){let[t,o]=`from`in r?[`from`,r.from]:`insertSegmentFrom`in r?[`insertSegmentFrom`,r.insertSegmentFrom]:[null,null];if(t!==null&&typeof o==`string`&&!a.includes(o)){e.issues.push({path:`actions.${n}.${t}`,message:`actions.${n} ${t}: references ${nS(o,i)}`,line:G(e.source,[`actions`,n,t])});continue}if(!(`set`in r))continue;jx.has(r.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${r.set}", which has no session pick — globals.${r.set} is set in the config file only, so a click would change nothing; write it with { persist: "${r.set}", … } instead`,line:G(e.source,[`actions`,n,`set`])});let s=Fx.get(r.set);s!==void 0&&RE(e,n,r,s,i)}for(let[n,r]of Object.entries(t.actions))`do`in r&&r.do.forEach((i,a)=>{let o=Object.prototype.hasOwnProperty.call(t.actions,i)?t.actions[i]:void 0,s=o===void 0?`references unknown action "${i}"`:`do`in o?`"${i}" is itself a do action — list its members here instead`:r.do.indexOf(i)===a?a>0&&xT(o)?`"${i}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${i}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:G(e.source,[`actions`,n,`do`])})});for(let[n,r]of Object.entries(t.actions)){let i=`persist`in r?r.persist:`reset`in r?r.reset:null;if(i===null)continue;let a=`persist`in r?`persist`:`reset`,o=mS(i);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a config globals field (have: ${fu().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, or a "presets.<name>.root" target`,line:G(e.source,[`actions`,n,a])});continue}let s=SE.filter(e=>e in r);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){CE(e,t,n,a,i,o.preset,r);continue}if(o.scope===`preset-globals`&&!fv(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: ${fv(t.presets).join(`, `)})`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${dd(o.segment)}`,line:G(e.source,[`actions`,n,a])});continue}`min`in r&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:G(e.source,[`actions`,n,a])})}}let o=uy(t);for(let t of o.names)t!==`settings`&&!t.startsWith(wE)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:G(e.source,[`variables`,t])});let s=(t,n,r)=>{Tw(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${_C}" ${Tw(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}),Ew(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${_C}" under a \`when\` or inside a disclosure body — the menu is visible under every condition, so its placement may not be gated. Move it to an ungated position, or remove it to put the menu at its default position.`,line:r}),c(t)&&e.issues.push({path:n,message:`${n} sets "distribution" on a container inside a bar cell — everything inside a cell wears that cell's hue and tone, so it would place nothing. Set it on the row whose children are the cells (the horizontal container) or on the root, which places the rows.`,line:r});let i=new Map;for(let e of pc(t)){if(e.kind!==`segment`)continue;let t=lc(e);i.set(t,[...i.get(t)??[],e])}for(let[t,a]of i){if(a.length<2)continue;let o=a[1].name,s=dc(o,new Set(i.keys()));e.issues.push({path:n,message:`${n} has ${a.length} placements with the id "${t}" — an id names one placement (its settings, its menus' open state, and edit mode all address it), so give each its own: { seg: "${o}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:r})}};function c(e,t=!1){return e.kind===`segment`?!1:t&&e.distribution!==void 0||e.children.some(n=>c(n,t||cc[e.direction]===`cell`))}let l=(n,r)=>{for(let[i,a]of vl(n,r)){let n=G(e.source,a.split(`.`));if(i.when!==void 0&&(IE(e,`${a}.when`,i.when,o,{line:n}),FE(e,`${a}.when`,i.when,n)),i.kind===`segment`){if(Sw(i.name)){(i.id!==void 0||i.settings!==void 0)&&e.issues.push({path:a,message:`${r} gives the global settings menu anchor "${_C}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${_C}"`,line:n});continue}Object.prototype.hasOwnProperty.call(t.segments,i.name)||e.issues.push({path:a,message:`${r} entry "${i.name}" does not match any declared segment${dd(i.name)}`,line:n}),ME(e,t,i,a,n)}}};n.root!==void 0&&l(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&l(t.root,`presets.${e}.root`);let u=new Map([[`root`,gl(t.root)]]);for(let e of fv(t.presets)){let{node:n,path:r}=hv(t,e);u.set(r,n)}for(let[t,n]of u)s(n,t,G(e.source,t.split(`.`)));for(let[n,r]of Object.entries(t.variables)){NE(e,`variables.${n}`,r,o);let t=vE(n);t!==void 0&&e.issues.push({path:`variables.${n}`,message:t,line:G(e.source,[`variables`,n])})}for(let[n,r]of Object.entries(t.segments)){if(r.vars)for(let[t,i]of Object.entries(r.vars))NE(e,`segments.${n}.vars.${t}`,i,o,n);let i=Cc(r);EE(e,n,i);let a=TE(o,i);for(let o of[`template`,`bg`,`fg`,`when`]){let s=r[o];if(typeof s==`string`){IE(e,`segments.${n}.${o}`,s,a,{segCtx:n,settings:i});for(let{name:r,site:i,via:a}of oy(s,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,r))continue;let s=i===`options`?` (in a picker, menu or carousel)`:``;if(a!==null){LE(e,a,`Template references unknown action "${r}"${s}`);continue}e.issues.push({path:`segments.${n}.${o}`,message:`${o} references unknown action "${r}"${s}`,line:G(e.source,[`segments`,n,o])})}}}}for(let[n,r]of Object.entries(t.variables))PE(e,`variables.${n}`,r,o);for(let[n,r]of Object.entries(t.segments))if(r.vars)for(let[t,i]of Object.entries(r.vars))PE(e,`segments.${n}.vars.${t}`,i,o,n)}const SE=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function CE(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=G(e.source,[`actions`,n,r]);if(!fv(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${fv(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(`, `)})${dd(i)}`,line:c})},p=new Set(uc(hv(t,a).node)),m=(r,i)=>{!ud.has(i)||p.has(i)||Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" names no placement${dd(i)}`,line:c})};`removeSegment`in o&&m(`removeSegment`,o.removeSegment),`insertSegment`in o&&f(`insertSegment`,o.insertSegment),(`insertSegment`in o||`insertSegmentFrom`in o)&&m(`anchor`,o.anchor)}const wE=`settings.`;function TE(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>wE+e)])}}function EE(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:G(e.source,[`segments`,t,`settings`,n])})},a=kE(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of Tc(n,OE(n)))i(e,`the defaults do not stand together: ${t}`)}function DE(e){return kE(e).length>0||Tc(e,OE(e)).length>0}function OE(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function kE(e){let t=t=>wc(AE(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||wc(AE(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${jE(e,n).join(`, `)||`none`})`}];let i=[n];for(let e=r;e!==void 0;e=t(e)){if(e===n)return i.every(e=>n<=e)?[{setting:n,message:`atLeast closes a cycle (${[...i,n].join(` ≥ `)}) — every setting on it could only ever equal the rest`}]:[];if(i.includes(e))return[];i.push(e)}return[]})}function AE(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function jE(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&wc(n)!==void 0).map(([e])=>e)}function ME(e,t,n,r,i){let a=Object.prototype.hasOwnProperty.call(t.segments,n.name)?t.segments[n.name]:void 0;if(a===void 0)return;let o=Cc(a),s=`${r}: placement "${lc(n)}" of segment "${n.name}"`;for(let[t,a]of Object.entries(n.settings??{})){let c=Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0,l=c===void 0?`sets "${t}", which segment "${n.name}" does not declare (it has: ${Object.keys(o).join(`, `)})`:Ec(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Ao(a):``}, but it must be ${kc(c)}`;l!==void 0&&e.issues.push({path:r,message:`${s} ${l}`,line:i})}let c=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,n.settings?.[e]??t.default]));if(!(!Object.entries(c).every(([e,t])=>Ec(o[e],t))||DE(o)))for(let{message:t}of Tc(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function NE(e,t,n,r,i){n.kind===`template`&&IE(e,`${t}.template`,n.template,r,{segCtx:i}),bc(n)&&n.cache&&`key`in n.cache&&IE(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function PE(e,t,n,r,i){if(bc(n)&&n.cache&&`depends_on`in n.cache)for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:G(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function FE(e,t,n,r){try{kv.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function IE(e,t,n,r,i){for(let[a,o]of ny(n,r.helpers)){if(ly(a,r))continue;if(a.startsWith(wE)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??G(e.source,t.split(`.`))});continue}if(o!==null){LE(e,o,`Template references unknown variable ".${a}"${yE(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&ly(n,r)?` (segment-local vars are namespaced — write ".${n}")`:yE(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??G(e.source,t.split(`.`))})}}function LE(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:G(e.source,[`helpers`,t])})}function RE(e,t,n,r,i){let a=n.set,o=Yl(Ox[r].configKey),s=`${a} takes ${iS(o,i)}`;if(`min`in n&&(o===`bool`||`from`in o)){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:G(e.source,[`actions`,t,`min`])});return}let c=VE(n,i);if(c===BE){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:G(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!rS(o,e.value,i));if(l.length!==0){if(a===Ox.style.sessionKey&&c.every(e=>qo(e.value))){let r=Ox.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:uE(`actions.${t}.to`,n.to,`set: "${r}", to`),line:G(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:G(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=zE?r.join(`, `):`${r.slice(0,zE).join(`, `)} and ${r.length-zE} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:G(e.source,[`actions`,t,n])})}}}const zE=3,BE=Symbol(`any integer`);function VE(e,t){return`to`in e?[{field:`to`,value:e.to}]:`cycle`in e?e.cycle.map(e=>({field:`cycle`,value:e})):`from`in e?eS(e.from,t).members.map(e=>({field:`from`,value:e})):`min`in e?[{field:`min`,value:String(e.min)},{field:`max`,value:String(e.max)}]:BE}function HE(e,t){let{graph:n,nodeInfo:r}=UE(t),i=new Map,a=[];for(let e of n.keys())i.set(e,0);for(let e of n.keys())if(i.get(e)===0&&o(e))return;function o(t){i.set(t,1),a.push(t);for(let s of n.get(t)??[]){let t=i.get(s);if(t===1){let t=a.indexOf(s),n=[...a.slice(t),s],i=n[0],o=r.get(i);return e.issues.push({path:o?.declarationPath??`variables.${i}`,message:`Dependency cycle: ${n.join(` → `)}`,line:G(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function UE(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 ny(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),bc(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 WE=[`json5`,`json`];function GE(e){try{return r.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function KE(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?h.homedir()+e.slice(1):e}function qE(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?WE.map(t=>l.join(e,`.cc-candybar.${t}`)):[],...WE.map(e=>l.join(r,`.cc-candybar.${e}`)),...WE.map(e=>`${JE()}.${e}`)])]}function JE(){let e=process.env.XDG_CONFIG_HOME??l.join(h.homedir(),`.config`);return l.join(e,`cc-candybar`,`config`)}function YE(e,t,n){let i=[],a=new Map;for(let o of qE(e,t,n)){let e=GE(o);if(e===`absent`)continue;if(e!==`present`){i.push(e);continue}let t=l.join(r.realpathSync(l.dirname(o)),l.basename(o).replace(/\.(json5|json)$/,``));a.has(t)||a.set(t,o)}let o=[...a.values()].reverse();if(n===void 0)return{kind:`chain`,layers:o,home:XE(o),unchecked:i};let[s]=i,c=n;return o.length>0?{kind:`chain`,layers:o,home:c,unchecked:i}:s===void 0?{kind:`missing`,path:n,home:c}:{kind:`unreadable`,...s,home:c}}function XE(e){let t=JE();return e.find(e=>WE.some(n=>e===`${t}.${n}`))??`${t}.${WE[0]}`}function ZE(e,t,n){let r=YE(e,t,n),i=r.kind===`chain`?r.layers:[];return{path:r.home,above:i.filter(e=>e!==r.home),projectDir:e??null}}function QE(e){return $E(e).join(`
164
- `)||null}function $E(e){switch(e.kind){case`chain`:return e.unchecked.map(e=>`Config location could not be checked: ${e.path} — ${e.error}`);case`missing`:return[`Config file not found: ${e.path} — rendering the bundled default until it appears`];case`unreadable`:return[`Config file could not be read: ${e.path} — ${e.error} — rendering the bundled default until it can be`]}}function eD(e,t){let n=qE(e,t).filter(e=>GE(e)===`present`),r=new Map;for(let e of n){let t=l.dirname(e),n=l.basename(e).replace(/\.(json5|json)$/,``),i=l.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 tD(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const nD=new Set([`data`,`segments`,`helpers`,`actions`]),rD=`plugin.json5`,iD=/^[a-z][a-z0-9_]*$/;function aD(e){let t=l.basename(l.dirname(e));return iD.test(t)?t:void 0}const oD=`plugins.`;function sD(e){return`${oD}${e}.data`}function cD(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:lD(e)}}}function lD(e){return e instanceof nc?e.issues.map(e=>e.path===``||e.message.includes(e.path)?e.message:`${e.path}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}function uD(e,t){return e.map(e=>l.resolve(l.dirname(t),KE(e)))}function dD(e,t,n,i){let a=new Map;return e.reduce((e,n)=>{let o=aD(n),s=(t,r)=>{let i=new Map(e.rendering);return o!==void 0&&r!==e.config&&i.delete(o),{...e,config:r,rendering:i,dropped:[...e.dropped,{path:n,plugin:o,reason:t}]}};if(l.basename(n)!==`plugin.json5`){let t=`a plugin is a folder holding its ${rD}, and the folder's name is the plugin's: move this file to <dir>/<name>/${rD} and list that`;return s(t,o===void 0?e.config:pD(fD(e.config,o),o,{path:n,plugin:o,reason:t}))}if(o===void 0)return s(`its folder "${l.basename(l.dirname(n))}" is not a plugin name (one matching ${iD}: it prefixes every name the plugin declares)`,e.config);let c=a.get(o);if(c!==void 0)return s(`plugin "${o}" is already listed, from ${c}`,e.config);a.set(o,n);let u=fD(e.config,o),d=cD(()=>{let e=r.readFileSync(n,`utf-8`),a=xl(yD(n,o,{source:e,json:it.default.parse(e)},t),u);return i(a),a});if(d.ok)return{...e,config:d.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[o,n]])};let f={path:n,plugin:o,reason:d.reason};return s(d.reason,pD(u,o,f))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function fD(e,t){let n=`${oD}${t}.`,r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!e.startsWith(n)));return{...e,variables:r(e.variables),segments:r(e.segments),helpers:r(e.helpers),actions:r(e.actions)}}function pD(e,t,n){return{...e,variables:{...e.variables,[sD(t)]:{kind:`dropped`,reason:tD(n),definition:n.path}}}}function mD(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function hD(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments)].map(mD)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:tD(e)}));return t=>{let i=mD(t);if(i===void 0)return[];let a=e.config.variables[sD(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function gD(e,t){let n=fv(e.presets).flatMap(t=>[...pc(hv(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),r=[...new Set([...n.map(e=>e.name),...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),i=Object.fromEntries(r.map(({name:e,cause:t})=>[e,_D(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=mD(t),r=n===void 0?void 0:e.variables[sD(n)];return r?.kind===`dropped`?{definition:r.definition,notice:r.reason}:void 0},o=Object.values(e.variables).some(e=>e.kind===`dropped`),s=o?Object.values(e.segments).flatMap(e=>[`template`,`bg`,`fg`,`when`].flatMap(t=>e[t]===void 0?[]:[e[t]])):[],c=o?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],l=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:a(e);return n===void 0?[]:[[e,n]]}),u=l([...s.flatMap(t=>oy(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...cy(t,e.helpers)]),e.helpers),f=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition)]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${sD(mD(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:f}}function _D(e,t,n){let r=`⚠ ${e}: ${t.join(`; `)}`,i=new Map;for(let e of n)for(let[t,n]of Object.entries(e.settings??{})){let e=i.get(t);i.set(t,e===void 0?[n]:[...e,n])}let a=Object.fromEntries([...i].map(([e,t])=>[e,vD(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function vD(e,t){let[n]=t,r=t.filter(e=>typeof e==`number`);return typeof n==`boolean`?{label:e,domain:`bool`,default:n}:typeof n==`number`?{label:e,domain:{min:Math.min(...r),max:Math.max(...r),step:1},default:n}:{label:e,domain:[...new Set(t.map(String))],default:n}}function yD(e,t,{source:n,json:r},{projectDir:i}){let a=[],o=()=>{throw new nc(e,a)};if(!Lc(r))return a.push({path:``,message:`a plugin definition must be an object, got ${Rc(r)}`}),o();for(let e of Object.keys(r))nD.has(e)||a.push({path:e,message:e===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${t}") — remove "plugin"`:`a plugin definition may not declare "${e}". Expected only: ${[...nD].join(`, `)}`});let s=SD(r.data,e,i,a);if(Lc(r.segments)||a.push({path:`segments`,message:`"segments" must be an object naming the plugin's segments`}),a.length>0||s===void 0)return o();let c={source:n,issues:a,allowedPalettes:new Set(No()),groups:[]},l=Eu(c,`data`,{[sD(t)]:{kind:`file`,path:s,parse:{json:!0},cache:{watch_file:s},default:{}}});for(let[e,t]of Object.entries(r.segments))Lc(t)&&`vars`in t&&a.push({path:`segments.${e}.vars`,message:`a plugin segment may not declare "vars": a plugin's only source is its data file`});let u={variables:l,segments:xD(t,Ed(c,r.segments,new Set)),helpers:xD(t,hE(c,r.helpers)),actions:xD(t,ST(c,r.actions))};for(let[e,t]of bD(u))try{kv.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),u}function*bD(e){for(let[t,n]of Object.entries(e.segments??{}))for(let e of[`template`,`bg`,`fg`,`when`]){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))`copy`in n&&(yield[`actions.${t}.copy`,n.copy]),`open`in n&&(yield[`actions.${t}.open`,n.open]),`preset`in n&&n.preset===`delete`&&(yield[`actions.${t}.name`,n.name])}function xD(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${oD}${e}.${t}`,n]))}function SD(e,t,n,r){if(typeof e==`string`&&e!==``)return l.resolve(l.dirname(t),KE(e));if(Lc(e)&&Object.keys(e).length===1&&typeof e.project==`string`&&e.project!==``){let t=e.project;if(l.isAbsolute(t)||t.startsWith(`~`)||l.normalize(t).split(l.sep)[0]===`..`){r.push({path:`data.project`,message:`data.project "${t}" must be a path inside the project, relative to its root (like ".lit/candybar.json"): no absolute path, "~" or ".."`});return}if(n===null){r.push({path:`data.project`,message:`data is read from the session's project, and this load has none`});return}return l.resolve(n,t)}r.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { project: "<path>" } relative to the session's project`})}function CD(e){let t=(process.env.XDG_DATA_DIRS||wD()).split(`:`).filter(e=>e!==``),n=process.env.XDG_DATA_HOME||l.join(h.homedir(),`.local`,`share`),r=[...[...t].reverse().map(e=>l.join(e,`cc-candybar`,`plugins`)),l.join(n,`cc-candybar`,`plugins`),...e===null?[]:[l.join(e,`.cc-candybar`,`plugins`)]];return r.filter((e,t)=>r.lastIndexOf(e)===t)}function wD(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${l.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function TD(e){let t=CD(e),n=new Map,r=[],i=[];for(let e of t){let t=ED(e);if(`error`in t){r.push(t);continue}for(let r of t.folders)n.delete(r),n.set(r,l.join(e,r,rD));for(let n of t.files)i.push({path:l.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${rD}: move this file to ${l.join(e,`<name>`,rD)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function ED(e){try{let t=r.readdirSync(e,{withFileTypes:!0}).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),n=t=>t.isDirectory()||DD(e,t);return{folders:t.filter(n).map(e=>e.name),files:t.filter(e=>!n(e)).map(e=>e.name)}}catch(t){return t.code===`ENOENT`?{folders:[],files:[]}:{path:e,error:t.message}}}function DD(e,t){if(!t.isSymbolicLink())return!1;try{return r.statSync(l.join(e,t.name)).isDirectory()}catch{return!0}}function OD(e,t,n,i){return e===null?{...ID,config:xl(ID.raw,t)}:AD(e,r.readFileSync(e,`utf-8`),t,n,i)}const kD={projectDir:null,beneath:{dropped:[],rendering:new Map}};function AD(e,t,n,r,i){let a=zD(e,t,i,(t,a)=>{let o=dD(uD(t,e),r,{config:n,rendering:r.beneath.rendering},t=>LD(FD(t),e,i)),s=hD(o,r.beneath.dropped);return{inherited:new Set([...Td(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=gD(xl(a.raw,o.config),s);return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(tD)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const jD=new WeakMap;function MD(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e,ND(e)])]),a=jD.get(n)??new Map;jD.set(n,a);let o=String(t.projectDir),s=a.get(o);if(s?.key===i)return s.layer;let c=dD(e,t,{config:n,rendering:new Map},e=>LD(FD(e),`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function ND(e){try{let t=r.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function PD(e,t,n,i,a=e=>r.readFileSync(e,`utf-8`),o){let s=TD(i.projectDir),c=MD(s.definitions,i,t,o),l={...c,dropped:[...c.dropped,...s.strays]};n.warned(s.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let u=l.config,d=[];for(let t of e){n.entered(t);let e=d.at(-1)?.plugins,r=AD(t,a(t),d.at(-1)?.config??u,{...i,beneath:{dropped:[...l.dropped,...d.flatMap(e=>e.plugins.dropped)],rendering:e?.rendering??l.rendering}},o);n.warned(r.warnings),d.push({...r,path:t})}let f=new Set(d.flatMap(e=>[...e.plugins.reached])),p=e=>f.has(e.path),m=l.dropped.filter(p),h=l.dropped.filter(e=>!p(e));n.warned(m.map(tD));let g={roots:s.roots,loaded:l.loaded,dropped:m,unreached:h,reached:f,rendering:d.at(-1)?.plugins.rendering??l.rendering},_=d.at(-1);if(_===void 0)return{layers:d,base:u,installed:g,config:LD(OD(null,u,kD),`<default>`,o)};try{return{layers:d,base:u,installed:g,config:LD(_,_.path,o)}}catch(e){for(let e of d.slice(0,-1))n.entered(e.path),LD(e,e.path,o);throw n.entered(_.path),e}}function FD(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const ID={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function LD({config:e,raw:t,source:n},r=`<config>`,i=new Set(No())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(xE(o,e,t),HE(o,e),a.length>0)throw new nc(r,a);let s=Ov(e,a);if(a.length>0)throw new nc(r,a);return vT(Rw(s))}function RD(e,t,n=new Set(No()),r=BD){return zD(e,t,n,()=>({inherited:r,layer:null})).raw}function zD(e,t,n,r){let i=VD(e,t),a=ac(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(No()),groups:[]};if(!Lc(i))throw new nc(e,[{path:``,message:`Config root must be an object, got ${Rc(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:WD({...c,issues:[]},i.plugins)??[],Lc(i.segments)?Object.keys(i.segments):[]),d=HD(c,i,l);if(s.length>0)throw new nc(e,s,o);return{raw:d,warnings:o,layer:u}}const BD=new Set;function VD(e,t){try{return it.default.parse(t)}catch(t){let n=t;throw new nc(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function HD(e,t,n){for(let n of Object.keys(t))UD.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...UD].join(`, `)}`,line:G(e.source,[n])});let r={};return t.globals!==void 0&&(r.globals=ou(e,`globals`,t.globals)),t.variables!==void 0&&(r.variables=Eu(e,`variables`,t.variables)),t.segments!==void 0&&(r.segments=Ed(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.
163
+ `).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return AS([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${NS[e]}`)])}}},FS="re-run `cc-candybar install`";function IS(e){if(e.kind===`failed`)return[`Launch Services could not be asked which app opens cc-candybar:// — ${e.reason}`];if(e.value===null)return[`no app is registered for cc-candybar:// — ${FS}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${FS}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${FS}`)}const LS=[PS,{name:`urlHandler`,label:`URL handler`,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${FS}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${FS}`};case`lost`:return AS([...IS(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}},MS];function RS(e){return LS.map(t=>({check:t,verdict:t.probe(e)}))}function zS(e){return LS.find(t=>t.name===e)}const BS=`${ad}doctor.`;function VS(e){let t=`${BS}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`}}function HS(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function US(e){return e.flatMap(({check:e,verdict:t})=>{let n=VS(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:``},{key:n.fixable,value:rs}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:HS(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?rs:ns}]})}const WS={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function GS(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries(WS).map(([t,n])=>[`${e}${t}`,n]))}}const KS=`armed`,qS=`disarmed`,JS=`.armed`,YS=e=>e.endsWith(JS);function XS(e,t,n){let r=`${e}${JS}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${KS}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:KS},[a]:{set:r,to:qS},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:qS}},disarm:a}}const ZS=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function QS(e){return typeof e==`string`&&ZS.test(e)?{kind:`line`,line:e}:{kind:`refused`,reason:`a slash command is "/" then its name, e.g. "/compact" or "/model opus", on one line with no control characters, got ${JSON.stringify(e)}`}}function $S(e){let t=QS(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const eC=[`/compact`,`/model`],tC=`/clear`;function nC(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=XS(`${e}clear`,{arm:tC,confirm:`${tC} ✓ confirm`},[n]);return{template:eC.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${Dx} }}`,actions:{...Object.fromEntries(eC.map(e=>[t(e),{slash:$S(e)}])),...r.actions,[n]:{slash:$S(tC)}},variables:r.variables,disarm:r.disarm}}function rC(e,t){let n=(e.CLAUDE_CONFIG_DIR??``).split(`,`)[0].trim();return n===``?void 0:l.resolve(t,n)}function iC(e){return e??l.join(h.homedir(),`.claude`)}function aC(e){return l.join(e,`settings.json`)}function oC(e){return l.join(e,`plugins`,`installed_plugins.json`)}function sC(e){return r.existsSync(e)?r.readFileSync(e,`utf8`):``}function cC(e){let t;try{let n=sC(e);if(/^\s*$/.test(n))return{};t=Ds.parse(n)}catch(t){throw Error(`cannot read ${e}: ${lC(t)}`,{cause:t})}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`cannot read ${e}: not a JSON object`);return t}const lC=e=>e instanceof Error?e.message:String(e),uC=Array.from({length:10},(e,t)=>(t+1)*1e5),dC=uC[0],fC=uC[uC.length-1];function pC(e){let t;try{t=cC(e)}catch(e){return X(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?J(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=dC&&n<=fC?J(n):X(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${dC}–${fC} tokens)`)}function mC(e,t){let n=Math.min(t??fC,fC),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:uC.filter(e=>e<r).at(-1)??0,higher:uC.find(e=>e>r&&e<=n)??0}}function hC(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${Dx} }}{{ if gt .autocompact.lower 0 }} {{ action (printf "${e}%d" .autocompact.lower) "−" }}{{ end }}{{ if gt .autocompact.higher 0 }} {{ action (printf "${e}%d" .autocompact.higher) "+" }}{{ end }}{{ if gt .autocompact.window 0 }} {{ action "${e}auto" "↺" }}{{ end }}{{ end }}{{ end }}`,bg:`{{ if ne .autocompact.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .autocompact.window 0) (ne .autocompact.error "") }}`,actions:{[`${e}auto`]:{slash:$S(`/autocompact auto`)},...Object.fromEntries(uC.map(t=>[`${e}${t}`,{slash:$S(`/autocompact ${t}`)}]))}}}const gC=e=>`{{ if ge ${e} 1000000 }}{{ printf "%.1f" (divf ${e} 1000000) }}M{{ else if ge ${e} 1000 }}{{ printf "%.1f" (divf ${e} 1000) }}K{{ else }}{{ ${e} }}{{ end }}`,_C=`${ad}menu`,vC=`open`,yC=`${ad}edit`,bC=`${ad}toolbar`,xC=GS(ad),SC=`${ad}commands`,CC=nC(`${SC}.`),wC=`${ad}autocompact`,TC=hC(`${wC}.`,gC),EC=e=>({kind:`segment`,name:e}),DC=`${ad}tab`,OC=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],kC=e=>`${DC}.${e}`,AC=e=>`${kC(e)}.toggle`,jC=e=>({variable:DC,key:DC,member:e}),MC=`${ad}save`,NC=`${ad}preset.save`,PC=`${ad}preset.delete`,FC=`${ad}resetAll`,IC=`${_C}.toggle`,LC={variable:_C,key:_C,member:vC},RC=`${ad}undo`,zC=`${ad}back`,BC=`${zC}.step`,VC=`${ad}navigation.back`,HC=zC,UC={template:`{{ if gt .${VC} 0 }}{{ action "${zC}" "◁" }}{{ else }}{{ fg (${DS}) "◁" }}{{ end }}`},WC=`${ad}redo`,GC=`${ad}doctor`,KC=`${GC}.run`,qC=e=>`${GC}.fix.${e}`,JC=e=>`${GC}.${e}`,YC=rv(`${ad}pickers`),XC=[{template:`{{ themePreview }}`}],ZC={template:`{{ layoutPreview }}`},QC={preset:[ZC,{when:`{{ not .preset.bundled }}`,template:`{{ action "${PC}" (printf "🗑 delete %s" .${Ox.preset.effectiveVar}) }}`}],theme:XC,style:XC,variation:[ZC]},$C=e=>`${ad}${e}`,ew=e=>`${ad}apply.${e}`,tw=e=>`${ad}reset.${e}`,nw=e=>`${ad}list.${e}`,rw=(e,t)=>`${nw(e)}.${t}`,iw=e=>`${ad}resettable.${e}`,aw=e=>e.length===0?`false`:`(or ${e.map(e=>`.${iw(e)}`).join(` `)})`,ow=Object.keys(Ox).map(e=>{let t=Ox[e],n=Yl(t.configKey),r=sS({label:t.label,domain:n},t.sessionKey,t.effectiveVar,ew(e),YC);return{...t,name:e,control:r,beneath:QC[e]??[]}}),sw={preset:`door`,theme:`look`,style:`look`,variation:`look`,endcaps:`look`,autoWrap:`layout`,padding:`layout`,updateNotice:`config`},cw=e=>ow.filter(t=>sw[t.name]===e),lw=e=>cw(e).map(xw);new Set(ow.flatMap(e=>[e.sessionKey,e.configKey]));const uw=XS(FC,{arm:`⟲`,confirm:`⟲ reset all?`},ow.map(e=>tw(e.name))),dw=[`unsaved`,`history.undo`,`history.redo`],fw=e=>`${ad}${e}`,pw=fw(`unsaved`),mw=(e,t)=>({body:t,shown:`(gt .${fw(e)} 0)`}),hw=[mw(`unsaved`,`{{ action "${MC}" (printf "💾 save %d" .${pw}) }}`),mw(`history.undo`,`{{ action "${RC}" "↶" }}`),mw(`history.redo`,`{{ action "${WC}" "↷" }}`),{body:uw.template,shown:`(or ${aw(ow.map(e=>e.name))} ${uw.armed})`}],gw={when:`{{ or ${hw.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+hw.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},_w=[{step:uw,place:`door`},{step:CC,place:`session`}],vw=e=>e.map(e=>e.step.disarm),yw=vw(_w),bw=vw(_w.filter(e=>e.place!==`door`));function xw(e){let t=$C(e.name);return e.control.kind===`inline`?EC(t):Al(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[EC(nw(e.name)),...e.beneath.map((t,n)=>EC(rw(e.name,n)))]},`drop`)}function Sw(e){return e===_C}function Cw(e){let t=EC(_C);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[Cw(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 ww(e){return Tw(e)>0?e:Cw(e)}function Tw(e){let t=0;for(let n of pc(e))n.kind===`segment`&&Sw(n.name)&&(t+=1);return t}function Ew(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&Sw(e.name)||e.opens!==void 0&&Ew(e.opens.body,!0):e.children.some(e=>Ew(e,n))}const Dw={session:{direction:`vertical`,content:[EC(bC),{kind:`container`,direction:`horizontal`,children:[EC(SC),EC(wC)]}]},look:{direction:`horizontal`,content:[]},layout:{direction:`horizontal`,content:[EC(NC),EC(yC)]},config:{direction:`horizontal`,content:[]},tools:{direction:`vertical`,content:[EC(GC),...LS.map(e=>EC(JC(e.name)))]}},Ow=e=>({kind:`container`,direction:Dw[e].direction,children:[...Dw[e].content,...lw(e)]});function kw(e){return e.kind===`segment`?Sw(e.name)?Al(e.name,LC,jw,`above`):e:Nw(e)}function Aw(){return{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[EC(HC),...lw(`door`),EC(MC)]},{kind:`container`,direction:`horizontal`,children:OC.map(({member:e})=>Al(kC(e),jC(e),Ow(e),`drop`))}]}}const jw=Aw();function Mw(e){let t=new Map;for(let e of pc(jw))e.kind===`segment`&&e.opens!==void 0&&t.set(e.opens.ref.key,e.opens.ref.variable);return[...t].map(([t,n])=>{let r=e.variables[n];if(r?.kind!==`state`||r.default===void 0)throw Error(`settings menu: the door folds "${t}", but "${n}" is not a state variable the menu declares with a default`);let i=`${_C}.fold.${td(t)}`;return e.actions[i]={set:t,to:r.default},i})}function Nw(e){return{...e,children:e.children.map(e=>kw(e))}}function Pw(e){let t={variables:{[_C]:Il(_C,Tl)},actions:{[IC]:Ll(_C,vC),[KC]:{doctor:`run`},[yC]:{do:[...Pv]},...xC.actions,...CC.actions,...TC.actions,[MC]:{save:!0},[RC]:{undo:!0},[BC]:{back:!0},[zC]:{do:[BC,...yw]},[WC]:{redo:!0},[NC]:{preset:`save`},[PC]:{preset:`delete`,name:`{{ .${Ox.preset.effectiveVar} }}`}},segments:{[_C]:{template:`{{ $door := ${Pl(_C,Fl(e),Fl(`✖`))} }}{{ if ${Ml(LC)} }}{{ fg (color "error") $door }}{{ else }}{{ $door }}{{ end }}`},[bC]:{template:xC.template},[SC]:{template:CC.template,when:CC.when},[wC]:{template:TC.template,bg:TC.bg,when:TC.when},[HC]:UC,[MC]:gw,[NC]:{template:`{{ action "${NC}" "+ preset" }}`},[GC]:{template:`{{ action "${KC}" "🩺 doctor" }}`},[yC]:{template:`{{ action "${yC}" "✎ arrange" "✎ done" }}`}}};t.variables[VC]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of dw)t.variables[fw(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[DC]=Il(DC,`session`);for(let{member:e,label:n}of OC){t.actions[AC(e)]=Ll(DC,e),t.actions[kC(e)]={do:[AC(e),...bw]};let r=aw(cw(e).map(e=>e.name)),i=`(ternary ${Fl(` •`)} "" ${r})`,a=e=>`(print ${Fl(e)} ${i})`;t.segments[kC(e)]={template:`{{ ${Pl(kC(e),a(n),a(`▾ ${n}`))} }}`}}return Object.assign(t.variables,CC.variables,uw.variables),Iw(t),Fw(t),t.actions[_C]={do:[IC,...yw,...Mw(t)]},t}function Fw(e){for(let t of LS){let n=VS(t.name),r=qC(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[JC(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${ns}" }} {{ action "${r}" "[fix]" }}{{ end }}{{ end }}`}}}function Iw(e){for(let t of ow){Object.assign(e.actions,t.control.actions);let n=tw(t.name);e.actions[n]={reset:t.configKey},e.variables[iw(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${iw(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[$C(t.name)]={template:`${t.control.template}${r}`},t.control.kind===`picker`&&(e.segments[nw(t.name)]={template:t.control.list.template}),t.beneath.forEach((n,r)=>{e.segments[rw(t.name,r)]=n})}Object.assign(e.actions,uw.actions)}function Lw(e){let{variables:t,actions:n}=Uv();Object.assign(e.variables,t),Object.assign(e.actions,n)}function Rw(e){let t=Pw(e.globals.menuGlyph??`🍫`);Lw(t);let n={...e.presets},r=[];for(let t of fv(e.presets)){let{node:i}=hv(e,t),a=kw(ww(i));r.push(a),n[t]={...mv(e.presets,t),root:a}}let i=Lx(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const zw=`${id}live`,Bw=[`☐ live`,`☑ live`],Vw=`${id}done`,Hw=`${id}cancel`,Uw=`${id}rewind`,Ww=`${id}changes`,Gw=`(gt .${Ww} 0)`,Kw=`(or ${Gw} (gt .${pw} 0))`,qw={variable:zw,key:zw,member:`open`};function Jw(e){return`${id}configuring.p${e}`}function Yw(e){return`and ${Ml(Rv)} (not ${Ml(qw)}) (ne .${Jw(e)} "true")`}function Xw(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${jv} "${kl(e)}")`).join(` `)} false }}`}}function Zw(e,t,n){return`{{ if ${Yw(e)} }}${t}{{ else }}${n}{{ end }}`}const Qw=`{{ and ${Ml(Rv)} .preset.customized }}`,$w=sd;function eT(e){return new Map([...Qx(e),...nT(e)])}const tT=`${id}addable`;function nT(e){return new Map([[tT,{members:Object.keys(e.segments).filter(e=>!$w(e)),library:{groups:$u.map(e=>({id:e,label:ed[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function rT(e,t,n){return n.segments[e]={template:t,when:zv,bg:yS},{kind:`segment`,name:e}}function iT(e,t,n){let r=`${id}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${lo}`}) (action "${r}" "✖") }}`}function aT(e){return`{{ if ${Ml(Rv)} }}${e}{{ end }}`}function oT(e,t){return e.reduce((e,t)=>`{{ if and ${Ml(Rv)} ${Ml(t)} }}true{{ else }}${e}{{ end }}`,t)}function sT(e){return e.flatMap(e=>[...pc(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function cT(e,t,n){return`${Iv}${e}.${t}.${n}`}function lT(e,t,n,r){let i=lc(n),a=`${id}${e.presetIdent}`,o=Lv(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=rv(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:Tl},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:jv,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=cT(e.presetIdent,i,r),l=`${Iv}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Dc(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=sS(aS(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};let p=`${d}.list`;return e.artifacts.segments[d]={template:f.template},e.artifacts.segments[p]={template:f.list.template},Al(d,f.list.ref,{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:p}]},`drop`)});return{term:`{{ action "${s}" "⚙️" }}`,ref:{variable:jv,key:jv,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const uT=`${id}label:`;function dT(e){if(e.startsWith(uT)){let t=e.slice(uT.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function fT(e,t,n,r){let{artifacts:i}=n,a=lc(e),o=`${uT}${a}:${e.name}`;i.segments[o]={template:`{{ "${kl(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=e.settings?.[Sc];return{...Al(o,r.ref,r.body,`drop`,oT([r.ref],`{{ ${Yw(n.presetIdent)} }}`)),...s!==void 0&&{settings:{theme:s}},drafts:{[Sc]:r.drafts[Sc]}}}function pT(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${id}${i}.insert.${t}`,s=`${id}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:tT,anchor:n,relation:r};let c=tv(o),l=nv(s,o,void 0),u=av(l),d=iv(l,c);return a.variables[l]=Il(l,Tl),a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=Ll(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${Ml({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${lo}`}) $m }}{{ end }}`}}function mT(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!$w(e.name)),i=e=>mT(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=fc(o,i);if($w(o.name)){n.push(s);continue}let c=lc(o),l=a===r?[pT(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=pT(t,u,c,`after`),f=iT(t,u,c),p=t.segments[o.name],m=lT(t,u,o,Cc(p)),h=aT(f),g=aT(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>rT(e.host,e.template,t.artifacts)),{...fT(o,p,t,m),lead:h,trail:g},{...s,when:Zw(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},rT(d.host,d.template,t.artifacts)]};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[_]}:_)}return{...e,children:n,...e.when!==void 0&&{when:oT(sT(n),Zw(t.presetIdent,`true`,e.when))}}}function hT(e,t,n,r,i,a,o){let s=`${id}${t}.resetLayout`,c=`${id}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:Qw},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},gT(e,o)]}}function gT(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),gT(n,t)]}:{...e,children:[...e.children,t]}}function _T(e,t,n,r,i,a){let{node:o}=hv(e,t),s={presetIdent:td(t),rootKey:fS(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=mT(o,s);return n.variables[Jw(s.presetIdent)]=Xw(s.configured),hT(c,s.presetIdent,s.rootKey,n,r,i,a)}function vT(e){let t={variables:{},actions:{},segments:{}},n=_S(`${id}help`,TS,[Rv],t);t.variables[zw]=Il(zw,Tl),t.actions[zw]=Ll(zw,qw.member),t.segments[zw]={template:Nl(zw,...Bw),when:zv};let r={kind:`segment`,name:zw},i=n;t.variables[Ww]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[Vw]={do:[MC,...Pv]},t.segments[Vw]={template:`{{ if ${Kw} }}{{ action "${Vw}" "✓ save" }}{{ else }}{{ action "${Vw}" "✓ done" }}{{ end }}`,when:zv},t.actions[Uw]={rewind:!0},t.actions[Hw]={do:[Uw,...Pv]},t.segments[Hw]={template:`{{ action "${Hw}" "↩ cancel" }}`,when:`{{ and ${Ml(Rv)} ${Gw} }}`};let a=[{kind:`segment`,name:Vw},{kind:`segment`,name:Hw}],o={...e.presets},s=[];for(let n of fv(e.presets)){let c=_T(e,n,t,a,r,i);s.push(c),o[n]={...mv(e.presets,n),root:c}}let c=Lx(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}const yT=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`doctor`,`ceiling`,`slash`,`do`];function bT(e){return e.ceiling===`set`?[`set`,e.to]:[`clear`]}function xT(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function ST(e,t){if(t===void 0)return{};if(!Lc(t))return Q(e,`actions`,`actions must be an object, got ${Rc(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=CT(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Q(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function CT(e,t,n){if(!Lc(n))return Q(e,t,`${t} must be an action object, got ${Rc(n)}`),null;if(`persistWhen`in n)return Q(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let r=yT.filter(e=>e in n);return r.length===1?wT[r[0]](e,t,n):(Q(e,t,`action must declare exactly one of: ${yT.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const wT={set:(e,t,n)=>nE(e,t,n,`set`,QT),persist:(e,t,n)=>nE(e,t,n,`persist`,$T),copy:TT(`copy`),open:TT(`open`),reset:ET,undo:OT(`undo`),redo:OT(`redo`),back:OT(`back`),rewind:OT(`rewind`),save:OT(`save`),preset:kT,doctor:AT,ceiling:jT,slash:MT,do:NT};function TT(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Mc(t,n,r,e);return i===null?null:{[e]:i}}}function ET(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=PT(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 DT={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,back:`it steps the session's navigation history`,rewind:`it steps the session's settings history back to where edit mode opened`,save:`it saves the session's unsaved settings`};function OT(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Q(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${DT[e]}), got ${K(r[e])}`),null)}}function kT(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Q(e,`${t}.preset`,`preset must be "save" or "delete", got ${K(r)}`),null;if(r===`save`)return{preset:`save`};let a=Mc(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function AT(e,t,n){let r=n.doctor,i=r===`run`?[`doctor`]:[`doctor`,`check`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${i.join(`, `)}`);if(r!==`run`&&r!==`fix`)return Q(e,`${t}.doctor`,`doctor must be "run" or "fix", got ${K(r)}`),null;if(r===`run`)return{doctor:`run`};let a=n.check;return typeof a!=`string`||zS(a)===void 0?(Q(e,`${t}.check`,`doctor fix must name a check (have: ${LS.map(e=>e.name).join(`, `)}), got ${K(a)}`),null):{doctor:`fix`,check:a}}function jT(e,t,n){let r=n.ceiling,i=r===`clear`?[`ceiling`]:[`ceiling`,`to`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a ceiling action. Expected only: ${i.join(`, `)}`);if(r===`clear`)return{ceiling:`clear`};if(r!==`set`)return Q(e,`${t}.ceiling`,`ceiling must be "set" or "clear", got ${K(r)}`),null;let a=n.to;return typeof a!=`string`||a.trim()===``?(Q(e,`${t}.to`,`ceiling set needs \`to\`: a memento ceiling value such as "+100_000", "400000" or "off", got ${K(a)}`),null):{ceiling:`set`,to:a}}function MT(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=QS(n.slash);return r.kind===`refused`?(Q(e,`${t}.slash`,r.reason),null):{slash:r.line}}function NT(e,t,n){for(let r of Object.keys(n))r!==`do`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Q(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${K(r)}`),null):{do:r}}function PT(e,t,n,r,i,a){let o=Mc(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Q(e,s,i),null):o.includes(`/`)?(Q(e,s,a(o)),null):o}const FT={set:`the SessionState key to write`,persist:`the config globals field to write`};function IT(e,t,n,r){let i=FT[r],a=PT(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 LT(e){return e===`set`?`set-state`:`set-config`}const RT={to:rE(`set`)},zT={to:rE(`persist`)},BT={from:iE(`set`)},VT={from:iE(`persist`)},HT={min:lE(),max:lE(),by:lE()},UT={int:oE()},WT={cycle:aE(`set`)},GT={cycle:aE(`persist`)},KT={removeSegment:sE(`removeSegment`)},qT={insertSegment:sE(`insertSegment`),anchor:sE(`anchor`),relation:cE()},JT={insertSegmentFrom:iE(`persist`),anchor:sE(`anchor`),relation:cE()},YT={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},XT={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function ZT(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>Vc(e,t,n,r),c=al(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?Yc(s,...n):s}}const QT=[ZT(`set`,RT),ZT(`set`,BT),ZT(`set`,HT,[YT,XT]),ZT(`set`,UT),ZT(`set`,WT)],$T=[ZT(`persist`,zT),ZT(`persist`,VT),ZT(`persist`,HT,[YT,XT]),ZT(`persist`,GT),ZT(`persist`,KT),ZT(`persist`,qT,[],[`insertSegment`]),ZT(`persist`,JT,[],[`insertSegmentFrom`])];function eE(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"endcaps"/"styles", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function tE(e){let t=eE(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 nE(e,t,n,r,i){let a=IT(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Q(e,t,`${tE(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Q(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function rE(e){let t=LT(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>PT(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 iE(e){let t=LT(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Q(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Q(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Q(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Q(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Q(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Q(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${K(o)}`)}}}function aE(e){let t=LT(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Q(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${Rc(o)}`);return}let c=o;if(c.length<2){Q(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Q(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Q(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Q(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function oE(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Q(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${K(r[n])}`);return}return!0}}}function sE(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Mc(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Q(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Q(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function cE(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Q(e,`${t}.${n}`,`relation must be "before" or "after", got ${K(i)}`);return}return i}}}function lE(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Q(e,`${t}.${n}`,`${n} must be an integer, got ${K(i)}`);return}return i}}}function uE(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const dE={noun:`style key`,fields:{hueShift:$c(),chromaScale:$c({min:0}),lightnessScale:$c(),lightnessShift:$c()}};function fE(e,t){if(!Lc(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${Rc(t)}`,line:G(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:G(e.source,[`styles`,r])});continue}if(qo(r)){e.issues.push({path:`styles.${r}`,message:uE(`styles.${r}`,r,`globals.endcaps`),line:G(e.source,[`styles`,r])});continue}let t=zc(e,dE,`styles.${r}`,i);t!==null&&(n[r]={...cr,...t})}return n}const pE={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:Yd(e,`${t}.${n}`,r[n])},globals:{required:!1,json:cu(),parse:(e,t,n,r)=>r[n]===void 0?void 0:su(e,`${t}.${n}`,r[n])}}};function mE(e,t){if(!Lc(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${Rc(t)}`,line:G(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:G(e.source,[`presets`,r])});continue}let t=zc(e,pE,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function hE(e,t){if(t===void 0)return{};if(!Lc(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${Rc(t)}`,line:G(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${K(i)}`,line:G(e.source,[`helpers`,r])});continue}n[r]=i}return n}const gE=new Map([[`session.budget.amount`,{segment:`session`,setting:`budget`}],[`session.budget.warningThreshold`,{segment:`session`,setting:`warnAt`}],[`today.budget.amount`,{segment:`today`,setting:`budget`}],[`today.budget.warningThreshold`,{segment:`today`,setting:`warnAt`}],[`block.budget.heatThreshold`,{segment:`block`,setting:`warnAt`}],[`block.budget.warningThreshold`,{segment:`block`,setting:`errorAt`}],[`weekly.budget.heatThreshold`,{segment:`weekly`,setting:`warnAt`}],[`weekly.budget.warningThreshold`,{segment:`weekly`,setting:`errorAt`}],[`burn.eta.errorMinutes`,{segment:`burnrate`,setting:`errorWithin`}],[`burn.eta.warnMinutes`,{segment:`burnrate`,setting:`warnWithin`}]]);function _E(e){return`it became the "${e.setting}" setting of each "${e.segment}" placement — set it on the placement where a row places "${e.segment}" ({ seg: "${e.segment}", settings: { ${e.setting}: <value> } }), or redeclare segments.${e.segment}.settings.${e.setting} with the default every placement should start from`}function vE(e){let t=gE.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${_E(t)}`}function yE(e){let t=gE.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${_E(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}function bE(e,t){let n=new Map;for(let e of Object.keys(t)){let t=td(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:G(e.source,[`presets`])})}function xE(e,t,n){let r=[[[`globals`],t.globals.style],[[`editGlobals`],t.editGlobals.style],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style])];for(let[n,i]of r){if(i===void 0||zo(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:qo(i)?uE(r,i,`${n.join(`.`)}.endcaps`):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:G(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:G(e.source,[`globals`,`preset`])}),bE(e,t.presets);let i=uy(t);for(let t of i.names)t!==`settings`&&!t.startsWith(wE)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:G(e.source,[`variables`,t])});let a=(t,n,r)=>{Tw(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${_C}" ${Tw(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}),Ew(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${_C}" 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}),o(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 pc(t)){if(e.kind!==`segment`)continue;let t=lc(e);i.set(t,[...i.get(t)??[],e])}for(let[t,a]of i){if(a.length<2)continue;let o=a[1].name,s=dc(o,new Set(i.keys()));e.issues.push({path:n,message:`${n} has ${a.length} placements with the id "${t}" — an id names one placement (its settings, its menus' open state, and edit mode all address it), so give each its own: { seg: "${o}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:r})}};function o(e,t=!1){return e.kind===`segment`?!1:t&&e.distribution!==void 0||e.children.some(n=>o(n,t||cc[e.direction]===`cell`))}let s=(n,r)=>{for(let[a,o]of vl(n,r)){let n=G(e.source,o.split(`.`));if(a.when!==void 0&&(IE(e,`${o}.when`,a.when,i,{line:n}),FE(e,`${o}.when`,a.when,n)),a.kind===`segment`){if(Sw(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${_C}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${_C}"`,line:n});continue}Object.prototype.hasOwnProperty.call(t.segments,a.name)||e.issues.push({path:o,message:`${r} entry "${a.name}" does not match any declared segment${dd(a.name)}`,line:n}),ME(e,t,a,o,n)}}};n.root!==void 0&&s(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&s(t.root,`presets.${e}.root`);let c=new Map([[`root`,gl(t.root)]]);for(let e of fv(t.presets)){let{node:n,path:r}=hv(t,e);c.set(r,n)}for(let[t,n]of c)a(n,t,G(e.source,t.split(`.`)));UE(e,t,i,()=>!0)}const SE=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function CE(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=G(e.source,[`actions`,n,r]);if(!fv(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${fv(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(`, `)})${dd(i)}`,line:c})},p=new Set(uc(hv(t,a).node)),m=(r,i)=>{!ud.has(i)||p.has(i)||Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" names no placement${dd(i)}`,line:c})};`removeSegment`in o&&m(`removeSegment`,o.removeSegment),`insertSegment`in o&&f(`insertSegment`,o.insertSegment),(`insertSegment`in o||`insertSegmentFrom`in o)&&m(`anchor`,o.anchor)}const wE=`settings.`;function TE(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>wE+e)])}}function EE(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:G(e.source,[`segments`,t,`settings`,n])})},a=kE(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of Tc(n,OE(n)))i(e,`the defaults do not stand together: ${t}`)}function DE(e){return kE(e).length>0||Tc(e,OE(e)).length>0}function OE(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function kE(e){let t=t=>wc(AE(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||wc(AE(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${jE(e,n).join(`, `)||`none`})`}];let i=[n];for(let e=r;e!==void 0;e=t(e)){if(e===n)return i.every(e=>n<=e)?[{setting:n,message:`atLeast closes a cycle (${[...i,n].join(` ≥ `)}) — every setting on it could only ever equal the rest`}]:[];if(i.includes(e))return[];i.push(e)}return[]})}function AE(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function jE(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&wc(n)!==void 0).map(([e])=>e)}function ME(e,t,n,r,i){let a=Object.prototype.hasOwnProperty.call(t.segments,n.name)?t.segments[n.name]:void 0;if(a===void 0)return;let o=Cc(a),s=`${r}: placement "${lc(n)}" of segment "${n.name}"`;for(let[t,a]of Object.entries(n.settings??{})){let c=Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0,l=c===void 0?`sets "${t}", which segment "${n.name}" does not declare (it has: ${Object.keys(o).join(`, `)})`:Ec(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Ao(a):``}, but it must be ${kc(c)}`;l!==void 0&&e.issues.push({path:r,message:`${s} ${l}`,line:i})}let c=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,n.settings?.[e]??t.default]));if(!(!Object.entries(c).every(([e,t])=>Ec(o[e],t))||DE(o)))for(let{message:t}of Tc(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function NE(e,t,n,r,i){n.kind===`template`&&IE(e,`${t}.template`,n.template,r,{segCtx:i}),bc(n)&&n.cache&&`key`in n.cache&&IE(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function PE(e,t,n,r,i){if(bc(n)&&n.cache&&`depends_on`in n.cache)for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:G(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function FE(e,t,n,r){try{kv.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function IE(e,t,n,r,i){for(let[a,o]of ny(n,r.helpers)){if(ly(a,r))continue;if(a.startsWith(wE)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??G(e.source,t.split(`.`))});continue}if(o!==null){LE(e,o,`Template references unknown variable ".${a}"${yE(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&ly(n,r)?` (segment-local vars are namespaced — write ".${n}")`:yE(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??G(e.source,t.split(`.`))})}}function LE(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:G(e.source,[`helpers`,t])})}function RE(e,t,n,r,i){let a=n.set,o=Yl(Ox[r].configKey),s=`${a} takes ${iS(o,i)}`;if(`min`in n&&(o===`bool`||`from`in o)){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:G(e.source,[`actions`,t,`min`])});return}let c=VE(n,i);if(c===BE){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:G(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!rS(o,e.value,i));if(l.length!==0){if(a===Ox.style.sessionKey&&c.every(e=>qo(e.value))){let r=Ox.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:uE(`actions.${t}.to`,n.to,`set: "${r}", to`),line:G(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:G(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=zE?r.join(`, `):`${r.slice(0,zE).join(`, `)} and ${r.length-zE} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:G(e.source,[`actions`,t,n])})}}}const zE=3,BE=Symbol(`any integer`);function VE(e,t){return`to`in e?[{field:`to`,value:e.to}]:`cycle`in e?e.cycle.map(e=>({field:`cycle`,value:e})):`from`in e?eS(e.from,t).members.map(e=>({field:`from`,value:e})):`min`in e?[{field:`min`,value:String(e.min)},{field:`max`,value:String(e.max)}]:BE}function HE(e,t){return Object.entries(e).filter(([e])=>t(e))}function UE(e,t,n,r){let i=eT(t),a=$x(i);for(let[n,o]of HE(t.actions,r)){let[t,r]=`from`in o?[`from`,o.from]:`insertSegmentFrom`in o?[`insertSegmentFrom`,o.insertSegmentFrom]:[null,null];if(t!==null&&typeof r==`string`&&!a.includes(r)){e.issues.push({path:`actions.${n}.${t}`,message:`actions.${n} ${t}: references ${nS(r,i)}`,line:G(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;jx.has(o.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${o.set}", which has no session pick — globals.${o.set} is set in the config file only, so a click would change nothing; write it with { persist: "${o.set}", … } instead`,line:G(e.source,[`actions`,n,`set`])});let s=Fx.get(o.set);s!==void 0&&RE(e,n,o,s,i)}for(let[n,i]of HE(t.actions,r))`do`in i&&i.do.forEach((r,a)=>{let o=Object.prototype.hasOwnProperty.call(t.actions,r)?t.actions[r]:void 0,s=o===void 0?`references unknown action "${r}"`:`do`in o?`"${r}" is itself a do action — list its members here instead`:i.do.indexOf(r)===a?a>0&&xT(o)?`"${r}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${r}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:G(e.source,[`actions`,n,`do`])})});for(let[n,i]of HE(t.actions,r)){let r=`persist`in i?i.persist:`reset`in i?i.reset:null;if(r===null)continue;let a=`persist`in i?`persist`:`reset`,o=mS(r);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a config globals field (have: ${fu().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, or a "presets.<name>.root" target`,line:G(e.source,[`actions`,n,a])});continue}let s=SE.filter(e=>e in i);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){CE(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!fv(t.presets).includes(o.preset)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names preset "${o.preset}" which is not declared (have: ${fv(t.presets).join(`, `)})`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${dd(o.segment)}`,line:G(e.source,[`actions`,n,a])});continue}`min`in i&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:G(e.source,[`actions`,n,a])})}}for(let[i,a]of HE(t.variables,r)){NE(e,`variables.${i}`,a,n);let t=vE(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:G(e.source,[`variables`,i])})}for(let[i,a]of HE(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))NE(e,`segments.${i}.vars.${t}`,r,n,i);let r=Cc(a);EE(e,i,r);let o=TE(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];if(typeof s==`string`){IE(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r});for(let{name:r,site:a,via:o}of oy(s,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,r))continue;let s=a===`options`?` (in a picker, menu or carousel)`:``;if(o!==null){LE(e,o,`Template references unknown action "${r}"${s}`);continue}e.issues.push({path:`segments.${i}.${n}`,message:`${n} references unknown action "${r}"${s}`,line:G(e.source,[`segments`,i,n])})}}}}for(let[i,a]of HE(t.variables,r))PE(e,`variables.${i}`,a,n);for(let[i,a]of HE(t.segments,r))if(a.vars)for(let[t,r]of Object.entries(a.vars))PE(e,`segments.${i}.vars.${t}`,r,n,i)}function WE(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=GE(t),a=new Map,o=[];for(let e of r.keys())a.set(e,0);for(let e of r.keys())if(!(!n(e)||a.get(e)!==0)&&s(e))return;function s(t){a.set(t,1),o.push(t);for(let c of r.get(t)??[]){if(!n(c))continue;let t=a.get(c);if(t===1){let t=o.indexOf(c),n=[...o.slice(t),c],r=n[0],a=i.get(r);return e.issues.push({path:a?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:G(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function GE(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 ny(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),bc(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 KE=[`json5`,`json`];function qE(e){try{return r.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function JE(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?h.homedir()+e.slice(1):e}function YE(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?KE.map(t=>l.join(e,`.cc-candybar.${t}`)):[],...KE.map(e=>l.join(r,`.cc-candybar.${e}`)),...KE.map(e=>`${XE()}.${e}`)])]}function XE(){let e=process.env.XDG_CONFIG_HOME??l.join(h.homedir(),`.config`);return l.join(e,`cc-candybar`,`config`)}function ZE(e,t,n){let i=[],a=new Map;for(let o of YE(e,t,n)){let e=qE(o);if(e===`absent`)continue;if(e!==`present`){i.push(e);continue}let t=l.join(r.realpathSync(l.dirname(o)),l.basename(o).replace(/\.(json5|json)$/,``));a.has(t)||a.set(t,o)}let o=[...a.values()].reverse();if(n===void 0)return{kind:`chain`,layers:o,home:QE(o),unchecked:i};let[s]=i,c=n;return o.length>0?{kind:`chain`,layers:o,home:c,unchecked:i}:s===void 0?{kind:`missing`,path:n,home:c}:{kind:`unreadable`,...s,home:c}}function QE(e){let t=XE();return e.find(e=>KE.some(n=>e===`${t}.${n}`))??`${t}.${KE[0]}`}function $E(e,t,n){let r=ZE(e,t,n),i=r.kind===`chain`?r.layers:[];return{path:r.home,above:i.filter(e=>e!==r.home),projectDir:e??null}}function eD(e){return tD(e).join(`
164
+ `)||null}function tD(e){switch(e.kind){case`chain`:return e.unchecked.map(e=>`Config location could not be checked: ${e.path} — ${e.error}`);case`missing`:return[`Config file not found: ${e.path} — rendering the bundled default until it appears`];case`unreadable`:return[`Config file could not be read: ${e.path} — ${e.error} — rendering the bundled default until it can be`]}}function nD(e,t){let n=YE(e,t).filter(e=>qE(e)===`present`),r=new Map;for(let e of n){let t=l.dirname(e),n=l.basename(e).replace(/\.(json5|json)$/,``),i=l.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 rD(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const iD=new Set([`data`,`segments`,`helpers`,`actions`]),aD=`plugin.json5`,oD=/^[a-z][a-z0-9_]*$/;function sD(e){let t=l.basename(l.dirname(e));return oD.test(t)?t:void 0}const cD=`plugins.`;function lD(e){return`${cD}${e}.data`}function uD(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:dD(e)}}}function dD(e){return e instanceof nc?e.issues.map(e=>e.path===``||e.message.includes(e.path)?e.message:`${e.path}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}function fD(e,t){return e.map(e=>l.resolve(l.dirname(t),JE(e)))}function pD(e,t,n,i){let a=new Map;return e.reduce((e,n)=>{let o=sD(n),s=(t,r)=>{let i=new Map(e.rendering);return o!==void 0&&r!==e.config&&i.delete(o),{...e,config:r,rendering:i,dropped:[...e.dropped,{path:n,plugin:o,reason:t}]}};if(l.basename(n)!==`plugin.json5`){let t=`a plugin is a folder holding its ${aD}, and the folder's name is the plugin's: move this file to <dir>/<name>/${aD} and list that`;return s(t,o===void 0?e.config:gD(hD(e.config,o),o,{path:n,plugin:o,reason:t}))}if(o===void 0)return s(`its folder "${l.basename(l.dirname(n))}" is not a plugin name (one matching ${oD}: it prefixes every name the plugin declares)`,e.config);let c=a.get(o);if(c!==void 0)return s(`plugin "${o}" is already listed, from ${c}`,e.config);a.set(o,n);let u=hD(e.config,o),d=uD(()=>{let a=r.readFileSync(n,`utf-8`),s=xl(SD(n,o,{source:a,json:it.default.parse(a)},t),u);return i(s,o,u!==e.config),s});if(d.ok)return{...e,config:d.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[o,n]])};let f={path:n,plugin:o,reason:d.reason};return s(d.reason,gD(u,o,f))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function mD(e){let t=`${cD}${e}.`;return e=>e.startsWith(t)}function hD(e,t){let n=mD(t),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n(e)));return[e.variables,e.segments,e.helpers,e.actions].some(e=>Object.keys(e).some(n))?{...e,variables:r(e.variables),segments:r(e.segments),helpers:r(e.helpers),actions:r(e.actions)}:e}function gD(e,t,n){return{...e,variables:{...e.variables,[lD(t)]:{kind:`dropped`,reason:rD(n),definition:n.path}}}}function _D(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function vD(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments)].map(_D)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:rD(e)}));return t=>{let i=_D(t);if(i===void 0)return[];let a=e.config.variables[lD(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function yD(e,t){let n=fv(e.presets).flatMap(t=>[...pc(hv(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),r=[...new Set([...n.map(e=>e.name),...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),i=Object.fromEntries(r.map(({name:e,cause:t})=>[e,bD(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=_D(t),r=n===void 0?void 0:e.variables[lD(n)];return r?.kind===`dropped`?{definition:r.definition,notice:r.reason}:void 0},o=Object.values(e.variables).some(e=>e.kind===`dropped`),s=o?Object.values(e.segments).flatMap(e=>[`template`,`bg`,`fg`,`when`].flatMap(t=>e[t]===void 0?[]:[e[t]])):[],c=o?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],l=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:a(e);return n===void 0?[]:[[e,n]]}),u=l([...s.flatMap(t=>oy(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...cy(t,e.helpers)]),e.helpers),f=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition)]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${lD(_D(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:f}}function bD(e,t,n){let r=`⚠ ${e}: ${t.join(`; `)}`,i=new Map;for(let e of n)for(let[t,n]of Object.entries(e.settings??{})){let e=i.get(t);i.set(t,e===void 0?[n]:[...e,n])}let a=Object.fromEntries([...i].map(([e,t])=>[e,xD(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function xD(e,t){let[n]=t,r=t.filter(e=>typeof e==`number`);return typeof n==`boolean`?{label:e,domain:`bool`,default:n}:typeof n==`number`?{label:e,domain:{min:Math.min(...r),max:Math.max(...r),step:1},default:n}:{label:e,domain:[...new Set(t.map(String))],default:n}}function SD(e,t,{source:n,json:r},{projectDir:i}){let a=[],o=()=>{throw new nc(e,a)};if(!Lc(r))return a.push({path:``,message:`a plugin definition must be an object, got ${Rc(r)}`}),o();for(let e of Object.keys(r))iD.has(e)||a.push({path:e,message:e===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${t}") — remove "plugin"`:`a plugin definition may not declare "${e}". Expected only: ${[...iD].join(`, `)}`});let s=TD(r.data,e,i,a);if(Lc(r.segments)||a.push({path:`segments`,message:`"segments" must be an object naming the plugin's segments`}),a.length>0||s===void 0)return o();let c={source:n,issues:a,allowedPalettes:new Set(No()),groups:[]},l=Eu(c,`data`,{[lD(t)]:{kind:`file`,path:s,parse:{json:!0},cache:{watch_file:s},default:{}}});for(let[e,t]of Object.entries(r.segments))Lc(t)&&`vars`in t&&a.push({path:`segments.${e}.vars`,message:`a plugin segment may not declare "vars": a plugin's only source is its data file`});let u={variables:l,segments:wD(t,Ed(c,r.segments,new Set)),helpers:wD(t,hE(c,r.helpers)),actions:wD(t,ST(c,r.actions))};for(let[e,t]of CD(u))try{kv.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),u}function*CD(e){for(let[t,n]of Object.entries(e.segments??{}))for(let e of[`template`,`bg`,`fg`,`when`]){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))`copy`in n&&(yield[`actions.${t}.copy`,n.copy]),`open`in n&&(yield[`actions.${t}.open`,n.open]),`preset`in n&&n.preset===`delete`&&(yield[`actions.${t}.name`,n.name])}function wD(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${cD}${e}.${t}`,n]))}function TD(e,t,n,r){if(typeof e==`string`&&e!==``)return l.resolve(l.dirname(t),JE(e));if(Lc(e)&&Object.keys(e).length===1&&typeof e.project==`string`&&e.project!==``){let t=e.project;if(l.isAbsolute(t)||t.startsWith(`~`)||l.normalize(t).split(l.sep)[0]===`..`){r.push({path:`data.project`,message:`data.project "${t}" must be a path inside the project, relative to its root (like ".lit/candybar.json"): no absolute path, "~" or ".."`});return}if(n===null){r.push({path:`data.project`,message:`data is read from the session's project, and this load has none`});return}return l.resolve(n,t)}r.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { project: "<path>" } relative to the session's project`})}function ED(e){let t=(process.env.XDG_DATA_DIRS||DD()).split(`:`).filter(e=>e!==``),n=process.env.XDG_DATA_HOME||l.join(h.homedir(),`.local`,`share`),r=[...[...t].reverse().map(e=>l.join(e,`cc-candybar`,`plugins`)),l.join(n,`cc-candybar`,`plugins`),...e===null?[]:[l.join(e,`.cc-candybar`,`plugins`)]];return r.filter((e,t)=>r.lastIndexOf(e)===t)}function DD(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${l.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function OD(e){let t=ED(e),n=new Map,r=[],i=[];for(let e of t){let t=kD(e);if(`error`in t){r.push(t);continue}for(let r of t.folders)n.delete(r),n.set(r,l.join(e,r,aD));for(let n of t.files)i.push({path:l.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${aD}: move this file to ${l.join(e,`<name>`,aD)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function kD(e){try{let t=r.readdirSync(e,{withFileTypes:!0}).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),n=t=>t.isDirectory()||AD(e,t);return{folders:t.filter(n).map(e=>e.name),files:t.filter(e=>!n(e)).map(e=>e.name)}}catch(t){return t.code===`ENOENT`?{folders:[],files:[]}:{path:e,error:t.message}}}function AD(e,t){if(!t.isSymbolicLink())return!1;try{return r.statSync(l.join(e,t.name)).isDirectory()}catch{return!0}}function jD(e,t,n,i){return e===null?{...BD,config:xl(BD.raw,t)}:ND(e,r.readFileSync(e,`utf-8`),t,n,i)}const MD={projectDir:null,beneath:{dropped:[],rendering:new Map}};function ND(e,t,n,r,i){let a=UD(e,t,i,(t,a)=>{let o=pD(fD(t,e),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>RD(t,n,r,e,i)),s=vD(o,r.beneath.dropped);return{inherited:new Set([...Td(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=yD(xl(a.raw,o.config),s);return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(rD)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const PD=new WeakMap;function FD(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e,ID(e)])]),a=PD.get(n)??new Map;PD.set(n,a);let o=String(t.projectDir),s=a.get(o);if(s?.key===i)return s.layer;let c=pD(e,t,{config:n,rendering:new Map},(e,t,n)=>RD(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function ID(e){try{let t=r.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function LD(e,t,n,i,a=e=>r.readFileSync(e,`utf-8`),o){let s=OD(i.projectDir),c=FD(s.definitions,i,t,o),l={...c,dropped:[...c.dropped,...s.strays]};n.warned(s.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let u=l.config,d=[];for(let t of e){n.entered(t);let e=d.at(-1)?.plugins,r=ND(t,a(t),d.at(-1)?.config??u,{...i,beneath:{dropped:[...l.dropped,...d.flatMap(e=>e.plugins.dropped)],rendering:e?.rendering??l.rendering}},o);n.warned(r.warnings),d.push({...r,path:t})}let f=new Set(d.flatMap(e=>[...e.plugins.reached])),p=e=>f.has(e.path),m=l.dropped.filter(p),h=l.dropped.filter(e=>!p(e));n.warned(m.map(rD));let g={roots:s.roots,loaded:l.loaded,dropped:m,unreached:h,reached:f,rendering:d.at(-1)?.plugins.rendering??l.rendering},_=d.at(-1);if(_===void 0)return{layers:d,base:u,installed:g,config:VD(jD(null,u,MD),`<default>`,o)};try{return{layers:d,base:u,installed:g,config:VD(_,_.path,o)}}catch(e){for(let e of d.slice(0,-1))n.entered(e.path),VD(e,e.path,o);throw n.entered(_.path),e}}function RD(e,t,n,r,i){if(n){VD(zD(e),r,i);return}let a=mD(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[]};if(UE(s,e,uy(e),a),WE(s,e,a),o.length>0)throw new nc(r,o)}function zD(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const BD={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function VD({config:e,raw:t,source:n},r=`<config>`,i=new Set(No())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(xE(o,e,t),WE(o,e),a.length>0)throw new nc(r,a);let s=Ov(e,a);if(a.length>0)throw new nc(r,a);return vT(Rw(s))}function HD(e,t,n=new Set(No()),r=WD){return UD(e,t,n,()=>({inherited:r,layer:null})).raw}function UD(e,t,n,r){let i=GD(e,t),a=ac(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(No()),groups:[]};if(!Lc(i))throw new nc(e,[{path:``,message:`Config root must be an object, got ${Rc(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:JD({...c,issues:[]},i.plugins)??[],Lc(i.segments)?Object.keys(i.segments):[]),d=KD(c,i,l);if(s.length>0)throw new nc(e,s,o);return{raw:d,warnings:o,layer:u}}const WD=new Set;function GD(e,t){try{return it.default.parse(t)}catch(t){let n=t;throw new nc(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function KD(e,t,n){for(let n of Object.keys(t))qD.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...qD].join(`, `)}`,line:G(e.source,[n])});let r={};return t.globals!==void 0&&(r.globals=ou(e,`globals`,t.globals)),t.variables!==void 0&&(r.variables=Eu(e,`variables`,t.variables)),t.segments!==void 0&&(r.segments=Ed(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.
165
165
  Replace: layout: [["seg1", "seg2"], ["seg3"]]
166
166
  With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
167
- Single-row example: root: { h: ["seg1", "seg2"] }`,line:G(e.source,[`layout`])}),t.root!==void 0&&(r.root=Yd(e,`root`,t.root)),t.actions!==void 0&&(r.actions=ST(e,t.actions)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:G(e.source,[`looks`])}),t.styles!==void 0&&(r.styles=fE(e,t.styles)),t.presets!==void 0&&(r.presets=mE(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=lu(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=hE(e,t.helpers)),t.plugins!==void 0&&(r.plugins=WD(e,t.plugins)),rf(e,r),Ev(e,r),Hv(e,r),ld(e,r,ad,`the global settings menu`),r}const UD=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`presets`,`editGlobals`,`helpers`,`plugins`]);function WD(e,t){if(Array.isArray(t)&&t.every(e=>typeof e==`string`&&e!==``))return t;e.issues.push({path:`plugins`,message:`"plugins" must be a list of plugin definition paths, got ${Rc(t)}`,line:G(e.source,[`plugins`])})}function GD(e){let t=ZD(e.termCols),n=ZD(e.termRows),r=QD(e.ssh),i=YD(e.tmux),a=JD(e.configEnv),o=qD(e.claudeConfigDir),s=KD(e.mementoEnv);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{mementoEnv:s}}}function KD(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Qe.filter(e=>t[e]!==void 0);return n.every(e=>qD(t[e])!==void 0)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function qD(e){return typeof e==`string`&&l.isAbsolute(e)?e:void 0}function JD(e){return typeof e==`string`&&e!==``?KE(e):void 0}function YD(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 XD=1e4;function ZD(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>XD?XD:t}function QD(e){return typeof e==`boolean`?e:void 0}function $D(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var eO=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function tO(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function nO(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 eO(`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 eO(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function rO(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=nO(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(tO(t))})}async function iO(e,t,n){let r=null;try{r=await lO(Re(),t.connectMs);let i=await rO(r,{v:3,...e},t.budgetMs);return sO(e.kind,i,n)}catch(e){return cO(e)}finally{r&&r.destroy()}}function aO(e,t){return typeof e==`string`?e:t}function oO(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function sO(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=aO(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:oO(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 cO(e){if(e instanceof eO||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 lO(e,t){return new Promise((n,r)=>{let i=x.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 uO(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 dO=`1.119.0`,fO={connectMs:50,budgetMs:150},pO={connectMs:50,budgetMs:200};function mO(e){let t=e.output;return typeof t==`string`?t:void 0}function hO(e,t,n,r){return iO({kind:`render`,hookData:e,args:t,cwd:n,...r},fO,mO)}function gO(e,t){return iO({kind:`click`,verb:e,value:t,clientVersion:dO},pO,mO)}function _O(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(`
168
- `)}function vO(e,t){return e===`darwin`?[yO(`footprint`,[`-p`,String(t)]),yO(`vmmap`,[`--summary`,String(t)])]:e===`linux`?[bO(`/proc/self/smaps_rollup`),bO(`/proc/self/status`)]:[]}function yO(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=k({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}`}${xO(n.stderr)}`}}}}function bO(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 xO(e){let t=e.split(`
169
- `).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const SO=`CC_CANDYBAR_RSS_LIMIT_MB`;function CO(e){let t=e[SO];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${SO} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function wO(e){return CO(e)*2}const TO=1024*1024;function EO(e){return CO(e)*TO}const DO={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function OO(e,t,n){let{prefix:r,suffix:i}=DO[t];return l.join(e,`${r}${n}${i}`)}function kO(e){for(let t of Object.keys(DO)){let{prefix:n,suffix:r}=DO[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function AO(e){let t=e.rssLimitBytes??512*TO,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 jO(e.log,`memory report`,()=>{let t=OO(e.snapshotDir,`memoryReport`,o);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),jO(e.log,`heap snapshot`,()=>{let t=OO(e.snapshotDir,`heapSnapshot`,o);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),jO(e.log,`artifact rotation`,()=>{NO(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 jO(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function MO(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=kO(t);if(n===null)return t;let{prefix:r,suffix:i}=DO[n];return t.slice(r.length,t.length-i.length)}function NO(e,t,n){let r=new Map;for(let t of e){let e=MO(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 PO(e,t,n={}){let i=Le();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:Z,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},captureMemoryReport:()=>_O(vO(process.platform,process.pid)),writeMemoryReport:(e,t)=>r.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>re.writeHeapSnapshot(e),listArtifacts:()=>{try{return r.readdirSync(i).filter(e=>kO(e)!==null).map(e=>l.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function FO(e={}){if(ZO()!==null)return;let n=e.spawn??QO,r=JO();if(r.kind===`contended`){let e=LO();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),IO(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),IO(n);return}try{IO(n)}finally{XO()}}function IO(e){WO()&&RO(e)}function LO(){try{let e=r.statSync(qe());return Date.now()-e.mtimeMs}catch{return null}}function RO(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
170
- `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function zO(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function BO(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function VO(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 HO(e,n){try{r.mkdirSync(l.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 UO(){try{r.unlinkSync(Ye())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function WO(){let e=Je(),n=Ye(),r=VO(n),i=zO(GO(e),BO(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`),KO(e),HO(n,Math.min(r+1,5)),!0)}function GO(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function KO(e){try{r.mkdirSync(l.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 qO=null;function JO(){let e=qe();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 qO={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(!YO(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 YO(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function XO(){if(!qO)return;let{fd:e,path:t}=qO;qO=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function ZO(){try{return r.mkdirSync(Le(),{recursive:!0}),null}catch(e){return`mkdir ${Le()}: ${e.message}`}}function QO(){let e=t.execPath,n=t.argv[1];return n?je({bin:e,args:[`--max-old-space-size=${wO(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const $O=`cc-candybar`,ek=`dispatch`,tk=`set-state`,nk=`step-state`,rk=`copy`,ik=`open-vscode`,ak=`toolbar-toggle`,ok=`show-config-error`,sk=`show-config-warning`,ck=`set-config`,lk=`step-config`,uk=`save`,dk=`save-preset`,fk=`delete-preset`,pk=`reset-config`,mk=`apply-layout-op`,hk=`undo`,gk=`redo`,_k=`back`,vk=`rewind`,yk=`apply-update`,bk=`doctor-run`,xk=`doctor-fix`,Sk=`doctor-probe`,Ck=`ceiling`,wk=`slash`;function Tk(e){return e.map(encodeURIComponent).join(`/`)}function Ek(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function Dk(e){return`${$O}://${ek}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Tk(e.args)}`)}`).join(`&`)}`}function Ok(e){return new T(e).getAll(`e`).map(Mk)}const kk=new Set([tk,pk]);function Ak(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&jk(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function jk(e,t){if(e.verb!==t.verb||!kk.has(e.verb))return;let[n,r]=[Mk(e.value),Mk(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function Mk(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const Nk=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Pk(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Fk(e){return Nk.test(e)?e:Pk(e)}const Ik=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function Lk(e){let t=Ik.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 Rk(e){return e.join(`.`)}function zk([e,t,n],[r,i,a]){return e-r||t-i||n-a}const Bk=`@promptctl/cc-candybar`;async function Vk(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`?Lk(n.latest):Y}catch(e){return X(e instanceof Error?e.message:String(e))}}function Hk(e,t){let n=Lk(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=zk(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 Uk(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${Rk(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${Rk(t.installed)} is newer than the registry's latest release (${Rk(t.latest)}): an unpublished build.\n`};case`stale`:{let n=Rk(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${Rk(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 Wk=`CCCandybarURLHandler`,Gk=[],Kk={"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 qk(e,t){return[e,...t].map(Fk).join(` `)}function Jk(){return l.join(h.homedir(),`Applications`,`${Wk}.app`)}function Yk(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function Xk(){if(process.platform===`darwin`)return l.join(h.homedir(),`Library`,`Application Support`,`CCCandybar`);let e=process.env.XDG_DATA_HOME??l.join(h.homedir(),`.local`,`share`);return l.join(e,`cc-candybar`)}function Zk(){return l.join(Xk(),`bin`,`cc-candybar`)}function Qk(){return l.join(Xk(),`dist`,`index.mjs`)}function $k(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(`
171
- `)}function eA(e){let t=/do shell script "'([^']+)' '([^']+)' url-handle "/.exec(e);if(t===null)return null;let n=e=>e.replace(/\\"/g,`"`);return{node:n(t[1]),script:n(t[2])}}function tA(e){return l.join(e,`Contents`,`Resources`,`Scripts`,`main.scpt`)}function nA(e){if(!e)throw Error(`install: process.argv[1] not set`);return e.endsWith(`.mjs`)||e.endsWith(`.js`)?e:l.resolve(l.dirname(e),`..`,`dist`,`index.mjs`)}function rA(t){let n=Kk[`${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:l.resolve(l.dirname(t),`..`,`bin`,`cc-candybar`)}}function iA(e,t){l.resolve(e)!==l.resolve(t)&&r.copyFileSync(e,t)}function aA(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 ${Bk}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function oA(){let e=nA(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=rA(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(l.dirname(Qk()),{recursive:!0}),r.mkdirSync(l.dirname(Zk()),{recursive:!0}),iA(e,Qk()),iA(t.sourcePath,Zk()),r.chmodSync(Zk(),493),r.rmSync(l.join(Xk(),`url-handler.mjs`),{force:!0});let n=aA(Zk());return process.stdout.write(`Staged cc-candybar v${dO} runtime at ${Xk()}\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:Zk(),distPath:Qk(),entryKind:n}}function sA(){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>${$O}</string>`,` </array>`,` </dict>`,`</array>`].join(`
172
- `)}]}function cA(e){let t=Jk();r.mkdirSync(l.dirname(t),{recursive:!0}),r.existsSync(t)&&r.rmSync(t,{recursive:!0,force:!0}),process.stdout.write(`Building ${t}\n`);let n=k({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,$k(process.execPath,e)],category:`install.osacompile`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`osacompile failed (${n.reason})`);let i=l.join(t,`Contents`,`Info.plist`);for(let{key:e}of sA())k({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of sA()){let n=k({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 ${$O}:// with Launch Services\n`);let a=k({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(`✓ ${Wk}.app installed and registered.\n`),process.stdout.write(` Test: open '${$O}://hello-world' && pbpaste\n`)}function lA(){Yk(),cA(oA().distPath)}function uA(e,t=$O){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:rk,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function dA(e){e||(process.stderr.write(`url-handle: missing URL argument.
173
- `),process.exit(1));let t;try{t=uA(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await gO(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(FO(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(fA(n)+`
174
- `),process.exit(1)}function fA(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 pA(){return`✓ install complete.
167
+ Single-row example: root: { h: ["seg1", "seg2"] }`,line:G(e.source,[`layout`])}),t.root!==void 0&&(r.root=Yd(e,`root`,t.root)),t.actions!==void 0&&(r.actions=ST(e,t.actions)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:G(e.source,[`looks`])}),t.styles!==void 0&&(r.styles=fE(e,t.styles)),t.presets!==void 0&&(r.presets=mE(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=lu(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=hE(e,t.helpers)),t.plugins!==void 0&&(r.plugins=JD(e,t.plugins)),rf(e,r),Ev(e,r),Hv(e,r),ld(e,r,ad,`the global settings menu`),r}const qD=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`presets`,`editGlobals`,`helpers`,`plugins`]);function JD(e,t){if(Array.isArray(t)&&t.every(e=>typeof e==`string`&&e!==``))return t;e.issues.push({path:`plugins`,message:`"plugins" must be a list of plugin definition paths, got ${Rc(t)}`,line:G(e.source,[`plugins`])})}function YD(e){let t=tO(e.termCols),n=tO(e.termRows),r=nO(e.ssh),i=$D(e.tmux),a=QD(e.configEnv),o=ZD(e.claudeConfigDir),s=XD(e.mementoEnv);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{mementoEnv:s}}}function XD(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Qe.filter(e=>t[e]!==void 0);return n.every(e=>ZD(t[e])!==void 0)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function ZD(e){return typeof e==`string`&&l.isAbsolute(e)?e:void 0}function QD(e){return typeof e==`string`&&e!==``?JE(e):void 0}function $D(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 eO=1e4;function tO(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>eO?eO:t}function nO(e){return typeof e==`boolean`?e:void 0}function rO(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var iO=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function aO(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function oO(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 iO(`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 iO(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function sO(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=oO(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(aO(t))})}async function cO(e,t,n){let r=null;try{r=await pO(Re(),t.connectMs);let i=await sO(r,{v:3,...e},t.budgetMs);return dO(e.kind,i,n)}catch(e){return fO(e)}finally{r&&r.destroy()}}function lO(e,t){return typeof e==`string`?e:t}function uO(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function dO(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=lO(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:uO(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 fO(e){if(e instanceof iO||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 pO(e,t){return new Promise((n,r)=>{let i=x.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 mO(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 hO=`1.119.1`,gO={connectMs:50,budgetMs:150},_O={connectMs:50,budgetMs:200};function vO(e){let t=e.output;return typeof t==`string`?t:void 0}function yO(e,t,n,r){return cO({kind:`render`,hookData:e,args:t,cwd:n,...r},gO,vO)}function bO(e,t){return cO({kind:`click`,verb:e,value:t,clientVersion:hO},_O,vO)}function xO(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(`
168
+ `)}function SO(e,t){return e===`darwin`?[CO(`footprint`,[`-p`,String(t)]),CO(`vmmap`,[`--summary`,String(t)])]:e===`linux`?[wO(`/proc/self/smaps_rollup`),wO(`/proc/self/status`)]:[]}function CO(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=k({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}`}${TO(n.stderr)}`}}}}function wO(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 TO(e){let t=e.split(`
169
+ `).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const EO=`CC_CANDYBAR_RSS_LIMIT_MB`;function DO(e){let t=e[EO];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${EO} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function OO(e){return DO(e)*2}const kO=1024*1024;function AO(e){return DO(e)*kO}const jO={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function MO(e,t,n){let{prefix:r,suffix:i}=jO[t];return l.join(e,`${r}${n}${i}`)}function NO(e){for(let t of Object.keys(jO)){let{prefix:n,suffix:r}=jO[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function PO(e){let t=e.rssLimitBytes??512*kO,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 FO(e.log,`memory report`,()=>{let t=MO(e.snapshotDir,`memoryReport`,o);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),FO(e.log,`heap snapshot`,()=>{let t=MO(e.snapshotDir,`heapSnapshot`,o);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),FO(e.log,`artifact rotation`,()=>{LO(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 FO(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function IO(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=NO(t);if(n===null)return t;let{prefix:r,suffix:i}=jO[n];return t.slice(r.length,t.length-i.length)}function LO(e,t,n){let r=new Map;for(let t of e){let e=IO(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 RO(e,t,n={}){let i=Le();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:Z,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},captureMemoryReport:()=>xO(SO(process.platform,process.pid)),writeMemoryReport:(e,t)=>r.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>re.writeHeapSnapshot(e),listArtifacts:()=>{try{return r.readdirSync(i).filter(e=>NO(e)!==null).map(e=>l.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function zO(e={}){if(tk()!==null)return;let n=e.spawn??nk,r=QO();if(r.kind===`contended`){let e=VO();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),BO(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),BO(n);return}try{BO(n)}finally{ek()}}function BO(e){JO()&&HO(e)}function VO(){try{let e=r.statSync(qe());return Date.now()-e.mtimeMs}catch{return null}}function HO(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
170
+ `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function UO(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function WO(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function GO(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 KO(e,n){try{r.mkdirSync(l.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 qO(){try{r.unlinkSync(Ye())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function JO(){let e=Je(),n=Ye(),r=GO(n),i=UO(YO(e),WO(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`),XO(e),KO(n,Math.min(r+1,5)),!0)}function YO(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function XO(e){try{r.mkdirSync(l.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 ZO=null;function QO(){let e=qe();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 ZO={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(!$O(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 $O(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function ek(){if(!ZO)return;let{fd:e,path:t}=ZO;ZO=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function tk(){try{return r.mkdirSync(Le(),{recursive:!0}),null}catch(e){return`mkdir ${Le()}: ${e.message}`}}function nk(){let e=t.execPath,n=t.argv[1];return n?je({bin:e,args:[`--max-old-space-size=${OO(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const rk=`cc-candybar`,ik=`dispatch`,ak=`set-state`,ok=`step-state`,sk=`copy`,ck=`open-vscode`,lk=`toolbar-toggle`,uk=`show-config-error`,dk=`show-config-warning`,fk=`set-config`,pk=`step-config`,mk=`save`,hk=`save-preset`,gk=`delete-preset`,_k=`reset-config`,vk=`apply-layout-op`,yk=`undo`,bk=`redo`,xk=`back`,Sk=`rewind`,Ck=`apply-update`,wk=`doctor-run`,Tk=`doctor-fix`,Ek=`doctor-probe`,Dk=`ceiling`,Ok=`slash`;function kk(e){return e.map(encodeURIComponent).join(`/`)}function Ak(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function jk(e){return`${rk}://${ik}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${kk(e.args)}`)}`).join(`&`)}`}function Mk(e){return new T(e).getAll(`e`).map(Ik)}const Nk=new Set([ak,_k]);function Pk(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&Fk(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function Fk(e,t){if(e.verb!==t.verb||!Nk.has(e.verb))return;let[n,r]=[Ik(e.value),Ik(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function Ik(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const Lk=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Rk(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function zk(e){return Lk.test(e)?e:Rk(e)}const Bk=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function Vk(e){let t=Bk.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 Hk(e){return e.join(`.`)}function Uk([e,t,n],[r,i,a]){return e-r||t-i||n-a}const Wk=`@promptctl/cc-candybar`;async function Gk(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`?Vk(n.latest):Y}catch(e){return X(e instanceof Error?e.message:String(e))}}function Kk(e,t){let n=Vk(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=Uk(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 qk(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${Hk(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${Hk(t.installed)} is newer than the registry's latest release (${Hk(t.latest)}): an unpublished build.\n`};case`stale`:{let n=Hk(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${Hk(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 Jk=`CCCandybarURLHandler`,Yk=[],Xk={"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 Zk(e,t){return[e,...t].map(zk).join(` `)}function Qk(){return l.join(h.homedir(),`Applications`,`${Jk}.app`)}function $k(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function eA(){if(process.platform===`darwin`)return l.join(h.homedir(),`Library`,`Application Support`,`CCCandybar`);let e=process.env.XDG_DATA_HOME??l.join(h.homedir(),`.local`,`share`);return l.join(e,`cc-candybar`)}function tA(){return l.join(eA(),`bin`,`cc-candybar`)}function nA(){return l.join(eA(),`dist`,`index.mjs`)}function rA(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(`
171
+ `)}function iA(e){let t=/do shell script "'([^']+)' '([^']+)' url-handle "/.exec(e);if(t===null)return null;let n=e=>e.replace(/\\"/g,`"`);return{node:n(t[1]),script:n(t[2])}}function aA(e){return l.join(e,`Contents`,`Resources`,`Scripts`,`main.scpt`)}function oA(e){if(!e)throw Error(`install: process.argv[1] not set`);return e.endsWith(`.mjs`)||e.endsWith(`.js`)?e:l.resolve(l.dirname(e),`..`,`dist`,`index.mjs`)}function sA(t){let n=Xk[`${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:l.resolve(l.dirname(t),`..`,`bin`,`cc-candybar`)}}function cA(e,t){l.resolve(e)!==l.resolve(t)&&r.copyFileSync(e,t)}function lA(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 ${Wk}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function uA(){let e=oA(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=sA(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(l.dirname(nA()),{recursive:!0}),r.mkdirSync(l.dirname(tA()),{recursive:!0}),cA(e,nA()),cA(t.sourcePath,tA()),r.chmodSync(tA(),493),r.rmSync(l.join(eA(),`url-handler.mjs`),{force:!0});let n=lA(tA());return process.stdout.write(`Staged cc-candybar v${hO} runtime at ${eA()}\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:tA(),distPath:nA(),entryKind:n}}function dA(){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>${rk}</string>`,` </array>`,` </dict>`,`</array>`].join(`
172
+ `)}]}function fA(e){let t=Qk();r.mkdirSync(l.dirname(t),{recursive:!0}),r.existsSync(t)&&r.rmSync(t,{recursive:!0,force:!0}),process.stdout.write(`Building ${t}\n`);let n=k({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,rA(process.execPath,e)],category:`install.osacompile`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`osacompile failed (${n.reason})`);let i=l.join(t,`Contents`,`Info.plist`);for(let{key:e}of dA())k({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of dA()){let n=k({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 ${rk}:// with Launch Services\n`);let a=k({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(`✓ ${Jk}.app installed and registered.\n`),process.stdout.write(` Test: open '${rk}://hello-world' && pbpaste\n`)}function pA(){$k(),fA(uA().distPath)}function mA(e,t=rk){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:sk,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function hA(e){e||(process.stderr.write(`url-handle: missing URL argument.
173
+ `),process.exit(1));let t;try{t=mA(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await bO(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(zO(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(gA(n)+`
174
+ `),process.exit(1)}function gA(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 _A(){return`✓ install complete.
175
175
  Restart Claude Code to pick up the new statusline.
176
- Tip: every bar carries a settings menu — click it (${El} by\n default) for quick actions, preset switching, edit mode, and clickable\n theme/style/variation/endcaps/wrap/padding controls.\n`}async function mA(e){let t=e.includes(`--force`),n=e.filter(e=>e!==`--force`),r=n.length>0?n:[...Gk],i=oA();process.platform===`darwin`?cA(i.distPath):process.stdout.write(`Skipping URL handler (cmd-click verbs are macOS-only).
177
- `),hA(i.binPath,r,t),process.stdout.write(pA());let a=Uk(Bk,Hk(dO,await Vk(Bk,fetch,`https://registry.npmjs.org`)));process[a.stream].write(a.text)}function hA(e,t,n,i){let a=i??aC(iC(rC(process.env,process.cwd())));r.mkdirSync(l.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,c=[e,Fk(e),Pk(e)],u=typeof s==`string`&&(s.startsWith(`pnpm dlx @promptctl/cc-candybar@`)||c.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:qk(e,t)},Ne(a,JSON.stringify(o,null,2)),process.stdout.write(`Updated ${a}\n`)}function gA(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 _A(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 vA(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 yA(e,t){let n=_A(e);if(n.kind===`owned`&&n.pid===t)try{r.unlinkSync(e)}catch{}}function bA(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 xA(e,t,n,r){let i=SA(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 SA(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 CA(e){let t=!1;function n(){let n=xA(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 wA(e,t=k){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 TA(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 EA(e,t=wA){let n=t(e);return n.kind===`start`?n.token:null}const DA=`CC_CANDYBAR_PARENT_PID`;function OA(e){let t=e[DA];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${DA} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function kA(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 AA(e){try{return t.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function jA(){let e=Number(process.env.CC_CANDYBAR_DAEMON_CEILING??``);return Number.isInteger(e)&&e>0?e:16}function MA(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 NA(e){try{return r.readdirSync(e).filter(e=>e.endsWith(`.json`)).map(t=>l.join(e,t))}catch{return[]}}function PA(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 FA(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 IA(e){if(!e.isolated)return{decision:MA(!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=MA(!0,FA(t,e.isSameLiveProcess,e.removeFile),e.ceiling);if(!n.allow)return{decision:n,registryPath:null};let r=l.join(e.registryDir,`pid-${e.pid}.json`);return e.writeEntry(r,{pid:e.pid,startTime:e.startTime}),{decision:n,registryPath:r}}function LA(e,t,n,r){let i=n(e);if(i!==null&&i.pid===t)try{r(e)}catch{}}function RA(e,t={}){return{isolated:!!process.env.CC_CANDYBAR_SOCKET,registryDir:Ke(),ceiling:jA(),pid:process.pid,startTime:e,isSameLiveProcess:(e,t)=>TA(e,t,{readStartTime:wA,pidAlive:AA}),listFiles:NA,readEntry:PA,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?Be:e=>{Be(l.dirname(e)),Be(e)},...t}}function zA(e){return e<32||e===127||e>=128&&e<=159}function BA(e){let t=``;for(let n of e)t+=zA(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function VA(e,t){let n=BA(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const HA=`\x1B[38;2;255;255;255m`,UA=`\x1B[48;2;200;40;40m`;function WA(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 GA={fg:WA(HA),bg:WA(UA)},KA={fg:WA(`\x1B[38;2;0;0;0m`),bg:WA(`\x1B[48;2;220;160;40m`)},qA=new yi;function JA(e){return qA.resolve(e)}function YA(e,t){return ka(e,{...t,theme:qA,onStyleError:e=>{throw e}})}const XA={unicode:ya,ascii:{glyph:`>`,divider:`|`,lead:`<`,tail:`>`}},ZA={unicode:{},ascii:{left:`(`,right:`)`}};function QA(e,t,n){switch(e){case`capsule`:return new Ta(ZA[t]);case`plain`:return new Ea(n===void 0?{}:{separator:n});case`powerline`:return new Sa(XA[t]);default:return e}}const $A=new Map;function ej(e){let t=JSON.stringify([e.endcaps,e.charset,e.separator??null]),n=$A.get(t);if(n!==void 0)return n;let r=QA(e.endcaps,e.charset,e.separator),i=e=>new W(`x`,{end:``,overflow:`ignore`,style:new V({bgcolor:e})}),a=e=>new W(YA(new da(e,r),{colorSystem:null}).replace(/\n$/,``)).cellLength,o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return $A.set(t,s),s}function tj(e){return ej(e).chrome}function nj(e){return ej(e).seam}function rj(e,t){if(e.length===0)return``;let n=QA(t.endcaps,t.charset,t.separator),r=t.colorCompatibility,i=t.wrap&&Number.isFinite(t.width)?YA(new Fa([...e],{joiner:n}),{width:t.width,colorSystem:r}):YA(new da([...e],n),{colorSystem:r});if(!i.endsWith(`
178
- `))throw Error(`renderStripCells: rich-js strip output did not end its last line`);return i.slice(0,-1)}function ij(e){return Math.min(20,e??20)}const aj={heading:`ERROR`,glyph:`⚠`,colors:GA},oj={heading:`WARNING`,glyph:`⚠`,colors:KA},sj={heading:`UPDATE`,glyph:`⬆`,colors:KA};function cj(e,t){return{text:BA(e),link:t}}function lj(e,t,n){let[r,...i]=[uj(e,aj,ok),t,uj(n,oj,sk)].flat();return r===void 0?null:{channels:[r,...i]}}function uj(e,t,n){let r=Dk([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>cj(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function dj(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
179
- `)}function fj(e,t,n,r){if(t===null)return e;let i=pj(r),a=t.channels.flatMap(e=>mj(e,i)),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[hj(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
180
- `);return e?`${l}\n${e}`:l}function pj(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function mj(e,t){let n=new V({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=Gt(Math.max(2,t.width-1)),i=(e,t)=>new W(`${e} `,{style:t,end:``,overflow:`ignore`});return e.lines.flatMap((a,o)=>rj([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=>Xt(e,r)).map(e=>i(e,t))})],t).split(`
181
- `))}function hj(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new V({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new W(e,{style:t,end:``,overflow:`ignore`}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(ae(a.path).href)):c(`full text unavailable: ${BA(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(BA(o),s.withLink(ae(o).href))],d=[c(`↳ `,s),...l,...u.slice(0,-1)],f=d.reduce((e,t)=>e+t.cellLength,0),p=u.slice(-1).map(e=>e.truncate(Math.max(1,r.width-f),{mode:`middle`})),m=W.fromFragments([...d,...p]).truncate(r.width);return m.overflow=`ignore`,rj([m],r)}const gj=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function _j(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function vj(e,t){return r.readdirSync(t).filter(gj).sort().flatMap(n=>{let i=l.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?vj(e,i):[[l.relative(e,i).split(l.sep).join(`/`),_j(i,a)]]})}function yj(e){let t=oe.createHash(`sha256`);for(let[n,r]of vj(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const bj=e=>e.slice(0,7);function xj(e){return l.dirname(l.dirname(e))}function Sj(){return{version:dO,digest:`e4c7761b67e257619e95450e4afb412db494e92eff074ff6949e498df3ae22f6`}}function Cj(e){let t=JSON.parse(r.readFileSync(l.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${l.join(e,`package.json`)} has no version string`);return n}function wj(e,t){try{let n=xj(E(e)),i=l.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=yj(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:Cj(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var $=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};function Tj(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function Ej(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 Dj(e,t,n){let r=dc(e,new Set(n.map(uc).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const Oj=/^-?\d+$/;function kj(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 Aj(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!Oj.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 jj(e,t,n){return r=>r?Oj.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 Mj(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=>!Oj.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 Nj(e){return e===`config`?`set-config`:`set-state`}function Pj(e,t,n){return t.kind===`int`?Aj(`menu page "${e}"`):t.kind===`range`?jj(t.min,t.max,`${n} stepper "${e}"`):kj(t.allowed,`${n} "${e}"`,Nj(n))}function Fj(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:Mj(e,n,t)}))}function Ij(e,t,n,r){let i=new Map(Object.entries(e)),a=new Map,o=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of n)if(o.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let s=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...n];for(let{key:t,spec:n}of Fj(s,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,Pj(t,n,r)),n.kind===`range`&&a.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>a.get(e)??null}}function Lj(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};Ij(e,[o],[],t),r.push(o),i++;let s=!0;return()=>{s&&(s=!1,r.splice(r.indexOf(o),1),i++)}},gateFor(o){let s=a.get(o);if(s?.epoch===i)return s.gate;let c=Ij(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const Rj=Lj({},`config`,Gj);function zj(e,t){return Rj.register(e,t)}function Bj(e){return Rj.gateFor(e)}function Vj(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:eS(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:[Tj({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[Tj({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:eS(e.insertSegmentFrom,t).members.map(t=>Tj({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function Hj(e,t){let n=mu(e).get(t);return n===void 0?null:String(n)}function Uj(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?mS(n.persist):null;e?.scope===`preset-root`&&t.add(fS(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function Wj(e){let t=eT(e);return[...Uj(e),...Object.values(e.actions).flatMap(e=>Vj(e,t))]}function Gj(e){return Fj(Wj(e),`config`)}const Kj=nC(`commands.`),qj=hC(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),Jj=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,Yj=`{{ \$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 (${Jj}) (basename .project_dir) (ne (${Jj}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,Xj=`{{ ${DS} }}`,Zj={min:0,max:100,step:5},Qj={warnAt:{label:`warning at %`,domain:Zj,default:50},errorAt:{label:`error at %`,domain:{...Zj,atLeast:`warnAt`},default:80}};function $j(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:Zj,default:80}}}const eM={globals:{palette:`tokyo-night`},variables:{...Kj.variables,...Ex,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},version:{kind:`input`,path:`version`,default:``},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"memento.ceiling":{kind:`input`,path:`memento.ceiling`,type:`number`,default:-1},"memento.off":{kind:`input`,path:`memento.off`,type:`boolean`,default:!1},"memento.session":{kind:`input`,path:`memento.session`,default:``},"memento.error":{kind:`input`,path:`memento.error`,default:``},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``},"activity.ticket.id":{kind:`input`,path:`activity.ticket.id`,type:`string`,default:``},"activity.ticket.phase":{kind:`input`,path:`activity.ticket.phase`,type:`string`,default:``},"activity.ticket.epic.done":{kind:`input`,path:`activity.ticket.epic.done`,type:`number`,default:0},"activity.ticket.epic.total":{kind:`input`,path:`activity.ticket.epic.total`,type:`number`,default:0},"activity.ticket.unread":{kind:`input`,path:`activity.ticket.unread`,type:`string`,default:``},"ticket.detail":{kind:`state`,key:`ticket-detail`,default:`collapsed`}},segments:{directory:{group:`location`,description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:Yj},model:{group:`model-context`,description:`The active model's display name.`,template:`✱ {{ formatModelName .model.display_name }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{group:`session-tools`,description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{group:`model-context`,description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{group:`location`,description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{group:`location`,description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{group:`git`,description:`The git state: a summary (branch, ahead/behind, S/U/? flags) that the arrow at its right edge expands to every fact — repo, in-progress operation, sha, upstream ±, stash count, time since the last commit.`,template:`{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}`,fg:Xj,when:`{{ ne .git.branch "" }}`,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if ne .git.prUrl "" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (ne .git.prUrl "") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:GS(``).template},commands:{group:`session-tools`,description:`Type /compact, /model or /clear into this session; /clear asks for a second click. Hidden when not inside tmux.`,template:Kj.template,when:Kj.when},themeSwitcher:{group:`session-tools`,description:"`◀ <theme> ▶`: the theme the bar is wearing; ◀ and ▶ switch this session to the previous or next theme, wrapping at the ends.",template:`{{ carousel "stepTheme" 0 }}`},session:{group:`cost-limits`,description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:$j(0)},today:{group:`cost-limits`,description:`Today's cost and tokens across every session, with a budget warning once a budget is configured.`,template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:$j(50)},block:{group:`cost-limits`,description:`The 5-hour rate-limit block: percent used and time to reset, heating to warning then error.`,template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:Qj,when:`{{ gt .block.resetsAt 0 }}`},weekly:{group:`cost-limits`,description:`The weekly rate-limit quota: percent used and time to reset, heating to warning then error.`,template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:Qj,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{group:`cost-limits`,description:`Spend per hour, with the projected time to the 5-hour and weekly limits.`,template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 (tint) 0 "error" .settings.errorWithin "warning" .settings.warnWithin (tint) }}`,settings:{errorWithin:{label:`error within (min)`,domain:{min:0,max:300,step:5},default:30},warnWithin:{label:`warning within (min)`,domain:{min:0,max:300,step:5,atLeast:`errorWithin`},default:60}},when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{group:`activity`,description:`Token throughput for the latest exchange: output, input, and total.`,template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{group:`activity`,description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,when:`{{ ne .speed.history "" }}`},cacheTimer:{group:`activity`,description:"Minutes until the prompt cache expires, or `cold` once it has.",template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ readableOn (color (cascade (minutesUntilReset .cache.expiresAt) "0:error" "9:warning" "21:foreground")) (bgOf) ${lo} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},ceiling:{group:`model-context`,description:`The memento plugin's context ceiling for this session: − and + move it by 100K, ∞ lifts it, ↺ drops this session's own setting.`,template:`{{ if ne .memento.error "" }}⌈ ⚠ {{ .memento.error }} {{ action "ceiling.clear" "↺" }}{{ else }}⌈ {{ if .memento.off }}off{{ else }}{{ template "formatTokenCount" .memento.ceiling }} {{ action "ceiling.lower" "−" }} {{ action "ceiling.raise" "+" }} {{ action "ceiling.off" "∞" }}{{ end }}{{ if ne .memento.session "" }} {{ action "ceiling.clear" "↺" }}{{ end }}{{ end }}`,bg:`{{ if ne .memento.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .memento.ceiling 0) (ne .memento.error "") }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:qj.template,bg:qj.bg,when:qj.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},ticket:{group:`activity`,description:`The lit ticket this session started; expands to its workflow phase and its epic's done/total.`,template:`🎫 {{ action "copyTicket" .activity.ticket.id }}{{ if eq .ticket.detail "expanded" }} · {{ .activity.ticket.phase }}{{ if .activity.ticket.epic.total }} · epic {{ .activity.ticket.epic.done }}/{{ .activity.ticket.epic.total }}{{ end }}{{ if .activity.ticket.unread }} · ⚠ unreadable {{ abbrev 40 .activity.ticket.unread }}{{ end }}{{ end }} {{ action "ticketDetail" "▸" "◂" }}`,when:`{{ ne .activity.ticket.id "" }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`ticket`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...GS(``).actions,...Kj.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},ticketDetail:{set:`ticket-detail`,cycle:[`collapsed`,`expanded`]},copyTicket:{copy:`{{ .activity.ticket.id }}`},"ceiling.raise":{ceiling:`set`,to:`+100_000`},"ceiling.lower":{ceiling:`set`,to:`-100_000`},"ceiling.off":{ceiling:`set`,to:`off`},"ceiling.clear":{ceiling:`clear`},...qj.actions},styles:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${lo}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ if and .settings.age (gt .git.timeSinceCommit 0) }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:gC(`.`),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 .)) }}`}},tM=new Set([eM.globals.palette,...Object.values(eM.segments).map(e=>e.palette)].filter(e=>e!==void 0)),nM=xl(RD(`<default>`,JSON.stringify(eM),tM),eM),rM=fv(nM.presets);function iM(e){return rM.includes(e)}function aM(e){if(!e)return 0;try{return s(e).mtimeMs}catch{return 0}}const oM=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 sM(e){return((...t)=>oM.run(()=>e(...t)))}const cM=sM(w),lM=sM(C),uM=sM(ee);async function dM(e,t){return oM.run(async()=>{let n=null;try{n=await S(e,`r`);let{size:r,mtimeMs:i,ino:a}=await n.stat(),o=t!==void 0&&(a!==t.ino||r<t.offset),s=o||t===void 0?0:t.offset;if(s>=r)return J({buf:Buffer.alloc(0),start:s,size:r,mtimeMs:i,ino:a,reset:o});let c=Buffer.alloc(r-s),l=0;for(;l<c.length;){let{bytesRead:e}=await n.read(c,l,c.length-l,s+l);if(e===0)break;l+=e}return J({buf:l===c.length?c:c.subarray(0,l),start:s,size:r,mtimeMs:i,ino:a,reset:o})}catch(t){return t.code===`ENOENT`?Y:X(`readAppended ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{O(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}async function fM(e,t){return oM.run(async()=>{let n=null;try{n=await S(e,`r`);let{size:r}=await n.stat(),i=Math.max(0,r-t),a=Buffer.alloc(r-i),o=0;for(;o<a.length;){let{bytesRead:e}=await n.read(a,o,a.length-o,i+o);if(e===0)break;o+=e}return J({buf:o===a.length?a:a.subarray(0,o),fromStart:i===0})}catch(t){return t.code===`ENOENT`?Y:X(`readTail ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{O(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}const pM=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function mM(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 hM(e){let t=await gM(e);return t.kind===`ok`?J(Math.floor((t.value+36e5)/1e3)):t}async function gM(e){for(let t of[65536,1048576]){let n=await fM(e,t);if(n.kind!==`ok`)return n;let r=_M(n.value.buf,n.value.fromStart);if(r!=null)return J(r);if(n.value.fromStart)return Y}return Y}function _M(e,t){let n=e.toString(`utf8`).split(`
182
- `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!pM.test(t))continue;let r=mM(t);if(r!=null)return r}return null}function vM(e,t){return{...e,claudeConfigDir:iC(t.claudeConfigDir),env:t.mementoEnv}}const yM=l.join(`lib`,`ceiling_config.py`),bM=l.join(`skills`,`ceiling`,`bin`,`ceiling`);function xM(e,t){let n=typeof e==`object`&&e?e.plugins:void 0;if(typeof n!=`object`||!n)throw Error(`${t} has no "plugins" object`);return Object.entries(n).filter(([e])=>e.split(`@`)[0]===`memento`).flatMap(([e,n])=>{if(!Array.isArray(n))throw Error(`${t}: "${e}" is not a list of installs`);return n.map(n=>{let{scope:r,installPath:i,projectPath:a}=n??{};if(typeof r!=`string`||typeof i!=`string`)throw Error(`${t}: an install of "${e}" has no scope/path`);return typeof a==`string`?{key:e,scope:r,installPath:i,projectPath:a}:{key:e,scope:r,installPath:i}})})}function SM(e,t){let n=!0;for(let i of e){if(!r.existsSync(i))continue;let e;try{e=JSON.parse(r.readFileSync(i,`utf8`))?.enabledPlugins?.[t]}catch(e){return X(`memento lookup: ${i}: ${e.message}`)}typeof e==`boolean`&&(n=e)}return J(n)}function CM(e,t){if(!r.existsSync(e))return Y;let n;try{n=xM(JSON.parse(r.readFileSync(e,`utf8`)),e)}catch(e){return X(`memento lookup: ${e.message}`)}let i=n.find(e=>e.projectPath===t)??n.find(e=>e.scope===`user`);if(i===void 0)return Y;let a=SM([l.join(l.dirname(l.dirname(e)),`settings.json`),l.join(t,`.claude`,`settings.json`),l.join(t,`.claude`,`settings.local.json`)],i.key);if(a.kind!==`ok`)return a;if(!a.value)return Y;let o=[yM,bM].filter(e=>!r.existsSync(l.join(i.installPath,e)));return o.length===0?J(i.installPath):X(`memento at ${i.installPath} has no ${o.join(` or `)} — upgrade the plugin`)}function wM(e,t=process.env){let n=new Set([`CLAUDE_PROJECT_DIR`,`CLAUDE_CODE_SESSION_ID`,...e.env===void 0?[]:Qe]);return{...Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e))),...e.env,CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir||e.cwd}}function TM(e){return e.stderr.trim()||e.error||`${e.reason}${e.exitCode===null?``:` (exit ${e.exitCode})`}`}function EM(e){let t;try{t=JSON.parse(e)}catch{return X(`memento read: not JSON: ${e.trim()}`)}let{ceiling:n,session:r}=t??{},i=n===`off`||typeof n==`number`&&n>=0?n:void 0;return i!==void 0&&(r===null||typeof r==`string`)?J({ceiling:i,session:r}):X(`memento read: unexpected answer: ${e.trim()}`)}async function DM(e,t){let n=await Ae({bin:`python3`,args:[`-c`,`
176
+ Tip: every bar carries a settings menu — click it (${El} by\n default) for quick actions, preset switching, edit mode, and clickable\n theme/style/variation/endcaps/wrap/padding controls.\n`}async function vA(e){let t=e.includes(`--force`),n=e.filter(e=>e!==`--force`),r=n.length>0?n:[...Yk],i=uA();process.platform===`darwin`?fA(i.distPath):process.stdout.write(`Skipping URL handler (cmd-click verbs are macOS-only).
177
+ `),yA(i.binPath,r,t),process.stdout.write(_A());let a=qk(Wk,Kk(hO,await Gk(Wk,fetch,`https://registry.npmjs.org`)));process[a.stream].write(a.text)}function yA(e,t,n,i){let a=i??aC(iC(rC(process.env,process.cwd())));r.mkdirSync(l.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,c=[e,zk(e),Rk(e)],u=typeof s==`string`&&(s.startsWith(`pnpm dlx @promptctl/cc-candybar@`)||c.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:Zk(e,t)},Ne(a,JSON.stringify(o,null,2)),process.stdout.write(`Updated ${a}\n`)}function bA(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 xA(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 SA(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 CA(e,t){let n=xA(e);if(n.kind===`owned`&&n.pid===t)try{r.unlinkSync(e)}catch{}}function wA(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 TA(e,t,n,r){let i=EA(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 EA(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 DA(e){let t=!1;function n(){let n=TA(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 OA(e,t=k){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 kA(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 AA(e,t=OA){let n=t(e);return n.kind===`start`?n.token:null}const jA=`CC_CANDYBAR_PARENT_PID`;function MA(e){let t=e[jA];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${jA} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function NA(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 PA(e){try{return t.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function FA(){let e=Number(process.env.CC_CANDYBAR_DAEMON_CEILING??``);return Number.isInteger(e)&&e>0?e:16}function IA(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 LA(e){try{return r.readdirSync(e).filter(e=>e.endsWith(`.json`)).map(t=>l.join(e,t))}catch{return[]}}function RA(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 zA(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 BA(e){if(!e.isolated)return{decision:IA(!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=IA(!0,zA(t,e.isSameLiveProcess,e.removeFile),e.ceiling);if(!n.allow)return{decision:n,registryPath:null};let r=l.join(e.registryDir,`pid-${e.pid}.json`);return e.writeEntry(r,{pid:e.pid,startTime:e.startTime}),{decision:n,registryPath:r}}function VA(e,t,n,r){let i=n(e);if(i!==null&&i.pid===t)try{r(e)}catch{}}function HA(e,t={}){return{isolated:!!process.env.CC_CANDYBAR_SOCKET,registryDir:Ke(),ceiling:FA(),pid:process.pid,startTime:e,isSameLiveProcess:(e,t)=>kA(e,t,{readStartTime:OA,pidAlive:PA}),listFiles:LA,readEntry:RA,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?Be:e=>{Be(l.dirname(e)),Be(e)},...t}}function UA(e){return e<32||e===127||e>=128&&e<=159}function WA(e){let t=``;for(let n of e)t+=UA(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function GA(e,t){let n=WA(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const KA=`\x1B[38;2;255;255;255m`,qA=`\x1B[48;2;200;40;40m`;function JA(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 YA={fg:JA(KA),bg:JA(qA)},XA={fg:JA(`\x1B[38;2;0;0;0m`),bg:JA(`\x1B[48;2;220;160;40m`)},ZA=new yi;function QA(e){return ZA.resolve(e)}function $A(e,t){return ka(e,{...t,theme:ZA,onStyleError:e=>{throw e}})}const ej={unicode:ya,ascii:{glyph:`>`,divider:`|`,lead:`<`,tail:`>`}},tj={unicode:{},ascii:{left:`(`,right:`)`}};function nj(e,t,n){switch(e){case`capsule`:return new Ta(tj[t]);case`plain`:return new Ea(n===void 0?{}:{separator:n});case`powerline`:return new Sa(ej[t]);default:return e}}const rj=new Map;function ij(e){let t=JSON.stringify([e.endcaps,e.charset,e.separator??null]),n=rj.get(t);if(n!==void 0)return n;let r=nj(e.endcaps,e.charset,e.separator),i=e=>new W(`x`,{end:``,overflow:`ignore`,style:new V({bgcolor:e})}),a=e=>new W($A(new da(e,r),{colorSystem:null}).replace(/\n$/,``)).cellLength,o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return rj.set(t,s),s}function aj(e){return ij(e).chrome}function oj(e){return ij(e).seam}function sj(e,t){if(e.length===0)return``;let n=nj(t.endcaps,t.charset,t.separator),r=t.colorCompatibility,i=t.wrap&&Number.isFinite(t.width)?$A(new Fa([...e],{joiner:n}),{width:t.width,colorSystem:r}):$A(new da([...e],n),{colorSystem:r});if(!i.endsWith(`
178
+ `))throw Error(`renderStripCells: rich-js strip output did not end its last line`);return i.slice(0,-1)}function cj(e){return Math.min(20,e??20)}const lj={heading:`ERROR`,glyph:`⚠`,colors:YA},uj={heading:`WARNING`,glyph:`⚠`,colors:XA},dj={heading:`UPDATE`,glyph:`⬆`,colors:XA};function fj(e,t){return{text:WA(e),link:t}}function pj(e,t,n){let[r,...i]=[mj(e,lj,uk),t,mj(n,uj,dk)].flat();return r===void 0?null:{channels:[r,...i]}}function mj(e,t,n){let r=jk([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>fj(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function hj(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
179
+ `)}function gj(e,t,n,r){if(t===null)return e;let i=_j(r),a=t.channels.flatMap(e=>vj(e,i)),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[yj(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
180
+ `);return e?`${l}\n${e}`:l}function _j(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function vj(e,t){let n=new V({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=Gt(Math.max(2,t.width-1)),i=(e,t)=>new W(`${e} `,{style:t,end:``,overflow:`ignore`});return e.lines.flatMap((a,o)=>sj([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=>Xt(e,r)).map(e=>i(e,t))})],t).split(`
181
+ `))}function yj(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new V({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new W(e,{style:t,end:``,overflow:`ignore`}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(ae(a.path).href)):c(`full text unavailable: ${WA(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(WA(o),s.withLink(ae(o).href))],d=[c(`↳ `,s),...l,...u.slice(0,-1)],f=d.reduce((e,t)=>e+t.cellLength,0),p=u.slice(-1).map(e=>e.truncate(Math.max(1,r.width-f),{mode:`middle`})),m=W.fromFragments([...d,...p]).truncate(r.width);return m.overflow=`ignore`,sj([m],r)}const bj=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function xj(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function Sj(e,t){return r.readdirSync(t).filter(bj).sort().flatMap(n=>{let i=l.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?Sj(e,i):[[l.relative(e,i).split(l.sep).join(`/`),xj(i,a)]]})}function Cj(e){let t=oe.createHash(`sha256`);for(let[n,r]of Sj(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const wj=e=>e.slice(0,7);function Tj(e){return l.dirname(l.dirname(e))}function Ej(){return{version:hO,digest:`fdf209a07d6147c214f8679197840d280a9389c7fee955acb15100f0dceced72`}}function Dj(e){let t=JSON.parse(r.readFileSync(l.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${l.join(e,`package.json`)} has no version string`);return n}function Oj(e,t){try{let n=Tj(E(e)),i=l.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=Cj(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:Dj(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var $=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};function kj(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function Aj(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 jj(e,t,n){let r=dc(e,new Set(n.map(uc).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const Mj=/^-?\d+$/;function Nj(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 Pj(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!Mj.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 Fj(e,t,n){return r=>r?Mj.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 Ij(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=>!Mj.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 Lj(e){return e===`config`?`set-config`:`set-state`}function Rj(e,t,n){return t.kind===`int`?Pj(`menu page "${e}"`):t.kind===`range`?Fj(t.min,t.max,`${n} stepper "${e}"`):Nj(t.allowed,`${n} "${e}"`,Lj(n))}function zj(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:Ij(e,n,t)}))}function Bj(e,t,n,r){let i=new Map(Object.entries(e)),a=new Map,o=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of n)if(o.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let s=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...n];for(let{key:t,spec:n}of zj(s,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,Rj(t,n,r)),n.kind===`range`&&a.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>a.get(e)??null}}function Vj(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};Bj(e,[o],[],t),r.push(o),i++;let s=!0;return()=>{s&&(s=!1,r.splice(r.indexOf(o),1),i++)}},gateFor(o){let s=a.get(o);if(s?.epoch===i)return s.gate;let c=Bj(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const Hj=Vj({},`config`,Yj);function Uj(e,t){return Hj.register(e,t)}function Wj(e){return Hj.gateFor(e)}function Gj(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:eS(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:[kj({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[kj({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:eS(e.insertSegmentFrom,t).members.map(t=>kj({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function Kj(e,t){let n=mu(e).get(t);return n===void 0?null:String(n)}function qj(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?mS(n.persist):null;e?.scope===`preset-root`&&t.add(fS(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function Jj(e){let t=eT(e);return[...qj(e),...Object.values(e.actions).flatMap(e=>Gj(e,t))]}function Yj(e){return zj(Jj(e),`config`)}const Xj=nC(`commands.`),Zj=hC(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),Qj=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,$j=`{{ \$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 (${Qj}) (basename .project_dir) (ne (${Qj}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,eM=`{{ ${DS} }}`,tM={min:0,max:100,step:5},nM={warnAt:{label:`warning at %`,domain:tM,default:50},errorAt:{label:`error at %`,domain:{...tM,atLeast:`warnAt`},default:80}};function rM(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:tM,default:80}}}const iM={globals:{palette:`tokyo-night`},variables:{...Xj.variables,...Ex,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},version:{kind:`input`,path:`version`,default:``},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"memento.ceiling":{kind:`input`,path:`memento.ceiling`,type:`number`,default:-1},"memento.off":{kind:`input`,path:`memento.off`,type:`boolean`,default:!1},"memento.session":{kind:`input`,path:`memento.session`,default:``},"memento.error":{kind:`input`,path:`memento.error`,default:``},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``},"activity.ticket.id":{kind:`input`,path:`activity.ticket.id`,type:`string`,default:``},"activity.ticket.phase":{kind:`input`,path:`activity.ticket.phase`,type:`string`,default:``},"activity.ticket.epic.done":{kind:`input`,path:`activity.ticket.epic.done`,type:`number`,default:0},"activity.ticket.epic.total":{kind:`input`,path:`activity.ticket.epic.total`,type:`number`,default:0},"activity.ticket.unread":{kind:`input`,path:`activity.ticket.unread`,type:`string`,default:``},"ticket.detail":{kind:`state`,key:`ticket-detail`,default:`collapsed`}},segments:{directory:{group:`location`,description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:$j},model:{group:`model-context`,description:`The active model's display name.`,template:`✱ {{ formatModelName .model.display_name }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{group:`session-tools`,description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{group:`model-context`,description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{group:`location`,description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{group:`location`,description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{group:`git`,description:`The git state: a summary (branch, ahead/behind, S/U/? flags) that the arrow at its right edge expands to every fact — repo, in-progress operation, sha, upstream ±, stash count, time since the last commit.`,template:`{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}`,fg:eM,when:`{{ ne .git.branch "" }}`,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if ne .git.prUrl "" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (ne .git.prUrl "") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:GS(``).template},commands:{group:`session-tools`,description:`Type /compact, /model or /clear into this session; /clear asks for a second click. Hidden when not inside tmux.`,template:Xj.template,when:Xj.when},themeSwitcher:{group:`session-tools`,description:"`◀ <theme> ▶`: the theme the bar is wearing; ◀ and ▶ switch this session to the previous or next theme, wrapping at the ends.",template:`{{ carousel "stepTheme" 0 }}`},session:{group:`cost-limits`,description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:rM(0)},today:{group:`cost-limits`,description:`Today's cost and tokens across every session, with a budget warning once a budget is configured.`,template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:rM(50)},block:{group:`cost-limits`,description:`The 5-hour rate-limit block: percent used and time to reset, heating to warning then error.`,template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:nM,when:`{{ gt .block.resetsAt 0 }}`},weekly:{group:`cost-limits`,description:`The weekly rate-limit quota: percent used and time to reset, heating to warning then error.`,template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:nM,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{group:`cost-limits`,description:`Spend per hour, with the projected time to the 5-hour and weekly limits.`,template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 (tint) 0 "error" .settings.errorWithin "warning" .settings.warnWithin (tint) }}`,settings:{errorWithin:{label:`error within (min)`,domain:{min:0,max:300,step:5},default:30},warnWithin:{label:`warning within (min)`,domain:{min:0,max:300,step:5,atLeast:`errorWithin`},default:60}},when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{group:`activity`,description:`Token throughput for the latest exchange: output, input, and total.`,template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{group:`activity`,description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,when:`{{ ne .speed.history "" }}`},cacheTimer:{group:`activity`,description:"Minutes until the prompt cache expires, or `cold` once it has.",template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ readableOn (color (cascade (minutesUntilReset .cache.expiresAt) "0:error" "9:warning" "21:foreground")) (bgOf) ${lo} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},ceiling:{group:`model-context`,description:`The memento plugin's context ceiling for this session: − and + move it by 100K, ∞ lifts it, ↺ drops this session's own setting.`,template:`{{ if ne .memento.error "" }}⌈ ⚠ {{ .memento.error }} {{ action "ceiling.clear" "↺" }}{{ else }}⌈ {{ if .memento.off }}off{{ else }}{{ template "formatTokenCount" .memento.ceiling }} {{ action "ceiling.lower" "−" }} {{ action "ceiling.raise" "+" }} {{ action "ceiling.off" "∞" }}{{ end }}{{ if ne .memento.session "" }} {{ action "ceiling.clear" "↺" }}{{ end }}{{ end }}`,bg:`{{ if ne .memento.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .memento.ceiling 0) (ne .memento.error "") }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:Zj.template,bg:Zj.bg,when:Zj.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},ticket:{group:`activity`,description:`The lit ticket this session started; expands to its workflow phase and its epic's done/total.`,template:`🎫 {{ action "copyTicket" .activity.ticket.id }}{{ if eq .ticket.detail "expanded" }} · {{ .activity.ticket.phase }}{{ if .activity.ticket.epic.total }} · epic {{ .activity.ticket.epic.done }}/{{ .activity.ticket.epic.total }}{{ end }}{{ if .activity.ticket.unread }} · ⚠ unreadable {{ abbrev 40 .activity.ticket.unread }}{{ end }}{{ end }} {{ action "ticketDetail" "▸" "◂" }}`,when:`{{ ne .activity.ticket.id "" }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`ticket`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...GS(``).actions,...Xj.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},ticketDetail:{set:`ticket-detail`,cycle:[`collapsed`,`expanded`]},copyTicket:{copy:`{{ .activity.ticket.id }}`},"ceiling.raise":{ceiling:`set`,to:`+100_000`},"ceiling.lower":{ceiling:`set`,to:`-100_000`},"ceiling.off":{ceiling:`set`,to:`off`},"ceiling.clear":{ceiling:`clear`},...Zj.actions},styles:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${lo}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ if and .settings.age (gt .git.timeSinceCommit 0) }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:gC(`.`),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 .)) }}`}},aM=new Set([iM.globals.palette,...Object.values(iM.segments).map(e=>e.palette)].filter(e=>e!==void 0)),oM=xl(HD(`<default>`,JSON.stringify(iM),aM),iM),sM=fv(oM.presets);function cM(e){return sM.includes(e)}function lM(e){if(!e)return 0;try{return s(e).mtimeMs}catch{return 0}}const uM=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 dM(e){return((...t)=>uM.run(()=>e(...t)))}const fM=dM(w),pM=dM(C),mM=dM(ee);async function hM(e,t){return uM.run(async()=>{let n=null;try{n=await S(e,`r`);let{size:r,mtimeMs:i,ino:a}=await n.stat(),o=t!==void 0&&(a!==t.ino||r<t.offset),s=o||t===void 0?0:t.offset;if(s>=r)return J({buf:Buffer.alloc(0),start:s,size:r,mtimeMs:i,ino:a,reset:o});let c=Buffer.alloc(r-s),l=0;for(;l<c.length;){let{bytesRead:e}=await n.read(c,l,c.length-l,s+l);if(e===0)break;l+=e}return J({buf:l===c.length?c:c.subarray(0,l),start:s,size:r,mtimeMs:i,ino:a,reset:o})}catch(t){return t.code===`ENOENT`?Y:X(`readAppended ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{O(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}async function gM(e,t){return uM.run(async()=>{let n=null;try{n=await S(e,`r`);let{size:r}=await n.stat(),i=Math.max(0,r-t),a=Buffer.alloc(r-i),o=0;for(;o<a.length;){let{bytesRead:e}=await n.read(a,o,a.length-o,i+o);if(e===0)break;o+=e}return J({buf:o===a.length?a:a.subarray(0,o),fromStart:i===0})}catch(t){return t.code===`ENOENT`?Y:X(`readTail ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{O(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}const _M=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function vM(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 yM(e){let t=await bM(e);return t.kind===`ok`?J(Math.floor((t.value+36e5)/1e3)):t}async function bM(e){for(let t of[65536,1048576]){let n=await gM(e,t);if(n.kind!==`ok`)return n;let r=xM(n.value.buf,n.value.fromStart);if(r!=null)return J(r);if(n.value.fromStart)return Y}return Y}function xM(e,t){let n=e.toString(`utf8`).split(`
182
+ `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!_M.test(t))continue;let r=vM(t);if(r!=null)return r}return null}function SM(e,t){return{...e,claudeConfigDir:iC(t.claudeConfigDir),env:t.mementoEnv}}const CM=l.join(`lib`,`ceiling_config.py`),wM=l.join(`skills`,`ceiling`,`bin`,`ceiling`);function TM(e,t){let n=typeof e==`object`&&e?e.plugins:void 0;if(typeof n!=`object`||!n)throw Error(`${t} has no "plugins" object`);return Object.entries(n).filter(([e])=>e.split(`@`)[0]===`memento`).flatMap(([e,n])=>{if(!Array.isArray(n))throw Error(`${t}: "${e}" is not a list of installs`);return n.map(n=>{let{scope:r,installPath:i,projectPath:a}=n??{};if(typeof r!=`string`||typeof i!=`string`)throw Error(`${t}: an install of "${e}" has no scope/path`);return typeof a==`string`?{key:e,scope:r,installPath:i,projectPath:a}:{key:e,scope:r,installPath:i}})})}function EM(e,t){let n=!0;for(let i of e){if(!r.existsSync(i))continue;let e;try{e=JSON.parse(r.readFileSync(i,`utf8`))?.enabledPlugins?.[t]}catch(e){return X(`memento lookup: ${i}: ${e.message}`)}typeof e==`boolean`&&(n=e)}return J(n)}function DM(e,t){if(!r.existsSync(e))return Y;let n;try{n=TM(JSON.parse(r.readFileSync(e,`utf8`)),e)}catch(e){return X(`memento lookup: ${e.message}`)}let i=n.find(e=>e.projectPath===t)??n.find(e=>e.scope===`user`);if(i===void 0)return Y;let a=EM([l.join(l.dirname(l.dirname(e)),`settings.json`),l.join(t,`.claude`,`settings.json`),l.join(t,`.claude`,`settings.local.json`)],i.key);if(a.kind!==`ok`)return a;if(!a.value)return Y;let o=[CM,wM].filter(e=>!r.existsSync(l.join(i.installPath,e)));return o.length===0?J(i.installPath):X(`memento at ${i.installPath} has no ${o.join(` or `)} — upgrade the plugin`)}function OM(e,t=process.env){let n=new Set([`CLAUDE_PROJECT_DIR`,`CLAUDE_CODE_SESSION_ID`,...e.env===void 0?[]:Qe]);return{...Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e))),...e.env,CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir||e.cwd}}function kM(e){return e.stderr.trim()||e.error||`${e.reason}${e.exitCode===null?``:` (exit ${e.exitCode})`}`}function AM(e){let t;try{t=JSON.parse(e)}catch{return X(`memento read: not JSON: ${e.trim()}`)}let{ceiling:n,session:r}=t??{},i=n===`off`||typeof n==`number`&&n>=0?n:void 0;return i!==void 0&&(r===null||typeof r==`string`)?J({ceiling:i,session:r}):X(`memento read: unexpected answer: ${e.trim()}`)}async function jM(e,t){let n=await Ae({bin:`python3`,args:[`-c`,`
183
183
  import json, math, sys
184
184
  sys.path.insert(0, sys.argv[1])
185
185
  from ceiling_config import CONFIG_NAME, anchored, ceiling_in, in_force, session_directory
@@ -188,41 +188,41 @@ ceiling = in_force(directory, anchored(sys.argv[3]))
188
188
  layer = ceiling_in(directory / CONFIG_NAME)
189
189
  print(json.dumps({"ceiling": "off" if ceiling == math.inf else ceiling,
190
190
  "session": layer.text if layer else None}))
191
- `,l.join(e,`lib`),t.sessionId,t.cwd],env:wM(t),timeoutMs:3e3,category:`memento.read`});return n.ok?EM(n.stdout):X(TM(n))}function OM(e,t,n){let r=k({bin:l.join(e,bM),args:n.kind===`set`?[`set`,`session`,n.to]:[`clear`,`session`],env:wM(t),timeoutMs:5e3,category:`memento.move`});if(!r.ok)throw Error(TM(r))}function kM(){return{locate:e=>CM(oC(e.claudeConfigDir),e.projectDir),read:DM,move:OM}}function AM(e,t,n){let r=n===void 0?``:`CLAUDE_CONFIG_DIR=${Fk(n)} `,i=e.added_dirs.map(e=>` --add-dir ${Fk(e)}`).join(``);return`cd ${Fk(e.project_dir)} && ${r}claude --resume ${Fk(t)}${i}`}function jM(e,t,n){let r=pv(t(`preset`),e.globals.preset,e.presets),i=gv(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{};return{preset:r,presetCustomized:n(r),theme:Kx(a.palette,t(`theme`),i.palette),style:Go(a.style,t(`style`),i.style,e.styles),endcaps:Jo(a.endcaps,t(`endcaps`),i.endcaps),variation:ts(a.variation,t(`variation`),i.variation),separator:a.default_separator??i.default_separator,autoWrap:ls(a.autoWrap,t(`autoWrap`),i.autoWrap),padding:ds(a.padding,t(`padding`),i.padding),charset:a.charset??i.charset??`unicode`,updateNotice:us(a.updateNotice,t(`updateNotice`),i.updateNotice),colorCompatibility:a.colorCompatibility??i.colorCompatibility??`truecolor`}}function MM(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,charset:e.charset,width:t}}function NM(e){return{theme:e.theme,style:e.style,preset:e.preset,variation:e.variation}}function PM(e){return{preset:{effective:e.preset,customized:e.presetCustomized,bundled:iM(e.preset)},endcaps:{effective:e.endcaps},variation:{effective:e.variation},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding},updateNotice:{effective:e.updateNotice}}}const FM=10*1e3;function IM(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 LM(e,t){if(!(t<60))return e*3600/t}function RM(e,t,n,r){let i=r-t;if(i<50||i>FM)return;let a=n-e;if(!(a<=0))return a*1e3/i}function zM(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=RM(t.input,t.atMs,n.input,n.atMs),i=RM(t.output,t.atMs,n.output,n.atMs),a=RM(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 BM(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>FM)continue;let o=RM(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function VM(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function HM(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`,()=>VM(h.hostname())),i=n(`user`,()=>h.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function UM(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=>ny(t,e.helpers).keys(),o=gv(e,t);for(let e of Ro){let t=o[e];if(zo(t))for(let e of a(t))r.push(e)}for(let n of pc(hv(e,t).node)){if(n.when)for(let e of a(n.when))r.push(e);if(n.kind!==`segment`)continue;let t=e.segments[n.name];if(t){for(let e of[t.template,t.when,t.bg,t.fg])if(e)for(let t of a(e))r.push(t)}}let s=new Set;for(;r.length>0;){let e=r.pop();for(let t of GM(n,e)){if(i.has(t))continue;i.add(t);let e=n.get(t);if(e){if(e.kind===`input`)s.add(e.path);else if(e.kind===`template`)for(let t of a(e.template))r.push(t)}}}return s}function WM(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=UM(e,n);return t.set(n,i),i}}function GM(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 KM(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function qM(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 JM(e,t,n,r,i,a,{configPath:o,...s}){let c=e=>KM(r,e),l=(t.clock??(()=>new Date))().getTime(),u=a.tmux??null,d=(e,t,n)=>t?n().catch(t=>X(`${e}: ${String(t)}`)):Promise.resolve(Y),[f,p,m,h,g,_,v,y,b,x,S]=await Promise.all([d(`git`,c(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,qM(r),e.workspace?.project_dir)),d(`session`,c(`session.cost`)||c(`session.tokens`)||c(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),d(`today`,c(`today`),()=>t.usageStore.getTodayInfo(e,a.claudeConfigDir)),d(`context`,c(`context`)||c(`autocompact`),()=>t.contextProvider.getContextInfo(e)),d(`metrics`,c(`metrics`)||c(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),d(`activity`,c(`activity`),()=>t.activityProvider.getActivityInfo(e.session_id,e)),d(`tmux`,c(`tmux.session`),()=>u===null?Promise.resolve(Y):t.tmuxService.getSessionName(u)),d(`cache`,c(`cache`),()=>hM(e.transcript_path)),d(`speed`,c(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,l)),d(`memento`,c(`memento`),()=>t.mementoProvider.getCeiling(vM({sessionId:e.session_id,projectDir:e.workspace?.project_dir??``,cwd:n??e.workspace?.current_dir??``},a))),d(`autocompact`,c(`autocompact`),()=>Promise.resolve(t.autoCompact(aC(iC(a.claudeConfigDir)))))]),C=[],w=e=>{if(e.kind===`failed`){C.push(e.reason);return}return e.kind===`ok`?e.value:void 0},ee=nN(f);C.push(...ee.failures);let te=HM(a);C.push(...te.failures);let ne=w(p),re=w(m),ie=w(h),T=w(g),E=w(_),ae=w(v),oe=w(y),se=ZM(x);x.kind===`failed`&&C.push(`memento: ${x.reason}`);let ce=YM(S,ie?.maxTokens);S.kind===`failed`&&C.push(`autocompact: ${S.reason}`);for(let e of C)t.log(`warn`,`provider fetch failed: ${e}`);let le=e.rate_limits?.five_hour,D=e.rate_limits?.seven_day,ue=le?IM(le.used_percentage,le.resets_at,18e6,l):void 0,de=D?IM(D.used_percentage,D.resets_at,6048e5,l):void 0,fe=ne?.session.cost,pe=T?.sessionDuration,me=c(`burn`)&&fe!=null&&pe!=null?LM(fe,pe):void 0,he=w(b),ge=he===void 0?void 0:zM(he),_e=he===void 0?void 0:BM(he),ve=ge!==void 0||_e!==void 0?{...ge,..._e!==void 0&&{history:_e}}:void 0,ye=tN(process.env.HOME??process.env.USERPROFILE),O=e.workspace?{...e.workspace,current_dir:tN(e.workspace.current_dir)??``,project_dir:tN(e.workspace.project_dir)??``,added_dirs:(e.workspace.added_dirs??[]).map(e=>tN(e)??e)}:e.workspace,be=ne===void 0?void 0:eN({cost:ne.session.cost,tokens:ne.session.tokens}),xe=re===void 0?void 0:{cost:re.cost,tokens:re.tokens},Se=T===void 0?void 0:eN({lastResponseTime:T.lastResponseTime,responseTime:T.responseTime,sessionDuration:T.sessionDuration,messageCount:T.messageCount,linesAdded:T.linesAdded,linesRemoved:T.linesRemoved}),Ce=E===void 0?void 0:QM(E);return{...e,...O!==void 0&&{workspace:O},...ye!==void 0&&{home:ye},...ee.git!==void 0&&{git:ee.git},...u!==null&&{tmux:{pane:u.pane,...ae!==void 0&&{session:ae}}},host:te.host,...PM(i),history:t.history(e.session_id),navigation:{back:t.navigation(e.session_id)},...s,...o!==null&&{configPath:o},resumeCommand:AM(O,e.session_id,a.claudeConfigDir),...be!==void 0&&{session:be},...xe!==void 0&&{today:xe},...me!==void 0&&{burn:{costPerHour:me}},...ve!==void 0&&{speed:ve},...c(`block`)&&le!==void 0&&{block:{nativeUtilization:le.used_percentage,resetsAt:le.resets_at,...ue!==void 0&&{etaMinutes:ue}}},...D!==void 0&&{weekly:{percentage:D.used_percentage,resetsAt:D.resets_at,...de!==void 0&&{etaMinutes:de}}},...oe!==void 0&&{cache:{expiresAt:oe}},...ie!==void 0&&{context:{totalTokens:ie.totalTokens,contextLeft:ie.contextLeftPercentage}},...Se!==void 0&&{metrics:Se},...Ce!==void 0&&{activity:Ce},...se!==void 0&&{memento:se},...ce!==void 0&&{autocompact:ce}}}function YM(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return mC(e.value,t)}}const XM=e=>e.trim().split(`
192
- `).at(-1).trim();function ZM(e){switch(e.kind){case`absent`:return;case`failed`:return{error:XM(e.reason)};case`ok`:{let{ceiling:t,session:n}=e.value;return{ceiling:t===`off`?0:t,off:t===`off`,session:n??``}}}}function QM(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=$M(e.running),i=$M(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}},o=e.ticket===null?void 0:{id:e.ticket.id,phase:e.ticket.phase,...e.ticket.epic!==null&&{epic:e.ticket.epic},...e.ticket.unread!==null&&{unread:e.ticket.unread}};if(!(o===void 0&&e.command===null&&n===void 0&&a===void 0))return{...o!==void 0&&{ticket:o},...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function $M(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function eN(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 tN(e){return e===void 0||e.length===0||l.sep!==`\\`?e:e.replace(/\\/g,`/`)}function nN(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 rN={theme:e=>e.theme.kind===`decided`?e.theme.name:null,preset:e=>e.preset,style:e=>e.style.kind===`decided`?e.style.name:null,endcaps:e=>e.endcaps,variation:e=>e.variation,autoWrap:e=>e.autoWrap?ns:rs,padding:e=>String(e.padding),updateNotice:e=>e.updateNotice?ns:rs},iN=Object.entries(Ox),aN=new Set(kx.map(e=>e.sessionKey)),oN=()=>!1;function sN(e,t){return jM(e,e=>aN.has(e)?t(e):null,oN)}function cN(e,t,n,r){return e.flatMap(([e,i])=>{let a=rN[e](t);return a===null||a===rN[e](n(e))?[]:[{...i,value:a,target:r(i)}]})}function lN(e,t,n){return rN[n](sN(e,t))}function uN(e,t){let n=sN(e,t),r=jM(e,()=>null,oN),i=jM(e,e=>e===Ox.preset.sessionKey?n.preset:null,oN);return cN(iN,n,e=>e===`preset`?r:i,t=>dN(e,n.preset,t.configKey))}function dN(e,t,n){return n in(mv(e.presets,t).globals??{})?pS(t,n):n}function fN(e,t,n){let r=pv(t(Ox.preset.sessionKey),e.globals.preset,e.presets),i=mS(n);return{key:i?.scope===`globals`?dN(e,r,i.field):n,globals:gv(e,r)}}function pN(e,t){let{preset:n}=sN(e,t);return gN(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:Oc(a,s);return c===void 0||Dc(c)===Dc(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function mN(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return fv(e.presets).flatMap(n=>{let i=gN(e,n);return[...new Set(i.filter(e=>r.has(e.key)).map(e=>e.id))].flatMap(e=>{let n=i.filter(t=>t.id===e);return Tc(Object.fromEntries(n.map(e=>[e.setting,e.decl])),Object.fromEntries(n.map(e=>{let n=r.get(e.key)??t(e.key),i=n===null?void 0:Oc(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const hN=new WeakMap;function gN(e,t){let n=hN.get(e)??new Map;hN.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...pc(hv(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Cc(e.segments[t.name])[n];return{id:r,setting:n,key:i,decl:a,saved:t.settings?.[n]??a.default}})),a=[...new Map(i.map(e=>[e.key,e])).values()];return n.set(t,a),a}function _N(e,t){let n=sN(e,t),r=jM(e,e=>e===Ox.preset.sessionKey?n.preset:null,oN);return{from:n.preset,globals:mv(e.presets,n.preset).globals??{},picks:cN(iN.filter(([e])=>e!==`preset`),n,()=>r,e=>e.configKey),placements:pN(e,t)}}function vN(e){return{sessionKeys:kx.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...iu(e)?rM.map(t=>pS(t,e)):[]]}}function yN(e){return new Set(kx.map(e=>e.configKey).filter(t=>vN(t).fileKeys.some(t=>SN(e,xN(t)))))}function bN(e,t,n){let r=uN(e,n),i=new Set(r.map(e=>e.configKey)),a=Px(e=>i.has(Ox[e].configKey)||t.has(Ox[e].configKey));return{unsaved:r.length+pN(e,n).length,resettable:a}}function xN(e){let t=mS(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return hS(t)}function SN(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&SN(e[n],r)}const CN=No(),wN=new Set(CN),TN=new Set(Ko),EN=e=>e?wN.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${CN.join(`, `)})`}:{ok:!1,reason:`theme name is required`},DN=e=>e?TN.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Ko.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},ON=new Set([`1`,`true`]),kN=new Set([`0`,`false`]),AN={endcaps:DN,theme:EN,"toolbar-expanded":e=>ON.has(e)?{ok:!0,value:`1`}:kN.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},jN=Lj(AN,`state`,RN);function MN(e,t){return jN.register(e,t)}function NN(e){return jN.gateFor(e)}function PN(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:eS(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 FN(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(AN,e.key))}function IN(e,t,n){let r=Fx.get(n);if(r!==void 0)return lN(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 LN(e){let t=eT(e);return FN(Object.values(e.actions).flatMap(e=>PN(e,t)))}function RN(e){return Fj(LN(e))}const zN=`update.dismissed`,BN=`updateNotice`,VN=Ox.updateNotice.sessionKey;function HN(e){return e.kind===`source`?e.newer.digest:Rk(e.newer)}const UN=e=>`${e.version} [${bj(e.digest)}]`;function WN(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:UN(e.newer),running:UN(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:Rk(e.newer),running:Rk(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${Bk}@${Rk(e.newer)}`,`install`]}}}}const GN={kind:`idle`},KN={kind:`running`};function qN(e,t,n){if(e===null)return[];let r=HN(e);if(!n.enabled||n.dismissed===r)return[];let i=WN(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(`
193
- `),c=Dk([{verb:sk,args:[s]}]),l=t.kind===`running`?cj(`[${i.busy}]`,c):cj(`[${i.act}]`,Dk([{verb:yk,args:[n.sessionId]}]));return[{severity:sj,message:s,lines:[[cj(a,c),l,cj(`[dismiss]`,Dk([{verb:tk,args:[n.sessionId,zN,r]}])),cj(`[disable]`,Dk([{verb:ck,args:[n.sessionId,BN,`false`]},{verb:tk,args:[n.sessionId,VN,`false`]}]))],...o.map(e=>[cj(e,c)])]}]}function JN(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 YN(e){switch(e.kind){case`current`:return[`info`,`build: current ${UN(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${UN(e.source)}, running ${UN(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function XN(e){switch(e.kind){case`current`:return[`info`,`release: current ${Rk(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${Rk(e.latest)}, running ${Rk(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${Rk(e.installed)}, latest ${Rk(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function ZN(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const QN=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function $N(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=QN(e.stderr)??e.error??QN(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function eP(){let e=[zj(BN,[`false`]),MN(VN,[`false`]),MN(zN,[])];return()=>e.forEach(e=>e())}function tP(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=GN,d=null,f=ZN(s),p=ZN(s),m=()=>JN(c,l);function h(){let e=m(),t=e===null?null:HN(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:MN(zN,[t])})}function g(){c=wj(t,Sj),f(YN(c)),h()}async function _(){l=Hk(dO,await Vk(Bk,a,i)),p(XN(l)),h()}return{arm(){eP(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>qN(m(),u,e),act(){let e=m();if(e===null)throw new $(`apply-update: nothing newer is known to apply`);let t=WN(e);if(u.kind===`running`)throw new $(`apply-update: already ${t.busy}`);u=KN,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),Ae({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=GN,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=$N(n);u={kind:`failed`,identity:HN(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}var nP=class{static CACHE_DIR=Ie();static USAGE_CACHE_DIR=l.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=l.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=l.join(this.LOCKS_DIR,e);if(!r.existsSync(t))return!1;try{let n=r.readFileSync(t,`utf-8`),i=parseInt(n.trim(),10);if(isNaN(i))return O(`Invalid PID in lock file ${e}, removing stale lock`),r.unlinkSync(t),!1;try{return process.kill(i,0),!0}catch(n){return n.code===`ESRCH`?(O(`Removing stale lock file ${e} for dead process ${i}`),r.unlinkSync(t),!1):(O(`Error checking process ${i} for lock ${e}:`,n),!0)}}catch(t){return O(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=l.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await r.promises.writeFile(n,a,{flag:`wx`}),O(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await D(50);else throw e}return O(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=l.join(this.LOCKS_DIR,e);try{await r.promises.unlink(t),O(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&O(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([r.promises.mkdir(this.CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){O(`Failed to create cache directories:`,e)}}static createProjectHash(e){return se(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=l.join(this.USAGE_CACHE_DIR,`${e}.json`),i=`${e}.usage.lock`;for(let a=0;a<3;a++){if(this.isLocked(i)){O(`Cache for ${e} is locked, waiting...`),await D(75);continue}try{let i=await r.promises.readFile(n,`utf-8`),a=JSON.parse(i);return!t||a.timestamp>=t?(O(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(a.data)):(O(`${e} cache outdated: cache=${a.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return O(`No shared ${e} usage cache found`),null;O(`Attempt ${a+1} failed to read ${e} cache: ${t.message}. Retrying...`),await D(75)}}return O(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let i=`${e}.usage.lock`;if(!await this.acquireLock(i)){O(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=l.join(this.USAGE_CACHE_DIR,`${e}.json`),a=JSON.stringify({data:t,timestamp:n||Date.now()});await r.promises.writeFile(i,a,`utf-8`),O(`[CACHE-SET] ${e} disk cache stored`)}catch(t){O(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(i)}}};const rP={"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 iP=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 nP.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await nP.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new ie(this.GITHUB_PRICING_URL),n=le({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){O(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let r=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){O(`Response too large`),n.destroy(),e(null);return}r+=t}),t.on(`end`,()=>{try{let t=JSON.parse(r),n=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(O(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),O(`Pricing last updated: ${n?.updated||`unknown`}`),e(i)):(O(`Invalid pricing data structure`),e(null))}catch(t){O(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{O(`Response error:`,t),e(null)})});n.on(`error`,t=>{O(`Request error:`,t),e(null)}),n.on(`timeout`,()=>{O(`Request timeout`),n.destroy(),e(null)}),n.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return O(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return O(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,O(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),O(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,O(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(O(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(rP).length} models`),this.executionCache=rP,O(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(rP).length} models`),rP)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return O(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),O(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const aP=String.raw`(?:^|[\s;&|(])`,oP=e=>RegExp(`(?:^|:)(?:${e})$`),sP=[{phase:`impl`,tool:`Edit`,match:/^/},{phase:`impl`,tool:`MultiEdit`,match:/^/},{phase:`impl`,tool:`Write`,match:/^/},{phase:`impl`,tool:`NotebookEdit`,match:/^/},{phase:`review`,tool:`Bash`,match:RegExp(`${aP}gh\\s+pr\\s+create\\b`)},{phase:`review`,tool:`Skill`,match:oP(`code-review|simplify`)},{phase:`groom`,tool:`Bash`,match:RegExp(`${aP}lit\\s+(done|close)\\b`)},{phase:`groom`,tool:`Skill`,match:oP(`groom-backlog`)},{phase:`handoff`,tool:`Skill`,match:oP(`message-in-a-bottle`)}],cP=e=>RegExp(`${aP}lit\\s+(?:${e})(?:\\s+(?:--?[\\w-]+(?:=\\S*)?|''))*\\s+([A-Za-z0-9][\\w.-]*)`),lP=[{verb:cP(`start`),to:`in_progress`},{verb:cP(`done|close`),to:`closed`}];function uP(e){return sP.find(t=>t.tool===e.tool&&t.match.test(e.subject))?.phase}function dP(e,t){if(t.tool===`Bash`)for(let{verb:n,to:r}of lP){let i=n.exec(t.subject)?.[1];if(i!==void 0)return{call:e,id:i,to:r}}}const fP=/^lit:state (.*)$/gm;function pP(e){return[...e.matchAll(fP)].map(([e,t])=>mP(t)??{kind:`unreadable`,line:e.trim()})}function mP(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=`object`||!t)return;let{id:n,status:r,epic:i}=t;if(typeof n!=`string`||typeof r!=`string`)return;if(i===null)return{kind:`state`,id:n,status:r,epic:null};if(typeof i!=`object`||i===void 0)return;let a=i;if(!(typeof a.id!=`string`||typeof a.done!=`number`||typeof a.total!=`number`))return{kind:`state`,id:n,status:r,epic:{id:a.id,done:a.done,total:a.total}}}function hP(e,t){let n=t??{};return{tool:e,subject:e===`Bash`&&typeof n.command==`string`?vP(n.command):e===`Skill`&&typeof n.skill==`string`?n.skill:e}}const gP=/(<<-?\s*(['"]?)(\w+)\2[^\n]*\n)[\s\S]*?\n\s*\3(?=\n|$)/g,_P=/'[^']*'|"(?:[^"\\]|\\.)*"/g;function vP(e){return e.replace(gP,`$1`).replace(_P,`''`)}function yP(e){return typeof e==`string`?[e]:Array.isArray(e)?e.flatMap(e=>typeof e==`object`&&e&&typeof e.text==`string`?[e.text]:[]):[]}const bP=/^(\S+) \[(open|in_progress|closed)\//gm,xP=/^Ticket (\S+) has been closed\./gm,SP={sentinels:[],said:[]};function CP(e){let t;for(let n of yP(e)){let e=n.includes(`lit:state `),r=n.includes(` [`),i=n.includes(`has been closed.`);if(!(!e&&!r&&!i)){if(t??={sentinels:[],said:[]},e&&t.sentinels.push(...pP(n)),r)for(let[,e,r]of n.matchAll(bP))t.said.push({id:e,status:r});if(i)for(let[,e]of n.matchAll(xP))t.said.push({id:e,status:`closed`})}}if(t===void 0)return SP;for(let e of t.sentinels)e.kind===`state`&&t.said.push({id:e.id,status:e.status});return t}const wP=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function TP(e){if(typeof e==`string`)return wP.exec(e)?.[1]}function EP(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 DP(e){let t=e.message?.content,n=e.type===`user`,r=[],i=[],a,o,s=[],c=[],l,u=[];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});let i=hP(n,t.input),o=dP(e,i);o!==void 0&&s.push(o),l=uP(i)??l,n===`TodoWrite`&&(a=EP(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id,n=CP(t.content);if(u.push(...n.sentinels),typeof e==`string`){i.push(e);for(let t of n.said)c.push({call:e,...t})}break}case`text`:o??=t.text;break;default:break}}let d=n?TP(o):void 0,f=s.length===0&&l===void 0&&u.length===0&&c.length===0?void 0:{...s.length>0&&{claims:s},...l!==void 0&&{phase:l},...u.length>0&&{sentinels:u},...c.length>0&&{said:c}};if(!(r.length===0&&i.length===0&&a===void 0&&d===void 0&&f===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...d!==void 0&&{command:d},...f!==void 0&&{lit:f}}}function OP(e){if(e!==void 0)return[e];let t=g();return[p(t,`.config`,`claude`),p(t,`.claude`)].filter(e=>a(e))}async function kP(e){let t=[];for(let n of e){let e=p(n,`projects`);if(a(e))try{let n=await cM(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=p(e,r.name);t.push(n)}}catch(t){O(`Failed to read projects directory ${e}:`,t)}}return t}async function AP(e,t,n){let r=[],i=p(t,e,`subagents`);try{let t=(await cM(i)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let a of t){let t=p(i,a);if(n?.has(t)){r.push(t);continue}try{let n=(await lM(t,`utf-8`)).split(`
194
- `)[0];n&&JSON.parse(n).sessionId===e&&r.push(t)}catch{O(`Failed to check agent file ${t}`)}}}catch(e){O(`Failed to read subagents directory ${i}:`,e)}return r}function jP(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 MP=new Map;async function NP(e){try{let t=await uM(e),n=t.size,r=MP.get(e);if(r&&r.mtime===t.mtimeMs&&r.size===n)return O(`[parse-cache] hit ${e}`),MP.delete(e),MP.set(e,r),r.entries;let i;return n>1048576?(O(`Using streaming parser for large file ${e} (${Math.round(n/1024)}KB)`),i=await RP(e)):i=await IP(e),O(`Parsed ${i.length} entries from ${e}`),n>5242880?i:(MP.delete(e),MP.size>=16&&MP.delete(MP.keys().next().value),MP.set(e,{mtime:t.mtimeMs,size:n,entries:i}),i)}catch(t){if(t.code===`ENOENT`)return O(`Transcript not present yet: ${e}`),[];throw t}}function PP(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:DP(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 FP(e){let t=[];for(let n of e.split(`
195
- `))if(n.trim())try{let e=PP(JSON.parse(n));e&&t.push(e)}catch(e){O(`Failed to parse JSONL line: ${e}`);continue}return t}async function IP(e){return FP(await lM(e,`utf-8`))}async function LP(e,t){let n=await dM(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:FP(r.subarray(0,c+1).toString(`utf-8`)),cursor:{offset:i+c+1,mtimeMs:a,ino:o},reset:s})}async function RP(e){return new Promise((t,n)=>{let r=[],a=i(e,{encoding:`utf8`}),o=ue({input:a,crlfDelay:1/0});o.on(`line`,e=>{let t=e.trim();if(t)try{let e=PP(JSON.parse(t));e&&r.push(e)}catch(e){O(`Failed to parse JSONL line: ${e}`)}}),o.on(`close`,()=>{t(r)}),o.on(`error`,t=>{O(`Streaming parser error for ${e}:`,t),n(t)}),a.on(`error`,t=>{O(`File stream error for ${e}:`,t),n(t)})})}var zP=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 BP(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 VP=new Map,HP={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},UP={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function WP(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function GP(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function KP(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}async function qP(e,t,n,r){let i=WP(new Date(GP())),a=e&&!t?e:void 0,o=a?.entries??0,s=a?.cost??0,c=a?{...a.breakdown}:KP(),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 iP.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=WP(new Date(e.timestamp));if(r<i)continue;let a=l.get(r)??{...HP};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 JP(e){let t=0,n=0,r=KP(),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)??{...HP};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:UP,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 YP(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 XP=class{entries=new Map;flight=new zP;seeded=new Map;seededDay=``;speedRings=new Map;speedFlight=new zP;maxEntries;staleAgeMs;log;hits=0;misses=0;sweeps=0;seeds=0;sweepTimer=null;constructor(e={}){this.log=e.logger??Ub,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:UP,i=t?.cost?.total_cost_usd??null;return J({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e,t){let n=WP(new Date),r=OP(t);try{await this.ensureSeeded(n,r)}catch(e){return X(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let i=await this.ingest(e?.session_id??``,e?.transcript_path);if(i.kind===`failed`)return i;let a=r.map(e=>p(e,`projects`)+m),o={...HP},s=!1;for(let[t,r]of this.entries){let i=r.transcriptPath??``,c=t===e?.session_id||a.some(e=>i.startsWith(e))?r.days:VP;s||=c.has(n);let l=c.get(n)??HP;o.cost+=l.cost,o.input+=l.input,o.output+=l.output,o.cacheCreation+=l.cacheCreation,o.cacheRead+=l.cacheRead}return s?J({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:n}):Y}async observeSpeed(e,t,n){let r=aM(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,r);if(i.kind===`failed`)return i;let a=BP(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??aM(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 AP(e,d(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 LP(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 qP(r,l,s,c)),e===t&&(a=c.mtimeMs)}return J({files:i,...JP(i),mainMtime:a})}ensureSeeded(e,t){this.seededDay!==e&&(this.seeded.clear(),this.seededDay=e);let n=t.join(`\0`),r=this.seeded.get(n);if(r)return r;let i=this.seed(t);return this.seeded.set(n,i),i.catch(()=>{this.seeded.get(n)===i&&this.seeded.delete(n)}),i}async seed(e){let t=GP(),n=await kP(e),r=[];for(let e of n){let n;try{n=await cM(e)}catch{continue}for(let i of n){if(!i.endsWith(`.jsonl`))continue;let n=p(e,i),a;try{a=(await uM(n)).mtimeMs}catch{continue}a<t||r.push({sessionId:i.slice(0,-6),path:n,mtime:a})}}await YP(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,e.mtime);t.kind===`failed`&&this.log(`warn`,`usageStore seed: ${t.reason}`)}),this.seeds++,this.log(`info`,`usageStore seed sessions=${r.length} dirs=${e.join(`,`)}`)}sweepStale(){let e=Date.now(),t=0;for(let[n,r]of this.entries)e-r.lastSeenAt>this.staleAgeMs&&(this.entries.delete(n),this.speedRings.delete(n),t++);return t>0&&(this.sweeps++,this.log(`info`,`usageStore sweep dropped=${t}`)),t}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e),this.speedRings.delete(e),this.log(`info`,`usageStore evict ${e}`)}}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.entries.clear(),this.seeded.clear(),this.speedRings.clear()}},ZP=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return O(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);O(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t){try{O(`Calculating context tokens from transcript: ${e}`);let n=await NP(e);if(n.length===0)return O(`No entries in transcript`),Y;let r=null;for(let e=n.length-1;e>=0;e--){let t=n[e];if(t&&t.message?.usage?.input_tokens&&t.isSidechain!==!0){r=t,O(`Context segment: Found most recent entry at ${t.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let e=r.message.usage,n=(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0);return O(`Most recent main chain context: ${n} tokens (limit: ${t})`),J({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return O(`No main chain entries with usage data found`),Y}catch(e){return X(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return J(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}},QP=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=aM(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await LP(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 $P={messageCount:0,recent:[]};function eF(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +!!jP(t),recent:n.length>20?n.slice(-20):n}}function tF(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(jP(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 nF=class{fold=new QP($P,eF);async getMetricsInfo(e,t){if(O(`Getting metrics from hook data for session: ${e}`),!t.cost)return Y;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?X(`metrics (${e}): ${n.reason}`):J({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:tF(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})}};function rF(e,t,n){return n.some(e=>e.call===t.call&&e.id===t.id&&e.status===t.to)?t.to===`closed`?e?.id===t.id?null:e:{id:t.id,phase:`prep`,epic:e?.id===t.id?e.epic:null,unread:null}:e}function iF(e,t,n){let r=[...e.claims,...t?.claims??[]],i=e=>n.includes(e.call),a=r.filter(i).reduce((e,n)=>rF(e,n,t?.said??[]),e.ticket),o=r.filter(e=>!i(e));if(a===null||t===void 0)return{claims:o,ticket:a};let s=t.sentinels??[],c=s.findLast(e=>e.kind===`state`&&e.id===a.id),l=s.findLast(e=>e.kind===`unreadable`);return{claims:o,ticket:{id:a.id,phase:t.phase??a.phase,epic:c?.kind===`state`?c.epic:a.epic,unread:l?.kind===`unreadable`?l.line:a.unread}}}const aF={ticket:null,claims:[],command:null,todos:[],pending:[],done:[]};function oF(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 sF(e,t){if(t.isSidechain)return e;let n=jP(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=oF(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos,...iF(n,r.lit,r.finished??[])}}function cF(e){return{ticket:e.ticket,command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>oF(e,t.name),[]),done:e.done}}var lF=class{fold=new QP(aF,sF);async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?X(`activity (${e}): ${n.reason}`):J(cF(n.value))}};function uF(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function dF(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function fF(e,t,n,r){return dF(k(uF(e,t,n,r)),n)}async function pF(e,t,n){return dF(await Ae(uF(e,t,n)),n)}const mF=e=>`${e.socket}\n${e.pane}`;var hF=class{names=new Map;asking=new zP;constructor(e=Date.now){this.now=e}getSessionName(e){let t=mF(e),n=this.names.get(t);if(n&&this.now()-n.at<3e4)return Promise.resolve(n.outcome);let r=this.asking.run(t,()=>this.ask(t,e));return n?Promise.resolve(n.outcome):r}async ask(e,t){O(`Getting tmux session name for pane ${t.pane} on ${t.socket}`);let n=await pF(t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]),r=n.kind===`ok`?n.stdout.trim():``,i=n.kind===`ok`?r?J(r):Y:X(n.reason);for(this.names.delete(e),this.names.set(e,{outcome:i,at:this.now()});this.names.size>64;)this.names.delete(this.names.keys().next().value);return i}};const gF=e=>JSON.stringify([e.sessionId,e.projectDir,e.cwd,e.claudeConfigDir,e.env===void 0?null:Qe.map(t=>e.env?.[t]??null)]);var _F=class{readings=new Map;inFlight=new Map;constructor(e,t=Date.now){this.edge=e,this.now=t}getCeiling(e){let t=gF(e),n=this.readings.get(t);if(n&&this.now()-n.at<1e4)return Promise.resolve(n.outcome);let r=this.inFlight.get(t)??this.fetch(t,e);return n?Promise.resolve(n.outcome):r}fetch(e,t){let n=this.edge.locate(t),r=(n.kind===`ok`?this.edge.read(n.value,t):Promise.resolve(n)).then(t=>{if(this.inFlight.get(e)!==r)return t;for(this.readings.delete(e),this.readings.set(e,{outcome:t,at:this.now()});this.readings.size>64;)this.readings.delete(this.readings.keys().next().value);return t}).finally(()=>{this.inFlight.get(e)===r&&this.inFlight.delete(e)});return this.inFlight.set(e,r),r}move(e,t){let n=this.edge.locate(e);if(n.kind!==`ok`)throw Error(n.kind===`failed`?n.reason:`memento is not installed or not enabled for this project`);let r=gF(e);try{this.edge.move(n.value,e,t)}finally{this.readings.delete(r),this.inFlight.delete(r),this.fetch(r,e)}}};function vF(e){return{gitProvider:new Qb({watchers:e.watchers,logger:e.logger}),usageStore:new XP({logger:e.logger}),contextProvider:new ZP,metricsProvider:new nF,activityProvider:new lF,tmuxService:new hF,mementoProvider:new _F(kM()),autoCompact:pC,log:e.logger}}function yF(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function bF(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function xF(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function SF({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function CF(e){let t=SF(e);if(t.length===1)return e.text;let n=bF(t);return n.style=e.text.style,n}function wF(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,lead:s=[],trail:c=[]}=t;if(e.length===0)return[];let l=bF(e,a).pad(o),u=new W(` `.repeat(o)),d={...s.length>0&&{lead:bF([u,...s],a)},...c.length>0&&{trail:bF([...c,u],a)}};if(n===`auto`)return[{text:l,...d}];let f={justify:r,truncate:i};return n===`fill`?[{text:l,fill:f,...d}]:(xF(l,n,f),[{text:l,...d}])}const TF=RegExp(`\\x1b\\[[0-9;]*m|${Xi.source}`,`g`);function EF(e){return Wt(e.replace(TF,``))}function DF(e,t){let n=e.map(CF),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=rj(n,t).split(`
196
- `);if(i.length>1)return n;let a=Math.max(0,t.width-EF(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];xF(l,l.cellLength+c,i),n[t]=CF(e[t])}),n}function OF(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=kF(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:JA(a.style)};if(e.style.link){i();let r=kF([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function kF(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>AF(e.frag,n?n.add(e.style):e.style)),i=W.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function AF(e,t){let n=e.copy();return n.style=t,n}function jF(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,MF(e,t,o,n,r,i));return i}function MF(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=eS(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=Mx.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=eS(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=eS(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:FF(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:FF(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)return n.doctor===`run`?{kind:`doctor-run`}:{kind:`doctor-fix`,check:n.check};if(`ceiling`in n)return{kind:`ceiling`,args:bT(n)};if(`slash`in n)return{kind:`slash`,line:n.slash};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:FF(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 NF(e){return e.kind===`do`?NF(e.head):e}function PF(e){switch(NF(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`doctor-run`:case`doctor-fix`:case`ceiling`:case`slash`:case`do`:return!1}}function FF(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function IF(e,t){return e.has(t)?yy(e.read(t)):``}function LF(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function RF(e,t,n,r){let i=new W(e,{style:V.combine([r,new V({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function zF(e,t){return Math.max(e.members.indexOf(IF(t,e.stateVar)),0)}function BF(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=IF(r,e.stateVar);return{effects:[{verb:tk,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=IF(r,e.stateVar);return{effects:[{verb:tk,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=IF(r,e.stateVar);return{effects:[{verb:tk,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(zF(e,r)+1)%e.members.length];return{effects:[{verb:tk,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:nk,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:rk,args:[LF(e.text,fb(r))]}],active:!1};case`open`:return{effects:[{verb:ik,args:[LF(e.target,fb(r))]}],active:!1};case`persist-literal`:{let t=IF(r,e.stateVar);return{effects:[{verb:ck,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=IF(r,e.stateVar);return{effects:[{verb:ck,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(zF(e,r)+1)%e.members.length];return{effects:[{verb:ck,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:lk,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:pk,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:hk,args:[i]}],active:!1};case`redo`:return{effects:[{verb:gk,args:[i]}],active:!1};case`back`:return{effects:[{verb:_k,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:vk,args:[i]}],active:!1};case`save`:return{effects:[{verb:uk,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:dk,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:fk,args:[i,LF(e.name,fb(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:bk,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:xk,args:[i,e.check]}],active:!1};case`ceiling`:return{effects:[{verb:Ck,args:[i,...e.args]}],active:!1};case`slash`:return{effects:[{verb:wk,args:[i,e.line]}],active:!1};case`layout-op`:return{effects:[{verb:mk,args:[i,e.key,Tj(e.op)]}],active:!1};case`do`:{let a=BF(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>BF(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:mk,args:[i,e.key,Tj(r)]}],active:!1}}}}function VF(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:Ol(`action "${e}"`,n,t.members.length,zF(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 HF(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}=VF(e,NF(r),t,i),{effects:s,active:c}=BF(r,a,o,i,IF(i,`session.id`));return RF(a,Dk(s),c)}function UF(e){return{action:{fn:(t,...n)=>HF(t,n,e),argTypes:[`string`,`string`],arity:{kind:`variadic`},returnType:`T`}}}function WF(e,t){return RF(`✕`,Dk([{verb:tk,args:[IF(e,`session.id`),t,Tl]}]),!1)}function GF(e,t,n){return new V({bgcolor:L.fromRgba(t),color:L.fromRgba(uo(e,t,n))})}function KF(e,t,n){return new V({color:L.fromRgba(Or(eo(e,`warning`),t,lo,n))})}function qF(e,t,n){return V.combine([GF(e,t,n),KF(e,t,n)])}function JF(e,t,n){return GF(e.palette,wo(e.palette,e.disclosure,[t],n),n)}function YF(e,t,n,r,i,a){return r===void 0?n=>JF(e,{...n,distribution:t},i):(e,t)=>XF(r(t,n),a,i)}function XF(e,t,n){return new V({bgcolor:L.fromRgba(t),color:L.fromRgba(Or(eo(e,`primary`),t,4.5,n))})}function ZF(e,t,n){let r=t.map(t=>({label:t.label,indices:e.flatMap((e,n)=>e.group===t.id?[n]:[])})).filter(e=>e.indices.length>0);if(r.reduce((e,t)=>e+t.indices.length,0)!==e.length){let n=new Set(t.map(e=>e.id)),r=e.flatMap((e,t)=>n.has(e.group)?[]:[`#${t} (group "${e.group}")`]);throw Error(`library: ${r.join(`, `)} name a group the domain does not list (${[...n].join(`, `)})`)}return n?r.flatMap(e=>QF(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function QF(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function $F(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function eI(e){return{current:null,drawnAt:e}}function tI(e,t,n,r,i,a){let o={segName:t,placementId:n,palette:r,disclosure:i,tint:a,bg:void 0,drops:[]};return e.current=o,o}function nI(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 rI(e){return new W(e).cellLength}function iI(e){return Math.max(1,e.width-e.chromeCols-2*e.padding)}function aI(e){return Math.max(1,iI(e)-(rI(`✕`)+2*e.padding+e.seamCols))}function oI(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 sI(e,t,n){let r=rI(`←`)+1+rI(`→`)+1,i=oI(e,t,n);return(i.length>1?oI(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function cI(e,t){let n=[];for(let t of e)n.length>0&&n.push(new W(` `)),n.push(t);let r=W.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function lI(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 uI(e,t,n){let r=e.compiled.get(t),i=r&&NF(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 dI(e,t,n,r,i,a,o){let s=uI(i,e,`picker`),c=i.compiled.get(e),l=i.store,u=IF(l,`session.id`),d=`stateVar`in s?IF(l,s.stateVar):void 0,f=r?n.kind===`led`?aI(i):iI(i):1/0,p=n.kind===`led`?0:rI(`✕`)+1,m=s.library&&{groups:s.library.groups,entries:s.options.map(s.library.entry)},h=m===void 0?sI(s.options.map(rI),f,p):ZF(m.entries,m.groups,r),g=parseInt(IF(l,t.stateVar),10),_=Number.isInteger(g)?Math.max(0,Math.min(g,h.length-1)):0,v=h[_]??[],y=e=>Dk([{verb:tk,args:[u,t.key,String(e)]}]),b=n.kind===`led`?[]:[{verb:tk,args:[u,...n.writes.flatMap(([e,t])=>[e,t])]}],x=n.kind===`own`&&n.onPick?b:[],S=e=>Dk([...BF(c,e,e,l,u).effects,...x]),C=(e,t)=>{let n=s.options[e];return RF(t,S(n),n===d,a({index:e,count:s.options.length},n))},w=n.kind===`led`?[]:[RF(`✕`,Dk(b),!1,o)];_>0&&w.push(RF(`←`,y(_-1),!1));let ee=_<h.length-1?[RF(`→`,y(_+1),!1)]:[];if(m===void 0){let e=v.flatMap(e=>e.indices);return[cI([...w,...e.map(e=>C(e,s.options[e])),...ee],r)]}let te=new V({bold:!0}),ne=h.length>1?` ${_+1}/${h.length}`:``,re=v.length===1?[new W(`${v[0].label}${ne}`,{style:te})]:[],ie=[cI([...w,...re,...ee],r)];for(let e of v){v.length>1&&ie.push(cI([new W(e.label,{style:te})],r));let t=Math.max(...e.indices.map(e=>rI(s.options[e])));for(let n of e.indices){let e=s.options[n],i=m.entries[n].description,a=i===void 0?void 0:BA(i),o=` `.repeat(t-rI(e)+2),c=a===void 0?e:`${e}${o}${a}`;ie.push(cI([C(n,$F(c,f))],r))}}return ie}function fI(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{ob(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=lI(e,r,`set-int`,`an int action ({ set, int: true })`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=uI(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=nI(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let[d]=dI(n,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,YF(u,qa(void 0),e,l.paletteOf,t.drawnAt(),u.bg),KF(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function pI(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+rI(e(-(s+1)))+1+rI(e(s+1))+1;if(t>r)break;o=t,s+=1}return s}function mI(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=n.store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=IF(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return cI([],!0);let d=IF(o,t.stateVar),f=Math.max(l.indexOf(d),0),p=e=>((f+e)%u+u)%u,m=e=>l[p(e)],h=new Map,g=e=>{let t=h.get(e);if(t!==void 0)return t;let n=Dk(BF(s,m(e),m(e),o,c).effects);return h.set(e,n),n},_=e=>RF(m(e),g(e),m(e)===d,r({index:p(e),count:u},m(e))),v=a===void 0?_(0):RF(m(0),Dk(BF(n.compiled.get(a),m(0),void 0,o,c).effects),!1),y=pI(m,u,rI(`◀`)+1+v.cellLength+1+rI(`▶`),aI(n),i),b=e=>Array.from({length:y},(t,n)=>_(e*(n+1)));return cI([...b(-1).reverse(),RF(`◀`,g(-1),!1),v,RF(`▶`,g(1),!1),...b(1)],!0)}function hI(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(ob(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&PF(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=uI(e,n,`carousel`),l=nI(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return mI(n,c,e,YF(l,qa(void 0),e,c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}const gI=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function _I(e,t,n){let r=_o(e,{hue:Ba,depth:0},n);return[Va(t.hues).map((t,n)=>({text:gI[n%gI.length],colour:to(e,t)})),[{text:`▾ open`,colour:r.state},{text:`menu`,colour:r.plane}],[{text:`warn`,colour:eo(e,`warning`)},{text:`error`,colour:eo(e,`error`)}]]}function vI(e,t,n,r){let i=_I(e,t,n).flatMap((t,r)=>t.map(({text:t,colour:i},a)=>({gap:r>0&&a===0?` `:``,cell:new W(` ${t} `,{style:GF(e,i,n)})}))),a=[],o=0;for(let{gap:e,cell:t}of i){if(o+=e.length+t.cellLength,o>r)break;e!==``&&a.push(new W(e)),a.push(t)}let s=W.fromFragments(a);return s.overflow=`ignore`,s.end=``,s}function yI(e,t){return{themePreview:{fn:()=>vI(e.palette,e.variation,t.drawnAt(),aI(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}const bI=e=>e.slice(e.lastIndexOf(`.`)+1),xI=(e,t)=>{let n=new W(bI(e));return n.truncate(t,{marker:`…`}),n.plain};function SI(e,t){let n=e.map(e=>e.map(({name:e})=>rI(bI(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 CI(e,t,n,r){let i=SI(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new W(` ${xI(s,i)} `,{style:GF(l,Oo(l,{kind:`bar`,variation:t,address:c},n).tint,n)});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
197
- `),...e]));return o.overflow=`ignore`,o.end=``,o}function wI(e,t){return{layoutPreview:{fn:()=>CI(e.layout(),e.variation,t.drawnAt(),aI(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function TI(e,t,n,r){let i=nI(r.activeSegment,`{{ menu }}`),a=r.action,o=nv(i.placementId,e,n.key),s=av(o),c=tv(e),l=IF(a.store,o)===c,u=IF(a.store,`session.id`),d=l?Tl:c,f=RF(Ol(`{{ menu "${e}" }}`,t,2,+!!l),Dk([{verb:tk,args:[u,o,d,s,`0`]}]),!1);return i.drops.push(...l?(()=>{let t=r.activeSegment.drawnAt(),c=_o(i.palette,i.disclosure,t).plane;return dI(e,{key:s,stateVar:s},{kind:`own`,writes:[[o,Tl],[s,`0`]],onPick:n.closeOnPick},n.paged,a,YF(i,n.distribution,a,uI(a,e,`menu`).paletteOf,t,c),KF(i.palette,c,t))})():[]),f}const EI=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function DI(e,t){let n=t[t.length-1],r=EI(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:lv(r??{})}}function OI(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=DI(t,n);return TI(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function kI(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=AI(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new W(t?i:a,{style:l===void 0?void 0:new V({color:l})}))}let l=W.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function AI(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 jI(e){let t={fn:(()=>{let t=nI(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],arity:{kind:`exact`},returnType:`string`},n={fn:(()=>nI(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r=Ky(()=>nI(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),i={fn:((e,t,n,i,a,o,...s)=>{let c=o===void 0?void 0:[o,...MI(s)];return kI({value:e,max:t,width:n,filled:i,empty:a,colourAt:c===void 0?void 0:e=>String(r.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...r,bgOf:t,tint:n,gauge:i}}function MI(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 NI(e){let t=[],n=[];for(let r of e){if(!r.contains(`
191
+ `,l.join(e,`lib`),t.sessionId,t.cwd],env:OM(t),timeoutMs:3e3,category:`memento.read`});return n.ok?AM(n.stdout):X(kM(n))}function MM(e,t,n){let r=k({bin:l.join(e,wM),args:n.kind===`set`?[`set`,`session`,n.to]:[`clear`,`session`],env:OM(t),timeoutMs:5e3,category:`memento.move`});if(!r.ok)throw Error(kM(r))}function NM(){return{locate:e=>DM(oC(e.claudeConfigDir),e.projectDir),read:jM,move:MM}}function PM(e,t,n){let r=n===void 0?``:`CLAUDE_CONFIG_DIR=${zk(n)} `,i=e.added_dirs.map(e=>` --add-dir ${zk(e)}`).join(``);return`cd ${zk(e.project_dir)} && ${r}claude --resume ${zk(t)}${i}`}function FM(e,t,n){let r=pv(t(`preset`),e.globals.preset,e.presets),i=gv(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{};return{preset:r,presetCustomized:n(r),theme:Kx(a.palette,t(`theme`),i.palette),style:Go(a.style,t(`style`),i.style,e.styles),endcaps:Jo(a.endcaps,t(`endcaps`),i.endcaps),variation:ts(a.variation,t(`variation`),i.variation),separator:a.default_separator??i.default_separator,autoWrap:ls(a.autoWrap,t(`autoWrap`),i.autoWrap),padding:ds(a.padding,t(`padding`),i.padding),charset:a.charset??i.charset??`unicode`,updateNotice:us(a.updateNotice,t(`updateNotice`),i.updateNotice),colorCompatibility:a.colorCompatibility??i.colorCompatibility??`truecolor`}}function IM(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,charset:e.charset,width:t}}function LM(e){return{theme:e.theme,style:e.style,preset:e.preset,variation:e.variation}}function RM(e){return{preset:{effective:e.preset,customized:e.presetCustomized,bundled:cM(e.preset)},endcaps:{effective:e.endcaps},variation:{effective:e.variation},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding},updateNotice:{effective:e.updateNotice}}}const zM=10*1e3;function BM(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 VM(e,t){if(!(t<60))return e*3600/t}function HM(e,t,n,r){let i=r-t;if(i<50||i>zM)return;let a=n-e;if(!(a<=0))return a*1e3/i}function UM(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=HM(t.input,t.atMs,n.input,n.atMs),i=HM(t.output,t.atMs,n.output,n.atMs),a=HM(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 WM(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>zM)continue;let o=HM(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function GM(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function KM(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`,()=>GM(h.hostname())),i=n(`user`,()=>h.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function qM(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=>ny(t,e.helpers).keys(),o=gv(e,t);for(let e of Ro){let t=o[e];if(zo(t))for(let e of a(t))r.push(e)}for(let n of pc(hv(e,t).node)){if(n.when)for(let e of a(n.when))r.push(e);if(n.kind!==`segment`)continue;let t=e.segments[n.name];if(t){for(let e of[t.template,t.when,t.bg,t.fg])if(e)for(let t of a(e))r.push(t)}}let s=new Set;for(;r.length>0;){let e=r.pop();for(let t of YM(n,e)){if(i.has(t))continue;i.add(t);let e=n.get(t);if(e){if(e.kind===`input`)s.add(e.path);else if(e.kind===`template`)for(let t of a(e.template))r.push(t)}}}return s}function JM(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=qM(e,n);return t.set(n,i),i}}function YM(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 XM(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function ZM(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 QM(e,t,n,r,i,a,{configPath:o,...s}){let c=e=>XM(r,e),l=(t.clock??(()=>new Date))().getTime(),u=a.tmux??null,d=(e,t,n)=>t?n().catch(t=>X(`${e}: ${String(t)}`)):Promise.resolve(Y),[f,p,m,h,g,_,v,y,b,x,S]=await Promise.all([d(`git`,c(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,ZM(r),e.workspace?.project_dir)),d(`session`,c(`session.cost`)||c(`session.tokens`)||c(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),d(`today`,c(`today`),()=>t.usageStore.getTodayInfo(e,a.claudeConfigDir)),d(`context`,c(`context`)||c(`autocompact`),()=>t.contextProvider.getContextInfo(e)),d(`metrics`,c(`metrics`)||c(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),d(`activity`,c(`activity`),()=>t.activityProvider.getActivityInfo(e.session_id,e)),d(`tmux`,c(`tmux.session`),()=>u===null?Promise.resolve(Y):t.tmuxService.getSessionName(u)),d(`cache`,c(`cache`),()=>yM(e.transcript_path)),d(`speed`,c(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,l)),d(`memento`,c(`memento`),()=>t.mementoProvider.getCeiling(SM({sessionId:e.session_id,projectDir:e.workspace?.project_dir??``,cwd:n??e.workspace?.current_dir??``},a))),d(`autocompact`,c(`autocompact`),()=>Promise.resolve(t.autoCompact(aC(iC(a.claudeConfigDir)))))]),C=[],w=e=>{if(e.kind===`failed`){C.push(e.reason);return}return e.kind===`ok`?e.value:void 0},ee=oN(f);C.push(...ee.failures);let te=KM(a);C.push(...te.failures);let ne=w(p),re=w(m),ie=w(h),T=w(g),E=w(_),ae=w(v),oe=w(y),se=tN(x);x.kind===`failed`&&C.push(`memento: ${x.reason}`);let ce=$M(S,ie?.maxTokens);S.kind===`failed`&&C.push(`autocompact: ${S.reason}`);for(let e of C)t.log(`warn`,`provider fetch failed: ${e}`);let le=e.rate_limits?.five_hour,D=e.rate_limits?.seven_day,ue=le?BM(le.used_percentage,le.resets_at,18e6,l):void 0,de=D?BM(D.used_percentage,D.resets_at,6048e5,l):void 0,fe=ne?.session.cost,pe=T?.sessionDuration,me=c(`burn`)&&fe!=null&&pe!=null?VM(fe,pe):void 0,he=w(b),ge=he===void 0?void 0:UM(he),_e=he===void 0?void 0:WM(he),ve=ge!==void 0||_e!==void 0?{...ge,..._e!==void 0&&{history:_e}}:void 0,ye=aN(process.env.HOME??process.env.USERPROFILE),O=e.workspace?{...e.workspace,current_dir:aN(e.workspace.current_dir)??``,project_dir:aN(e.workspace.project_dir)??``,added_dirs:(e.workspace.added_dirs??[]).map(e=>aN(e)??e)}:e.workspace,be=ne===void 0?void 0:iN({cost:ne.session.cost,tokens:ne.session.tokens}),xe=re===void 0?void 0:{cost:re.cost,tokens:re.tokens},Se=T===void 0?void 0:iN({lastResponseTime:T.lastResponseTime,responseTime:T.responseTime,sessionDuration:T.sessionDuration,messageCount:T.messageCount,linesAdded:T.linesAdded,linesRemoved:T.linesRemoved}),Ce=E===void 0?void 0:nN(E);return{...e,...O!==void 0&&{workspace:O},...ye!==void 0&&{home:ye},...ee.git!==void 0&&{git:ee.git},...u!==null&&{tmux:{pane:u.pane,...ae!==void 0&&{session:ae}}},host:te.host,...RM(i),history:t.history(e.session_id),navigation:{back:t.navigation(e.session_id)},...s,...o!==null&&{configPath:o},resumeCommand:PM(O,e.session_id,a.claudeConfigDir),...be!==void 0&&{session:be},...xe!==void 0&&{today:xe},...me!==void 0&&{burn:{costPerHour:me}},...ve!==void 0&&{speed:ve},...c(`block`)&&le!==void 0&&{block:{nativeUtilization:le.used_percentage,resetsAt:le.resets_at,...ue!==void 0&&{etaMinutes:ue}}},...D!==void 0&&{weekly:{percentage:D.used_percentage,resetsAt:D.resets_at,...de!==void 0&&{etaMinutes:de}}},...oe!==void 0&&{cache:{expiresAt:oe}},...ie!==void 0&&{context:{totalTokens:ie.totalTokens,contextLeft:ie.contextLeftPercentage}},...Se!==void 0&&{metrics:Se},...Ce!==void 0&&{activity:Ce},...se!==void 0&&{memento:se},...ce!==void 0&&{autocompact:ce}}}function $M(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return mC(e.value,t)}}const eN=e=>e.trim().split(`
192
+ `).at(-1).trim();function tN(e){switch(e.kind){case`absent`:return;case`failed`:return{error:eN(e.reason)};case`ok`:{let{ceiling:t,session:n}=e.value;return{ceiling:t===`off`?0:t,off:t===`off`,session:n??``}}}}function nN(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=rN(e.running),i=rN(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}},o=e.ticket===null?void 0:{id:e.ticket.id,phase:e.ticket.phase,...e.ticket.epic!==null&&{epic:e.ticket.epic},...e.ticket.unread!==null&&{unread:e.ticket.unread}};if(!(o===void 0&&e.command===null&&n===void 0&&a===void 0))return{...o!==void 0&&{ticket:o},...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function rN(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function iN(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 aN(e){return e===void 0||e.length===0||l.sep!==`\\`?e:e.replace(/\\/g,`/`)}function oN(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 sN={theme:e=>e.theme.kind===`decided`?e.theme.name:null,preset:e=>e.preset,style:e=>e.style.kind===`decided`?e.style.name:null,endcaps:e=>e.endcaps,variation:e=>e.variation,autoWrap:e=>e.autoWrap?ns:rs,padding:e=>String(e.padding),updateNotice:e=>e.updateNotice?ns:rs},cN=Object.entries(Ox),lN=new Set(kx.map(e=>e.sessionKey)),uN=()=>!1;function dN(e,t){return FM(e,e=>lN.has(e)?t(e):null,uN)}function fN(e,t,n,r){return e.flatMap(([e,i])=>{let a=sN[e](t);return a===null||a===sN[e](n(e))?[]:[{...i,value:a,target:r(i)}]})}function pN(e,t,n){return sN[n](dN(e,t))}function mN(e,t){let n=dN(e,t),r=FM(e,()=>null,uN),i=FM(e,e=>e===Ox.preset.sessionKey?n.preset:null,uN);return fN(cN,n,e=>e===`preset`?r:i,t=>hN(e,n.preset,t.configKey))}function hN(e,t,n){return n in(mv(e.presets,t).globals??{})?pS(t,n):n}function gN(e,t,n){let r=pv(t(Ox.preset.sessionKey),e.globals.preset,e.presets),i=mS(n);return{key:i?.scope===`globals`?hN(e,r,i.field):n,globals:gv(e,r)}}function _N(e,t){let{preset:n}=dN(e,t);return bN(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:Oc(a,s);return c===void 0||Dc(c)===Dc(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function vN(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return fv(e.presets).flatMap(n=>{let i=bN(e,n);return[...new Set(i.filter(e=>r.has(e.key)).map(e=>e.id))].flatMap(e=>{let n=i.filter(t=>t.id===e);return Tc(Object.fromEntries(n.map(e=>[e.setting,e.decl])),Object.fromEntries(n.map(e=>{let n=r.get(e.key)??t(e.key),i=n===null?void 0:Oc(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const yN=new WeakMap;function bN(e,t){let n=yN.get(e)??new Map;yN.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...pc(hv(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Cc(e.segments[t.name])[n];return{id:r,setting:n,key:i,decl:a,saved:t.settings?.[n]??a.default}})),a=[...new Map(i.map(e=>[e.key,e])).values()];return n.set(t,a),a}function xN(e,t){let n=dN(e,t),r=FM(e,e=>e===Ox.preset.sessionKey?n.preset:null,uN);return{from:n.preset,globals:mv(e.presets,n.preset).globals??{},picks:fN(cN.filter(([e])=>e!==`preset`),n,()=>r,e=>e.configKey),placements:_N(e,t)}}function SN(e){return{sessionKeys:kx.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...iu(e)?sM.map(t=>pS(t,e)):[]]}}function CN(e){return new Set(kx.map(e=>e.configKey).filter(t=>SN(t).fileKeys.some(t=>EN(e,TN(t)))))}function wN(e,t,n){let r=mN(e,n),i=new Set(r.map(e=>e.configKey)),a=Px(e=>i.has(Ox[e].configKey)||t.has(Ox[e].configKey));return{unsaved:r.length+_N(e,n).length,resettable:a}}function TN(e){let t=mS(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return hS(t)}function EN(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&EN(e[n],r)}const DN=No(),ON=new Set(DN),kN=new Set(Ko),AN=e=>e?ON.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${DN.join(`, `)})`}:{ok:!1,reason:`theme name is required`},jN=e=>e?kN.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Ko.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},MN=new Set([`1`,`true`]),NN=new Set([`0`,`false`]),PN={endcaps:jN,theme:AN,"toolbar-expanded":e=>MN.has(e)?{ok:!0,value:`1`}:NN.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},FN=Vj(PN,`state`,HN);function IN(e,t){return FN.register(e,t)}function LN(e){return FN.gateFor(e)}function RN(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:eS(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 zN(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(PN,e.key))}function BN(e,t,n){let r=Fx.get(n);if(r!==void 0)return pN(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 VN(e){let t=eT(e);return zN(Object.values(e.actions).flatMap(e=>RN(e,t)))}function HN(e){return zj(VN(e))}const UN=`update.dismissed`,WN=`updateNotice`,GN=Ox.updateNotice.sessionKey;function KN(e){return e.kind===`source`?e.newer.digest:Hk(e.newer)}const qN=e=>`${e.version} [${wj(e.digest)}]`;function JN(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:qN(e.newer),running:qN(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:Hk(e.newer),running:Hk(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${Wk}@${Hk(e.newer)}`,`install`]}}}}const YN={kind:`idle`},XN={kind:`running`};function ZN(e,t,n){if(e===null)return[];let r=KN(e);if(!n.enabled||n.dismissed===r)return[];let i=JN(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(`
193
+ `),c=jk([{verb:dk,args:[s]}]),l=t.kind===`running`?fj(`[${i.busy}]`,c):fj(`[${i.act}]`,jk([{verb:Ck,args:[n.sessionId]}]));return[{severity:dj,message:s,lines:[[fj(a,c),l,fj(`[dismiss]`,jk([{verb:ak,args:[n.sessionId,UN,r]}])),fj(`[disable]`,jk([{verb:fk,args:[n.sessionId,WN,`false`]},{verb:ak,args:[n.sessionId,GN,`false`]}]))],...o.map(e=>[fj(e,c)])]}]}function QN(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 $N(e){switch(e.kind){case`current`:return[`info`,`build: current ${qN(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${qN(e.source)}, running ${qN(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function eP(e){switch(e.kind){case`current`:return[`info`,`release: current ${Hk(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${Hk(e.latest)}, running ${Hk(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${Hk(e.installed)}, latest ${Hk(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function tP(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const nP=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function rP(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=nP(e.stderr)??e.error??nP(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function iP(){let e=[Uj(WN,[`false`]),IN(GN,[`false`]),IN(UN,[])];return()=>e.forEach(e=>e())}function aP(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=YN,d=null,f=tP(s),p=tP(s),m=()=>QN(c,l);function h(){let e=m(),t=e===null?null:KN(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:IN(UN,[t])})}function g(){c=Oj(t,Ej),f($N(c)),h()}async function _(){l=Kk(hO,await Gk(Wk,a,i)),p(eP(l)),h()}return{arm(){iP(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>ZN(m(),u,e),act(){let e=m();if(e===null)throw new $(`apply-update: nothing newer is known to apply`);let t=JN(e);if(u.kind===`running`)throw new $(`apply-update: already ${t.busy}`);u=XN,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),Ae({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=YN,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=rP(n);u={kind:`failed`,identity:KN(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}var oP=class{static CACHE_DIR=Ie();static USAGE_CACHE_DIR=l.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=l.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=l.join(this.LOCKS_DIR,e);if(!r.existsSync(t))return!1;try{let n=r.readFileSync(t,`utf-8`),i=parseInt(n.trim(),10);if(isNaN(i))return O(`Invalid PID in lock file ${e}, removing stale lock`),r.unlinkSync(t),!1;try{return process.kill(i,0),!0}catch(n){return n.code===`ESRCH`?(O(`Removing stale lock file ${e} for dead process ${i}`),r.unlinkSync(t),!1):(O(`Error checking process ${i} for lock ${e}:`,n),!0)}}catch(t){return O(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=l.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await r.promises.writeFile(n,a,{flag:`wx`}),O(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await D(50);else throw e}return O(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=l.join(this.LOCKS_DIR,e);try{await r.promises.unlink(t),O(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&O(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([r.promises.mkdir(this.CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){O(`Failed to create cache directories:`,e)}}static createProjectHash(e){return se(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=l.join(this.USAGE_CACHE_DIR,`${e}.json`),i=`${e}.usage.lock`;for(let a=0;a<3;a++){if(this.isLocked(i)){O(`Cache for ${e} is locked, waiting...`),await D(75);continue}try{let i=await r.promises.readFile(n,`utf-8`),a=JSON.parse(i);return!t||a.timestamp>=t?(O(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(a.data)):(O(`${e} cache outdated: cache=${a.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return O(`No shared ${e} usage cache found`),null;O(`Attempt ${a+1} failed to read ${e} cache: ${t.message}. Retrying...`),await D(75)}}return O(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let i=`${e}.usage.lock`;if(!await this.acquireLock(i)){O(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=l.join(this.USAGE_CACHE_DIR,`${e}.json`),a=JSON.stringify({data:t,timestamp:n||Date.now()});await r.promises.writeFile(i,a,`utf-8`),O(`[CACHE-SET] ${e} disk cache stored`)}catch(t){O(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(i)}}};const sP={"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 cP=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 oP.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await oP.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new ie(this.GITHUB_PRICING_URL),n=le({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){O(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let r=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){O(`Response too large`),n.destroy(),e(null);return}r+=t}),t.on(`end`,()=>{try{let t=JSON.parse(r),n=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(O(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),O(`Pricing last updated: ${n?.updated||`unknown`}`),e(i)):(O(`Invalid pricing data structure`),e(null))}catch(t){O(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{O(`Response error:`,t),e(null)})});n.on(`error`,t=>{O(`Request error:`,t),e(null)}),n.on(`timeout`,()=>{O(`Request timeout`),n.destroy(),e(null)}),n.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return O(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return O(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,O(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),O(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,O(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(O(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(sP).length} models`),this.executionCache=sP,O(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(sP).length} models`),sP)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return O(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),O(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const lP=String.raw`(?:^|[\s;&|(])`,uP=e=>RegExp(`(?:^|:)(?:${e})$`),dP=[{phase:`impl`,tool:`Edit`,match:/^/},{phase:`impl`,tool:`MultiEdit`,match:/^/},{phase:`impl`,tool:`Write`,match:/^/},{phase:`impl`,tool:`NotebookEdit`,match:/^/},{phase:`review`,tool:`Bash`,match:RegExp(`${lP}gh\\s+pr\\s+create\\b`)},{phase:`review`,tool:`Skill`,match:uP(`code-review|simplify`)},{phase:`groom`,tool:`Bash`,match:RegExp(`${lP}lit\\s+(done|close)\\b`)},{phase:`groom`,tool:`Skill`,match:uP(`groom-backlog`)},{phase:`handoff`,tool:`Skill`,match:uP(`message-in-a-bottle`)}],fP=e=>RegExp(`${lP}lit\\s+(?:${e})(?:\\s+(?:--?[\\w-]+(?:=\\S*)?|''))*\\s+([A-Za-z0-9][\\w.-]*)`),pP=[{verb:fP(`start`),to:`in_progress`},{verb:fP(`done|close`),to:`closed`}];function mP(e){return dP.find(t=>t.tool===e.tool&&t.match.test(e.subject))?.phase}function hP(e,t){if(t.tool===`Bash`)for(let{verb:n,to:r}of pP){let i=n.exec(t.subject)?.[1];if(i!==void 0)return{call:e,id:i,to:r}}}const gP=/^lit:state (.*)$/gm;function _P(e){return[...e.matchAll(gP)].map(([e,t])=>vP(t)??{kind:`unreadable`,line:e.trim()})}function vP(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=`object`||!t)return;let{id:n,status:r,epic:i}=t;if(typeof n!=`string`||typeof r!=`string`)return;if(i===null)return{kind:`state`,id:n,status:r,epic:null};if(typeof i!=`object`||i===void 0)return;let a=i;if(!(typeof a.id!=`string`||typeof a.done!=`number`||typeof a.total!=`number`))return{kind:`state`,id:n,status:r,epic:{id:a.id,done:a.done,total:a.total}}}function yP(e,t){let n=t??{};return{tool:e,subject:e===`Bash`&&typeof n.command==`string`?SP(n.command):e===`Skill`&&typeof n.skill==`string`?n.skill:e}}const bP=/(<<-?\s*(['"]?)(\w+)\2[^\n]*\n)[\s\S]*?\n\s*\3(?=\n|$)/g,xP=/'[^']*'|"(?:[^"\\]|\\.)*"/g;function SP(e){return e.replace(bP,`$1`).replace(xP,`''`)}function CP(e){return typeof e==`string`?[e]:Array.isArray(e)?e.flatMap(e=>typeof e==`object`&&e&&typeof e.text==`string`?[e.text]:[]):[]}const wP=/^(\S+) \[(open|in_progress|closed)\//gm,TP=/^Ticket (\S+) has been closed\./gm,EP={sentinels:[],said:[]};function DP(e){let t;for(let n of CP(e)){let e=n.includes(`lit:state `),r=n.includes(` [`),i=n.includes(`has been closed.`);if(!(!e&&!r&&!i)){if(t??={sentinels:[],said:[]},e&&t.sentinels.push(..._P(n)),r)for(let[,e,r]of n.matchAll(wP))t.said.push({id:e,status:r});if(i)for(let[,e]of n.matchAll(TP))t.said.push({id:e,status:`closed`})}}if(t===void 0)return EP;for(let e of t.sentinels)e.kind===`state`&&t.said.push({id:e.id,status:e.status});return t}const OP=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function kP(e){if(typeof e==`string`)return OP.exec(e)?.[1]}function AP(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 jP(e){let t=e.message?.content,n=e.type===`user`,r=[],i=[],a,o,s=[],c=[],l,u=[];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});let i=yP(n,t.input),o=hP(e,i);o!==void 0&&s.push(o),l=mP(i)??l,n===`TodoWrite`&&(a=AP(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id,n=DP(t.content);if(u.push(...n.sentinels),typeof e==`string`){i.push(e);for(let t of n.said)c.push({call:e,...t})}break}case`text`:o??=t.text;break;default:break}}let d=n?kP(o):void 0,f=s.length===0&&l===void 0&&u.length===0&&c.length===0?void 0:{...s.length>0&&{claims:s},...l!==void 0&&{phase:l},...u.length>0&&{sentinels:u},...c.length>0&&{said:c}};if(!(r.length===0&&i.length===0&&a===void 0&&d===void 0&&f===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...d!==void 0&&{command:d},...f!==void 0&&{lit:f}}}function MP(e){if(e!==void 0)return[e];let t=g();return[p(t,`.config`,`claude`),p(t,`.claude`)].filter(e=>a(e))}async function NP(e){let t=[];for(let n of e){let e=p(n,`projects`);if(a(e))try{let n=await fM(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=p(e,r.name);t.push(n)}}catch(t){O(`Failed to read projects directory ${e}:`,t)}}return t}async function PP(e,t,n){let r=[],i=p(t,e,`subagents`);try{let t=(await fM(i)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let a of t){let t=p(i,a);if(n?.has(t)){r.push(t);continue}try{let n=(await pM(t,`utf-8`)).split(`
194
+ `)[0];n&&JSON.parse(n).sessionId===e&&r.push(t)}catch{O(`Failed to check agent file ${t}`)}}}catch(e){O(`Failed to read subagents directory ${i}:`,e)}return r}function FP(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 IP=new Map;async function LP(e){try{let t=await mM(e),n=t.size,r=IP.get(e);if(r&&r.mtime===t.mtimeMs&&r.size===n)return O(`[parse-cache] hit ${e}`),IP.delete(e),IP.set(e,r),r.entries;let i;return n>1048576?(O(`Using streaming parser for large file ${e} (${Math.round(n/1024)}KB)`),i=await HP(e)):i=await BP(e),O(`Parsed ${i.length} entries from ${e}`),n>5242880?i:(IP.delete(e),IP.size>=16&&IP.delete(IP.keys().next().value),IP.set(e,{mtime:t.mtimeMs,size:n,entries:i}),i)}catch(t){if(t.code===`ENOENT`)return O(`Transcript not present yet: ${e}`),[];throw t}}function RP(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:jP(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 zP(e){let t=[];for(let n of e.split(`
195
+ `))if(n.trim())try{let e=RP(JSON.parse(n));e&&t.push(e)}catch(e){O(`Failed to parse JSONL line: ${e}`);continue}return t}async function BP(e){return zP(await pM(e,`utf-8`))}async function VP(e,t){let n=await hM(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:zP(r.subarray(0,c+1).toString(`utf-8`)),cursor:{offset:i+c+1,mtimeMs:a,ino:o},reset:s})}async function HP(e){return new Promise((t,n)=>{let r=[],a=i(e,{encoding:`utf8`}),o=ue({input:a,crlfDelay:1/0});o.on(`line`,e=>{let t=e.trim();if(t)try{let e=RP(JSON.parse(t));e&&r.push(e)}catch(e){O(`Failed to parse JSONL line: ${e}`)}}),o.on(`close`,()=>{t(r)}),o.on(`error`,t=>{O(`Streaming parser error for ${e}:`,t),n(t)}),a.on(`error`,t=>{O(`File stream error for ${e}:`,t),n(t)})})}var UP=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 WP(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 GP=new Map,KP={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},qP={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function JP(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function YP(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function XP(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}async function ZP(e,t,n,r){let i=JP(new Date(YP())),a=e&&!t?e:void 0,o=a?.entries??0,s=a?.cost??0,c=a?{...a.breakdown}:XP(),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 cP.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=JP(new Date(e.timestamp));if(r<i)continue;let a=l.get(r)??{...KP};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 QP(e){let t=0,n=0,r=XP(),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)??{...KP};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:qP,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 $P(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 eF=class{entries=new Map;flight=new UP;seeded=new Map;seededDay=``;speedRings=new Map;speedFlight=new UP;maxEntries;staleAgeMs;log;hits=0;misses=0;sweeps=0;seeds=0;sweepTimer=null;constructor(e={}){this.log=e.logger??Ub,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:qP,i=t?.cost?.total_cost_usd??null;return J({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e,t){let n=JP(new Date),r=MP(t);try{await this.ensureSeeded(n,r)}catch(e){return X(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let i=await this.ingest(e?.session_id??``,e?.transcript_path);if(i.kind===`failed`)return i;let a=r.map(e=>p(e,`projects`)+m),o={...KP},s=!1;for(let[t,r]of this.entries){let i=r.transcriptPath??``,c=t===e?.session_id||a.some(e=>i.startsWith(e))?r.days:GP;s||=c.has(n);let l=c.get(n)??KP;o.cost+=l.cost,o.input+=l.input,o.output+=l.output,o.cacheCreation+=l.cacheCreation,o.cacheRead+=l.cacheRead}return s?J({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:n}):Y}async observeSpeed(e,t,n){let r=lM(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,r);if(i.kind===`failed`)return i;let a=WP(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??lM(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 PP(e,d(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 VP(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 ZP(r,l,s,c)),e===t&&(a=c.mtimeMs)}return J({files:i,...QP(i),mainMtime:a})}ensureSeeded(e,t){this.seededDay!==e&&(this.seeded.clear(),this.seededDay=e);let n=t.join(`\0`),r=this.seeded.get(n);if(r)return r;let i=this.seed(t);return this.seeded.set(n,i),i.catch(()=>{this.seeded.get(n)===i&&this.seeded.delete(n)}),i}async seed(e){let t=YP(),n=await NP(e),r=[];for(let e of n){let n;try{n=await fM(e)}catch{continue}for(let i of n){if(!i.endsWith(`.jsonl`))continue;let n=p(e,i),a;try{a=(await mM(n)).mtimeMs}catch{continue}a<t||r.push({sessionId:i.slice(0,-6),path:n,mtime:a})}}await $P(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,e.mtime);t.kind===`failed`&&this.log(`warn`,`usageStore seed: ${t.reason}`)}),this.seeds++,this.log(`info`,`usageStore seed sessions=${r.length} dirs=${e.join(`,`)}`)}sweepStale(){let e=Date.now(),t=0;for(let[n,r]of this.entries)e-r.lastSeenAt>this.staleAgeMs&&(this.entries.delete(n),this.speedRings.delete(n),t++);return t>0&&(this.sweeps++,this.log(`info`,`usageStore sweep dropped=${t}`)),t}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e),this.speedRings.delete(e),this.log(`info`,`usageStore evict ${e}`)}}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.entries.clear(),this.seeded.clear(),this.speedRings.clear()}},tF=class{thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return O(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);O(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t){try{O(`Calculating context tokens from transcript: ${e}`);let n=await LP(e);if(n.length===0)return O(`No entries in transcript`),Y;let r=null;for(let e=n.length-1;e>=0;e--){let t=n[e];if(t&&t.message?.usage?.input_tokens&&t.isSidechain!==!0){r=t,O(`Context segment: Found most recent entry at ${t.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let e=r.message.usage,n=(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0);return O(`Most recent main chain context: ${n} tokens (limit: ${t})`),J({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return O(`No main chain entries with usage data found`),Y}catch(e){return X(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return J(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}},nF=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=lM(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await VP(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 rF={messageCount:0,recent:[]};function iF(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +!!FP(t),recent:n.length>20?n.slice(-20):n}}function aF(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(FP(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 oF=class{fold=new nF(rF,iF);async getMetricsInfo(e,t){if(O(`Getting metrics from hook data for session: ${e}`),!t.cost)return Y;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?X(`metrics (${e}): ${n.reason}`):J({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:aF(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})}};function sF(e,t,n){return n.some(e=>e.call===t.call&&e.id===t.id&&e.status===t.to)?t.to===`closed`?e?.id===t.id?null:e:{id:t.id,phase:`prep`,epic:e?.id===t.id?e.epic:null,unread:null}:e}function cF(e,t,n){let r=[...e.claims,...t?.claims??[]],i=e=>n.includes(e.call),a=r.filter(i).reduce((e,n)=>sF(e,n,t?.said??[]),e.ticket),o=r.filter(e=>!i(e));if(a===null||t===void 0)return{claims:o,ticket:a};let s=t.sentinels??[],c=s.findLast(e=>e.kind===`state`&&e.id===a.id),l=s.findLast(e=>e.kind===`unreadable`);return{claims:o,ticket:{id:a.id,phase:t.phase??a.phase,epic:c?.kind===`state`?c.epic:a.epic,unread:l?.kind===`unreadable`?l.line:a.unread}}}const lF={ticket:null,claims:[],command:null,todos:[],pending:[],done:[]};function uF(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 dF(e,t){if(t.isSidechain)return e;let n=FP(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=uF(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos,...cF(n,r.lit,r.finished??[])}}function fF(e){return{ticket:e.ticket,command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>uF(e,t.name),[]),done:e.done}}var pF=class{fold=new nF(lF,dF);async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?X(`activity (${e}): ${n.reason}`):J(fF(n.value))}};function mF(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function hF(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function gF(e,t,n,r){return hF(k(mF(e,t,n,r)),n)}async function _F(e,t,n){return hF(await Ae(mF(e,t,n)),n)}const vF=e=>`${e.socket}\n${e.pane}`;var yF=class{names=new Map;asking=new UP;constructor(e=Date.now){this.now=e}getSessionName(e){let t=vF(e),n=this.names.get(t);if(n&&this.now()-n.at<3e4)return Promise.resolve(n.outcome);let r=this.asking.run(t,()=>this.ask(t,e));return n?Promise.resolve(n.outcome):r}async ask(e,t){O(`Getting tmux session name for pane ${t.pane} on ${t.socket}`);let n=await _F(t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]),r=n.kind===`ok`?n.stdout.trim():``,i=n.kind===`ok`?r?J(r):Y:X(n.reason);for(this.names.delete(e),this.names.set(e,{outcome:i,at:this.now()});this.names.size>64;)this.names.delete(this.names.keys().next().value);return i}};const bF=e=>JSON.stringify([e.sessionId,e.projectDir,e.cwd,e.claudeConfigDir,e.env===void 0?null:Qe.map(t=>e.env?.[t]??null)]);var xF=class{readings=new Map;inFlight=new Map;constructor(e,t=Date.now){this.edge=e,this.now=t}getCeiling(e){let t=bF(e),n=this.readings.get(t);if(n&&this.now()-n.at<1e4)return Promise.resolve(n.outcome);let r=this.inFlight.get(t)??this.fetch(t,e);return n?Promise.resolve(n.outcome):r}fetch(e,t){let n=this.edge.locate(t),r=(n.kind===`ok`?this.edge.read(n.value,t):Promise.resolve(n)).then(t=>{if(this.inFlight.get(e)!==r)return t;for(this.readings.delete(e),this.readings.set(e,{outcome:t,at:this.now()});this.readings.size>64;)this.readings.delete(this.readings.keys().next().value);return t}).finally(()=>{this.inFlight.get(e)===r&&this.inFlight.delete(e)});return this.inFlight.set(e,r),r}move(e,t){let n=this.edge.locate(e);if(n.kind!==`ok`)throw Error(n.kind===`failed`?n.reason:`memento is not installed or not enabled for this project`);let r=bF(e);try{this.edge.move(n.value,e,t)}finally{this.readings.delete(r),this.inFlight.delete(r),this.fetch(r,e)}}};function SF(e){return{gitProvider:new Qb({watchers:e.watchers,logger:e.logger}),usageStore:new eF({logger:e.logger}),contextProvider:new tF,metricsProvider:new oF,activityProvider:new pF,tmuxService:new yF,mementoProvider:new xF(NM()),autoCompact:pC,log:e.logger}}function CF(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function wF(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function TF(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function EF({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function DF(e){let t=EF(e);if(t.length===1)return e.text;let n=wF(t);return n.style=e.text.style,n}function OF(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,lead:s=[],trail:c=[]}=t;if(e.length===0)return[];let l=wF(e,a).pad(o),u=new W(` `.repeat(o)),d={...s.length>0&&{lead:wF([u,...s],a)},...c.length>0&&{trail:wF([...c,u],a)}};if(n===`auto`)return[{text:l,...d}];let f={justify:r,truncate:i};return n===`fill`?[{text:l,fill:f,...d}]:(TF(l,n,f),[{text:l,...d}])}const kF=RegExp(`\\x1b\\[[0-9;]*m|${Xi.source}`,`g`);function AF(e){return Wt(e.replace(kF,``))}function jF(e,t){let n=e.map(DF),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=sj(n,t).split(`
196
+ `);if(i.length>1)return n;let a=Math.max(0,t.width-AF(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];TF(l,l.cellLength+c,i),n[t]=DF(e[t])}),n}function MF(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=NF(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:QA(a.style)};if(e.style.link){i();let r=NF([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function NF(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>PF(e.frag,n?n.add(e.style):e.style)),i=W.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function PF(e,t){let n=e.copy();return n.style=t,n}function FF(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,IF(e,t,o,n,r,i));return i}function IF(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=eS(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=Mx.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=eS(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=eS(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:zF(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:zF(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)return n.doctor===`run`?{kind:`doctor-run`}:{kind:`doctor-fix`,check:n.check};if(`ceiling`in n)return{kind:`ceiling`,args:bT(n)};if(`slash`in n)return{kind:`slash`,line:n.slash};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:zF(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 LF(e){return e.kind===`do`?LF(e.head):e}function RF(e){switch(LF(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`doctor-run`:case`doctor-fix`:case`ceiling`:case`slash`:case`do`:return!1}}function zF(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function BF(e,t){return e.has(t)?yy(e.read(t)):``}function VF(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function HF(e,t,n,r){let i=new W(e,{style:V.combine([r,new V({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function UF(e,t){return Math.max(e.members.indexOf(BF(t,e.stateVar)),0)}function WF(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=BF(r,e.stateVar);return{effects:[{verb:ak,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=BF(r,e.stateVar);return{effects:[{verb:ak,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=BF(r,e.stateVar);return{effects:[{verb:ak,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(UF(e,r)+1)%e.members.length];return{effects:[{verb:ak,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:ok,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:sk,args:[VF(e.text,fb(r))]}],active:!1};case`open`:return{effects:[{verb:ck,args:[VF(e.target,fb(r))]}],active:!1};case`persist-literal`:{let t=BF(r,e.stateVar);return{effects:[{verb:fk,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=BF(r,e.stateVar);return{effects:[{verb:fk,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(UF(e,r)+1)%e.members.length];return{effects:[{verb:fk,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:pk,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:_k,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:yk,args:[i]}],active:!1};case`redo`:return{effects:[{verb:bk,args:[i]}],active:!1};case`back`:return{effects:[{verb:xk,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:Sk,args:[i]}],active:!1};case`save`:return{effects:[{verb:mk,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:hk,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:gk,args:[i,VF(e.name,fb(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:wk,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Tk,args:[i,e.check]}],active:!1};case`ceiling`:return{effects:[{verb:Dk,args:[i,...e.args]}],active:!1};case`slash`:return{effects:[{verb:Ok,args:[i,e.line]}],active:!1};case`layout-op`:return{effects:[{verb:vk,args:[i,e.key,kj(e.op)]}],active:!1};case`do`:{let a=WF(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>WF(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:vk,args:[i,e.key,kj(r)]}],active:!1}}}}function GF(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:Ol(`action "${e}"`,n,t.members.length,UF(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 KF(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}=GF(e,LF(r),t,i),{effects:s,active:c}=WF(r,a,o,i,BF(i,`session.id`));return HF(a,jk(s),c)}function qF(e){return{action:{fn:(t,...n)=>KF(t,n,e),argTypes:[`string`,`string`],arity:{kind:`variadic`},returnType:`T`}}}function JF(e,t){return HF(`✕`,jk([{verb:ak,args:[BF(e,`session.id`),t,Tl]}]),!1)}function YF(e,t,n){return new V({bgcolor:L.fromRgba(t),color:L.fromRgba(uo(e,t,n))})}function XF(e,t,n){return new V({color:L.fromRgba(Or(eo(e,`warning`),t,lo,n))})}function ZF(e,t,n){return V.combine([YF(e,t,n),XF(e,t,n)])}function QF(e,t,n){return YF(e.palette,wo(e.palette,e.disclosure,[t],n),n)}function $F(e,t,n,r,i,a){return r===void 0?n=>QF(e,{...n,distribution:t},i):(e,t)=>eI(r(t,n),a,i)}function eI(e,t,n){return new V({bgcolor:L.fromRgba(t),color:L.fromRgba(Or(eo(e,`primary`),t,4.5,n))})}function tI(e,t,n){let r=t.map(t=>({label:t.label,indices:e.flatMap((e,n)=>e.group===t.id?[n]:[])})).filter(e=>e.indices.length>0);if(r.reduce((e,t)=>e+t.indices.length,0)!==e.length){let n=new Set(t.map(e=>e.id)),r=e.flatMap((e,t)=>n.has(e.group)?[]:[`#${t} (group "${e.group}")`]);throw Error(`library: ${r.join(`, `)} name a group the domain does not list (${[...n].join(`, `)})`)}return n?r.flatMap(e=>nI(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function nI(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function rI(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function iI(e){return{current:null,drawnAt:e}}function aI(e,t,n,r,i,a){let o={segName:t,placementId:n,palette:r,disclosure:i,tint:a,bg:void 0,drops:[]};return e.current=o,o}function oI(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 sI(e){return new W(e).cellLength}function cI(e){return Math.max(1,e.width-e.chromeCols-2*e.padding)}function lI(e){return Math.max(1,cI(e)-(sI(`✕`)+2*e.padding+e.seamCols))}function uI(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 dI(e,t,n){let r=sI(`←`)+1+sI(`→`)+1,i=uI(e,t,n);return(i.length>1?uI(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function fI(e,t){let n=[];for(let t of e)n.length>0&&n.push(new W(` `)),n.push(t);let r=W.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function pI(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 mI(e,t,n){let r=e.compiled.get(t),i=r&&LF(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 hI(e,t,n,r,i,a,o){let s=mI(i,e,`picker`),c=i.compiled.get(e),l=i.store,u=BF(l,`session.id`),d=`stateVar`in s?BF(l,s.stateVar):void 0,f=r?n.kind===`led`?lI(i):cI(i):1/0,p=n.kind===`led`?0:sI(`✕`)+1,m=s.library&&{groups:s.library.groups,entries:s.options.map(s.library.entry)},h=m===void 0?dI(s.options.map(sI),f,p):tI(m.entries,m.groups,r),g=parseInt(BF(l,t.stateVar),10),_=Number.isInteger(g)?Math.max(0,Math.min(g,h.length-1)):0,v=h[_]??[],y=e=>jk([{verb:ak,args:[u,t.key,String(e)]}]),b=n.kind===`led`?[]:[{verb:ak,args:[u,...n.writes.flatMap(([e,t])=>[e,t])]}],x=n.kind===`own`&&n.onPick?b:[],S=e=>jk([...WF(c,e,e,l,u).effects,...x]),C=(e,t)=>{let n=s.options[e];return HF(t,S(n),n===d,a({index:e,count:s.options.length},n))},w=n.kind===`led`?[]:[HF(`✕`,jk(b),!1,o)];_>0&&w.push(HF(`←`,y(_-1),!1));let ee=_<h.length-1?[HF(`→`,y(_+1),!1)]:[];if(m===void 0){let e=v.flatMap(e=>e.indices);return[fI([...w,...e.map(e=>C(e,s.options[e])),...ee],r)]}let te=new V({bold:!0}),ne=h.length>1?` ${_+1}/${h.length}`:``,re=v.length===1?[new W(`${v[0].label}${ne}`,{style:te})]:[],ie=[fI([...w,...re,...ee],r)];for(let e of v){v.length>1&&ie.push(fI([new W(e.label,{style:te})],r));let t=Math.max(...e.indices.map(e=>sI(s.options[e])));for(let n of e.indices){let e=s.options[n],i=m.entries[n].description,a=i===void 0?void 0:WA(i),o=` `.repeat(t-sI(e)+2),c=a===void 0?e:`${e}${o}${a}`;ie.push(fI([C(n,rI(c,f))],r))}}return ie}function gI(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{ob(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=pI(e,r,`set-int`,`an int action ({ set, int: true })`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=mI(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=oI(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let[d]=hI(n,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,$F(u,qa(void 0),e,l.paletteOf,t.drawnAt(),u.bg),XF(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function _I(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+sI(e(-(s+1)))+1+sI(e(s+1))+1;if(t>r)break;o=t,s+=1}return s}function vI(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=n.store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=BF(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return fI([],!0);let d=BF(o,t.stateVar),f=Math.max(l.indexOf(d),0),p=e=>((f+e)%u+u)%u,m=e=>l[p(e)],h=new Map,g=e=>{let t=h.get(e);if(t!==void 0)return t;let n=jk(WF(s,m(e),m(e),o,c).effects);return h.set(e,n),n},_=e=>HF(m(e),g(e),m(e)===d,r({index:p(e),count:u},m(e))),v=a===void 0?_(0):HF(m(0),jk(WF(n.compiled.get(a),m(0),void 0,o,c).effects),!1),y=_I(m,u,sI(`◀`)+1+v.cellLength+1+sI(`▶`),lI(n),i),b=e=>Array.from({length:y},(t,n)=>_(e*(n+1)));return fI([...b(-1).reverse(),HF(`◀`,g(-1),!1),v,HF(`▶`,g(1),!1),...b(1)],!0)}function yI(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(ob(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&RF(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=mI(e,n,`carousel`),l=oI(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return vI(n,c,e,$F(l,qa(void 0),e,c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}const bI=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function xI(e,t,n){let r=_o(e,{hue:Ba,depth:0},n);return[Va(t.hues).map((t,n)=>({text:bI[n%bI.length],colour:to(e,t)})),[{text:`▾ open`,colour:r.state},{text:`menu`,colour:r.plane}],[{text:`warn`,colour:eo(e,`warning`)},{text:`error`,colour:eo(e,`error`)}]]}function SI(e,t,n,r){let i=xI(e,t,n).flatMap((t,r)=>t.map(({text:t,colour:i},a)=>({gap:r>0&&a===0?` `:``,cell:new W(` ${t} `,{style:YF(e,i,n)})}))),a=[],o=0;for(let{gap:e,cell:t}of i){if(o+=e.length+t.cellLength,o>r)break;e!==``&&a.push(new W(e)),a.push(t)}let s=W.fromFragments(a);return s.overflow=`ignore`,s.end=``,s}function CI(e,t){return{themePreview:{fn:()=>SI(e.palette,e.variation,t.drawnAt(),lI(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}const wI=e=>e.slice(e.lastIndexOf(`.`)+1),TI=(e,t)=>{let n=new W(wI(e));return n.truncate(t,{marker:`…`}),n.plain};function EI(e,t){let n=e.map(e=>e.map(({name:e})=>sI(wI(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 DI(e,t,n,r){let i=EI(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new W(` ${TI(s,i)} `,{style:YF(l,Oo(l,{kind:`bar`,variation:t,address:c},n).tint,n)});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
197
+ `),...e]));return o.overflow=`ignore`,o.end=``,o}function OI(e,t){return{layoutPreview:{fn:()=>DI(e.layout(),e.variation,t.drawnAt(),lI(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function kI(e,t,n,r){let i=oI(r.activeSegment,`{{ menu }}`),a=r.action,o=nv(i.placementId,e,n.key),s=av(o),c=tv(e),l=BF(a.store,o)===c,u=BF(a.store,`session.id`),d=l?Tl:c,f=HF(Ol(`{{ menu "${e}" }}`,t,2,+!!l),jk([{verb:ak,args:[u,o,d,s,`0`]}]),!1);return i.drops.push(...l?(()=>{let t=r.activeSegment.drawnAt(),c=_o(i.palette,i.disclosure,t).plane;return hI(e,{key:s,stateVar:s},{kind:`own`,writes:[[o,Tl],[s,`0`]],onPick:n.closeOnPick},n.paged,a,$F(i,n.distribution,a,mI(a,e,`menu`).paletteOf,t,c),XF(i.palette,c,t))})():[]),f}const AI=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function jI(e,t){let n=t[t.length-1],r=AI(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:lv(r??{})}}function MI(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=jI(t,n);return kI(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function NI(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=PI(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new W(t?i:a,{style:l===void 0?void 0:new V({color:l})}))}let l=W.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function PI(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 FI(e){let t={fn:(()=>{let t=oI(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],arity:{kind:`exact`},returnType:`string`},n={fn:(()=>oI(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r=Ky(()=>oI(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),i={fn:((e,t,n,i,a,o,...s)=>{let c=o===void 0?void 0:[o,...II(s)];return NI({value:e,max:t,width:n,filled:i,empty:a,colourAt:c===void 0?void 0:e=>String(r.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...r,bgOf:t,tint:n,gauge:i}}function II(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 LI(e){let t=[],n=[];for(let r of e){if(!r.contains(`
198
198
  `)){n.push(r);continue}let e=r.split(`
199
- `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function PI(e,t){let n=t.flatMap(e=>e.filter(e=>e.place===`above`)),r=t.map(e=>e.filter(e=>e.place===`flow`));return[...n,...FI(e,r)]}function FI(e,t){switch(e){case`vertical`:return t.flatMap(e=>e);case`horizontal`:return t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`,place:`flow`},...t.flatMap(e=>e.slice(1))]}}function II(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:PI(e.direction,e.children.map((t,i)=>n(t,[...r,LI(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function LI(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:cc[e.direction]}}const RI={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:qa(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,mc(t.path,n)))}},render(e,t){return PI(e.direction,e.children.map((n,r)=>t.renderChild(n,t.visible,LI(e,r))))}},zI={drop:e=>e.place,above:()=>`above`},BI={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},VI={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:lc(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(jl(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,hc(t.path)),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render(e,t){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(!t.visible)return[];let a=mb(t.scope,e.settings);try{if(!yF(i.when,a))return[];let n=Vx(e.settings.theme,t.palette),o=e.opens!==void 0&&yF(e.opens.open,t.scope),{styles:s,fragments:c,lead:l,trail:u,drops:d,open:f}=t.evaluateSegment(e,a,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,lead:e.lead,trail:e.trail},o),p=f?s.trigger:s.closed,m={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:p,padding:t.padding},h=e.opens,g=h===void 0?[]:t.renderBody(h.body,o,s.disclosure).map(e=>({...e,place:zI[h.placement](e)})),_=NI(OF(c,p)).map((e,t)=>({cells:wF(e,{...m,lead:t===0?OF(l,p):[],trail:t===0?OF(u,p):[]}),band:`own`,place:`flow`})),v=d.map(e=>({cells:wF(OF([e],s.band),{...m,baseStyle:s.band}),band:`deeper`,place:`flow`})),y=(e,t,n)=>wF(OF([e],t),{...m,width:`auto`,baseStyle:t,padding:n}),b=g.findIndex(e=>e.band===`own`),{lead:x,stays:S}=h!==void 0&&b!==-1?BI[h.placement](_,()=>y(t.closeDisclosure(h.key),s.close,t.padding)):{lead:[],stays:_},C=x.flatMap(e=>y(new W(` `.repeat(SF(e).reduce((e,t)=>e+t.cellLength,0))),s.trigger,0)),w=(e,t)=>e.band===`own`?t===b?x:C:[],ee=g.map((e,t)=>({cells:[...w(e,t),...e.cells],band:`deeper`,place:e.place})),te=[...S,...v];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...te.flatMap(e=>e.cells),...g.flatMap(w)].flatMap(SF)),[...te,...ee]}catch(n){let r=n.message??String(n);t.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:wF([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,lead:HI(e.lead,e,a,t),trail:HI(e.trail,e,a,t)}),band:`own`,place:`flow`}]}}};function HI(e,t,n,r){if(e===void 0)return[];try{return r.evaluateSegment(t,n,r.palette,r.region,{bg:void 0,fg:void 0,body:e,lead:void 0,trail:void 0},!1).fragments}catch(e){return r.onSegmentError?.(t.id,e.message??String(e)),[]}}const UI={container:RI,segment:VI};function WI(e){return UI[e]}function GI(e){if(`ttl`in e)return{kind:`ttl`,durationMs:ix(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 KI(e,t){switch(vc(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 qI(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);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:GI(n.cache),parse:KI(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:GI(n.cache),parse:KI(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?ix(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 JI(e,t){let n=Nf.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 YI=e=>ts(void 0,null,e.globals.variation);function XI(e,t,n){let r=n.cwd,i=Jx(e.globals.palette),a={store:t.variableStore,compiled:new Map,chromeCols:tj({endcaps:`powerline`,charset:Xo}),width:80,basePalette:i,palette:i,variation:za[YI(e)],padding:1,seamCols:nj({endcaps:`powerline`,charset:Xo}),layout:()=>[]},o=eI(t.drawnAt),s={action:a,activeSegment:o},c=Object.keys(e.styles),l=fv(e.presets),u=eT(e),d=db({...UF(a),...fI(a,o),...hI(a,o),...yI(a,o),...wI(a,o),...OI(s),...jI(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},n.clock,t.drawnAt),f=JI(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 Nx)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=jF(p,e.actions,g,u);let _=[];for(let[n,i]of Object.entries(e.variables))try{qI(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{qI(t,`${n}.${e}`,a,r)}catch(t){_.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let v=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=p)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};v[t]={when:n.when===void 0?void 0:e(n.when,`when`,h),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let y=(e,t,n)=>{try{return h(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},b=t.variableStore,x=t=>{let n=Cc(e.segments[t.name]),r=Object.create(null);for(let[e,i]of Object.entries(n)){let n=t.settings?.[e]??i.default,a=t.drafts?.[e];Object.defineProperty(r,e,{enumerable:!0,get:a===void 0?()=>n:()=>Oc(i,String(b.read(a.variable)))??n})}return Object.freeze(r)},S=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:y(e.when,t,`when`),parse:(e,n)=>y(e,t,n),compileChild:S,placementSettings:x};return WI(e.kind).compile(e,n)},C=new Map;for(let t of l){let{node:n,path:r}=hv(e,t);C.set(t,S(n,r))}let w=new Map(Ro.map(e=>[e,new Map])),ee=[[`globals`,e.globals],...Object.entries(e.presets).map(([e,t])=>[`presets.${e}.globals`,t.globals??{}])];for(let[e,t]of ee)for(let n of Ro){let r=t[n];if(!zo(r))continue;let i=`${e}.${n}`,a=w.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:ZI(p,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:v,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:w,loadWarnings:_}}function ZI(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function QI(e,t,n){let r=e.globalExpressions.get(t).get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the render but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r}function $I(e,t){return e.template.evaluate(t).map(e=>e.plain).join(``)}function eL(e,t){return e.kind===`decided`?e.name:t}function tL(e,t,n,r,i,a,o,s){let{perSegmentSink:c,onSegmentError:l,onRenderWarning:u}=o??{};r.drawAt(Qo(a.colorCompatibility));let{preset:d=uv}=s??{},f=gv(e,d),p=za[s?.variation??ts(void 0,null,f.variation)];t.menuRuntime.action.variation=p;let m=s?.style??Wo(`none`,e.styles),h=s?.theme??Kx(void 0,null,f.palette),g=(e,t)=>({...i,term:{cols:a.width},theme:{effective:e},style:{effective:t}});r.applyInput(g(eL(h,jo),eL(m,Ho))),t.menuRuntime.action.chromeCols=tj(a),t.menuRuntime.action.padding=a.padding,t.menuRuntime.action.width=a.width,t.menuRuntime.action.seamCols=nj(a);let _=fb(n),v=Vo(h,e=>{let n=QI(t,`palette`,e);return Gx($I(n,_),n.where,e=>u?.(e))}),y=Vo(m,n=>Wo($I(QI(t,`style`,n),_),e.styles));(v!==h||y!==m)&&r.applyInput(g(v.name,y.name));let b=v.value;t.menuRuntime.action.basePalette=b;let x=Ux(b,y.value);t.menuRuntime.action.palette=x,c?.clear();let S=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},C=(e,n,i,a,o,s)=>{try{let c=r.drawnAt(),{tint:l,disclosure:u}=Oo(i,a,c),d=tI(t.activeSegment,e.name,e.id,i,u,l),f=xS(d,c,o.bg,o.fg,n),p=()=>_o(i,u,c).state;s&&(d.bg=p());let m=o.body.evaluate(n),h=d.drops.length>0||s;h&&(d.bg=p());let g=o.lead?.evaluate(n)??[],_=o.trail?.evaluate(n)??[];return{styles:{closed:f,get trigger(){return GF(i,p(),c)},get band(){return GF(i,_o(i,u,c).plane,c)},get close(){return qF(i,p(),c)},disclosure:u},fragments:m,lead:g,trail:_,drops:d.drops,open:h}}finally{t.activeSegment.current=null}},w=(e,t,r)=>{let i=t&&yF(e.when,_),o={scope:_,palette:x,visible:i,padding:a.padding,region:r,perSegmentSink:c,onSegmentError:l,evaluateSegment:C,lookupSegment:S,renderChild:(e,t,n)=>w(e,t,Eo(r,n)),renderBody:(e,t,n)=>w(e,i&&t,Do(n)),closeDisclosure:e=>WF(n,e)};return WI(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 "${uv}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let te=e=>{if(!yF(e.when,_))return!1;if(e.kind===`container`)return!0;if(dT(e.name)===void 0)return!1;try{return yF(t.segments[e.name].when,mb(_,e.settings))}catch{return!0}};return t.menuRuntime.action.layout=()=>II(ee,te).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=dT(e);return r===void 0?[]:[{name:r,address:t,palette:Vx(n.theme,x)}]})),w(ee,!0,To(p)).map(e=>rj(DF(e.cells,a),a)).join(`
200
- `)}function*nL(e){yield*Object.entries(e.variables??{});for(let[t,n]of Object.entries(e.segments??{}))for(let[e,r]of Object.entries(n.vars??{}))yield[`${t}.${e}`,r]}function*rL(e){for(let t of Object.values(e.segments))for(let e of[t.template,t.bg,t.fg,t.when])e!==void 0&&(yield e);for(let t of fv(e.presets)){for(let n of pc(hv(e,t).node))n.when!==void 0&&(yield n.when);let n=gv(e,t);for(let e of Ro){let t=n[e];zo(t)&&(yield t)}}for(let[,t]of nL(e))t.kind===`template`&&(yield t.template),bc(t)&&t.cache&&`key`in t.cache&&(yield t.cache.key);for(let t of Object.values(e.actions))`copy`in t&&(yield t.copy),`open`in t&&(yield t.open),`preset`in t&&t.preset===`delete`&&(yield t.name)}function iL(e,t){return e===t||t.startsWith(`${e}.`)||e.startsWith(`${t}.`)}function aL(e,t){let n=new Set,r=new Set,i=new Set;for(let e of rL(t)){for(let r of ny(e,t.helpers).keys())n.add(r);for(let{name:n}of oy(e,t.helpers))r.add(n);for(let n of sy(e,t.helpers))i.add(n)}for(let[,e]of nL(t))if(bc(e)&&e.cache&&`depends_on`in e.cache)for(let t of e.cache.depends_on)n.add(t);let a=new Set(r);for(let e of r){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)a.add(e)}let o=new Set,s=new Set;for(let e of a){let n=t.actions[e];if(n!==void 0&&(`set`in n&&o.add(n.set),`insertSegment`in n&&s.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)s.add(e)}for(let e of fv(t.presets))for(let n of pc(hv(t,e).node))n.kind===`segment`&&s.add(n.name);let c=(e,t)=>[...n].some(t=>iL(t,e))||t.kind===`state`&&o.has(t.key),l=e=>[...e].filter(e=>!sd(e)),u=(e,t,n)=>l(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),d=new Map(nL(e));return[...u(`variable`,d.keys(),e=>c(e,d.get(e))),...u(`action`,Object.keys(e.actions??{}),e=>a.has(e)),...u(`helper`,Object.keys(e.helpers??{}),e=>i.has(e)),...u(`segment`,Object.keys(e.segments??{}),e=>s.has(e))]}var oL=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,fL(e,t,n,`initial value`),this.cell=gy.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){fL(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}},sL=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,gy.computed)(()=>{let e=n();return fL(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},cL=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=gy.observable.box(dL(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=dL(e);uL(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function lL(e){return JSON.stringify(e)}function uL(e,t){return lL(e)===lL(t)}function dL(e){return e.kind===`ok`?{kind:`ok`,value:_y(e.value)}:e}function fL(e,t,n,r){let i=vy(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var pL=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new oL(e,t,n))}defineDocument(e,t){this.assertNotDefined(e),this.nodes.set(e,new cL(e,t))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new sL(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,gy.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,gy.runInAction)(()=>n.set(t))}runInAction(e){(0,gy.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 lL(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 mL(e,{loaded:t,dropped:n,unreached:r}){Z(`info`,`config load ${e.join(` < `)||`<default>`}: plugins loaded=${t.length} dropped=${n.length} unplaced=${r.length}`+t.map(e=>` +${e}`).join(``)+n.map(e=>` -${e.path} (${e.reason})`).join(``)+r.map(e=>` ~${e.path} (${e.reason})`).join(``))}function hL(e,t,n){return e+`\0`+t+`\0`+(n??``)}function gL(e,t){return new Set(fv(e.presets).filter(n=>hv(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function _L(e,t){let n=new Map,{roots:r,loaded:i,dropped:a,unreached:o}=e.state.plugins;for(let t of[...qE(e.projectDir,e.cwd,e.configFile),...r,...i,...[...a,...o].map(e=>e.path)]){let{dir:e,name:r}=fy(t),i=n.has(e)?n.get(e):new Set;i?.add(r),n.set(e,i)}for(let e of r){let{dir:t,name:r,leaf:i}=fy(l.join(e,`_`));i&&r===`_`&&n.set(t,null)}return{files:t,dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})}}function vL(e){return e.filter(Boolean).join(`
201
- `)||null}function yL(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=PD(t.layers,nM,{entered:i,warned:e=>n.push(...e)},{projectDir:t.projectDir});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??nM,l=a.find(e=>e.path===t.home)?.raw??{},u=new pL,d=new Tx(u,o.globals.default_empty_value??``,r.gitService,r.sessionState),f;try{f=XI(o,d,{cwd:e}),n.push(...f.loadWarnings),NN(o),Bj(o)}catch(e){throw d.dispose(),e}return{config:o,store:u,registry:d,compiled:f,neededInputPaths:WM(o),lastRenderCellsBySegment:new Map,authoredRoots:gL(c,l),fileHeldSettings:yN(l),unused:[...new Map(a.flatMap(e=>aL(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering}}}function bL(e,t,n,r){let i=YE(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[eD(e,t),QE(i)],s,c=null;try{s=yL(t,a,o,r,e=>{c=e})}catch(e){return e instanceof nc&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:vL(o),state:null,error:e instanceof nc||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:vL(o),state:s,error:null}}var xL=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=hL(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=bL(e,t,n,this.deps);a.state!==null&&mL(a.layers,a.state.plugins);let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??yL(t,{layers:[],home:``,projectDir:e},[],this.deps),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;n.state.registry.dispose(),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a),this.observers.onReload?.(o),o}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=bL(e.projectDir,e.cwd,e.configFile,this.deps);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(mL(t.layers,t.state.plugins),e.state.registry.dispose(),e.state=t.state),this.refreshWatcher(e,t),this.observers.onReload?.(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=_L(e,t.layers),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){Z(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const SL=16384;var CL=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<SL){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%SL}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:dO,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,renderCache:{size:e.renderCacheSize},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes}}};function wL(e,t,n){let r=(r,i,a)=>{let o=i.filter(t).map(t=>({key:t,before:e.get(r,t)}));a();for(let{key:t,before:i}of o)n(r,t,i,e.get(r,t))};return{get:(t,n)=>e.get(t,n),set:(t,n,i)=>r(t,[n],()=>e.set(t,n,i)),setBatch:(t,n)=>r(t,n.map(e=>e.key),()=>e.setBatch(t,n)),clear:(t,n)=>r(t,[n],()=>e.clear(t,n))}}const TL={load:()=>({}),save:()=>{},flush:()=>{}};function EL(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var DL=class{sessions;storage;atom=(0,gy.createAtom)(`SessionState`);constructor(e=TL,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=EL(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,gy.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,gy.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,gy.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,n]of this.sessions)e[t]=Object.fromEntries(n);return e}};function OL(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 kL=class{timer=null;pending=null;constructor(e,t=500,n=Ub){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 OL(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(l.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 AL={default_empty_value:`string`,default_separator:`string`,palette:`string`,style:`string`,preset:`string`,endcaps:`string`,variation:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,updateNotice:`boolean`,colorCompatibility:`string`,menuGlyph:`string`},jL=new Set([`1`,`true`]),ML=new Set([`0`,`false`,``]);function NL(e,t){let n=iR(e),r=n.scope===`segment-palette`?`string`:AL[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(jL.has(t))return`true`;if(ML.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function PL(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function FL(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(l.dirname(e),{recursive:!0}),Ne(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function IL(e){return/^\s*$/.test(e)?null:vs(e)}function LL(e,t){return e!==null&&bs(e,t)!==void 0}function RL(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(RL),...i}}return e}function zL(e){if(!pl(e))return RL(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,RL(t)])),...n}}const BL=eM,VL=BL.segments,HL=BL.presets,UL=BL.root;function WL(e,t,n,r){if(!LL(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function GL(e,t){let n=hS(t);return t.scope===`segment-palette`&&WL(e,[`segments`,t.segment],VL[t.segment],n.join(`.`)),n}function KL(e){return vs(Os(e))}function qL(){return Object.entries(UL.rows).map(([e,t])=>{let n=RL(t);return{path:[`root`],fragment:KL({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function JL(e,t){let n=e===null?void 0:bs(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function YL(e,t){if(t===void 0)return null;let n=zL(t);return{path:e,fragment:KL(n),unit:{path:e,value:n}}}function XL(e,t){let n=[`presets`,t],r=[...n,`root`],i=HL[t];WL(e,n,i,r.join(`.`));let a=JL(e,r)??YL(r,i?.root);return a!==null&&Ys(a.fragment)?a:null}function ZL(e,t){let n=Js(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 QL(e,t){return[...qL(),JL(e,[`root`]),XL(e,t)].filter(e=>e!==null).reduce(ZL,new Map)}function $L(e,t,n){for(let{node:r,...i}of QL(e,t).values())if(Zs(r,n))return i;throw new $(`${eR(e,t).join(`.`)} holds no placement "${n}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`)}function eR(e,t){return XL(e,t)?.path??[`root`]}function tR(e,t){return t.scope===`preset-root`?eR(e,t.preset):hS(t)}function nR(e,{unit:t}){return t===null?e:Hs(e,t.path,Os(t.value),Es)}function rR(e){let t=mS(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function iR(e){let t=rR(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function aR(e,t,n,r,i){i(t,n,gR(t,r)),FL(t.path,r,e.logger),e.record(t.path,n,r)}function oR(e,t,n){let r=lR(e,t,n);if(r.length>0)throw new $(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const sR=()=>{};function cR(e,t){try{return t()}catch(t){throw!(t instanceof $)||e.above.length===0?t:new $(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function lR(e,t,n){let r=uR(e,t);if(r===null)return[];let i=new Set(mR(pR(r),pR(n)));return mR(fR(e,r),fR(e,n)).filter(e=>!i.has(e))}function uR(e,t){try{return dR(e,t)}catch(e){if(e instanceof nc)return null;throw e}}function dR(e,t){return PD(t===null?e.above:[e.path,...e.above],nM,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir},n=>n===e.path&&t!==null?t:r.readFileSync(n,`utf8`))}function fR(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function pR(e){return e.layers.at(-1)?.config??e.base}function mR(e,t,n=``){return!hR(e)||!hR(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>mR(e[r],t[r],n===``?r:`${n}.${r}`))}function hR(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gR(e,t){try{return dR(e,t)}catch(e){throw e instanceof nc?new $(`refused: the config file would not load after this click — ${e.message}`):e}}function _R(e,t){let n=iR(t),r=IL(PL(e)??``),i=r===null?void 0:bs(r,hS(n));return i!==void 0&&`value`in i?i.value:void 0}function vR(e,t,n){yR(e,t,n,[])}function yR(e,t,n,r){let i=PL(t.path),a=n.reduce((e,[t,n])=>Hs(e,GL(IL(e),iR(t)),NL(t,n),Es),i??``);aR(e,t,i,cR(t,()=>bR(a,t.path,r,e=>e)),oR)}function bR(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=$L(IL(s),n,i),l=tc(nR(s,c),c.path,i,a,Os(o));if(l===null)throw new $(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function xR(e,t,n){let r=IL(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of QL(r,t)){if(!Zs(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?Ss(e,c):Os(s.value);if(a!==`#`)return Hs(e,[...i,`rows`,a],l,Es);if(XL(r,t)!==null)throw new $(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return Hs(e,i,l,Es)}return e}function SR(e,t){return Ws(e,t,t[0]===`presets`&&t.length>2&&!iM(t[1])?2:0)}function CR(e,t,n){let r=n.map(rR),i=PL(t.path);if(i===null)return;let a=r.reduce((e,t)=>SR(e,tR(IL(e),t)),i);a!==i&&aR(e,t,i,a,sR)}function wR(e){let t=e===null?void 0:bs(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function TR(e,t){let n=new Set([...rM,...wR(e),...t.above.flatMap(e=>Object.keys(it.default.parse(r.readFileSync(e,`utf8`)).presets??{}))].map(td));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(td(e)))}function ER(e,t,n,r,i,a){let o=PL(t.path),s=IL(o??``),c=TR(s,t),l=[`presets`,c],u=cR(t,()=>XL(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?Ss(o??``,u.fragment):Os(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Os(r)]]],f=i.map(([e,t])=>{let n=pS(c,e);return[GL(s,iR(n)),NL(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Hs(e,t,n,Es),Hs(o??``,l,`{}`,Es));return aR(e,t,o,cR(t,()=>bR(p,t.path,a.map(e=>({...e,preset:c})),xR)),oR),c}function DR(e,t,n){if(iM(n))throw new $(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=PL(t.path),a=IL(i??``);if(i===null||a===null||bs(a,r)===void 0)throw new $(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=bs(a,[`globals`,`preset`]);aR(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>SR(e,t),i),sR)}function OR(e,t,n,r){let i=rR(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=PL(t.path),o=r.op===`remove`?r.target:r.anchor,s=cR(t,()=>$L(IL(a??``),i.preset,o)),c=nR(a??``,s),{after:l,placed:u}=kR(c,s.path,r,()=>{let e=gR(t,c).config;return fv(e.presets).map(t=>hv(e,t).node)});if(l===null)throw new $(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return aR(e,t,a,l,oR),u}function kR(e,t,n,r){switch(n.op){case`remove`:return{after:$s(e,t,n.target),placed:null};case`insert`:{let i=Dj(n.segment,n.anchor,r());return{after:ec(e,t,i,n.anchor,n.relation),placed:i}}}}const AR={load:()=>({}),save:()=>{}},jR=new Set(kx.map(e=>e.sessionKey)),MR=e=>jR.has(e)||e.startsWith(Iv),NR=8*1024*1024,PR={past:[],future:[]},FR=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var IR=class{state=new Map;constructor(e,t,n=AR){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}useStorage(e){this.storage=e,this.state=new Map(Object.entries(e.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??PR;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??PR}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(FR(n));r.set(FR(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:wL(this.sessionState,e=>MR(e)||e===`edit.mode`,(e,r,i,a)=>{if(r===`edit.mode`){let t=n.get(e);n.set(e,{before:t===void 0?i:t.before,after:a});return}t(e,{kind:`session`,key:r,before:i,after:a})}),file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=new Map(e),r=new Map(n);e.clear(),n.clear();for(let e of new Set([...t.keys(),...r.keys()])){let n=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=n.length===0?i:WR(i,n),o=r.get(e),s=o===void 0?a:JR(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new $(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,KR(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new $(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(FR)),a=n.net.filter(e=>!i.has(FR(e))),o=zR(YR(qR(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new $(`rewind: ${r.map(ZR).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new $(`redo: nothing to redo`);let a=[...n,i],o=zR(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...VR(t.savepoint,a.length-o.length,i)}),i}apply(e,t,n,r,i){let a=n===`before`?`after`:`before`,o=t.filter(t=>this.read(e,t)!==t[a]);if(o.length>0){let t=new Set(o.map(FR)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:YR(n,t),future:YR(i,t),...a!==void 0&&{savepoint:{at:YR([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(FR(e))),below:YR(a.below,t)}}}),new $(`${r}: ${o.map(ZR).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):PL(t.file)}write(e,t,n){t.kind===`file`?FL(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||LR(n)>NR;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,RR(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${NR} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function LR(e){let t=0;for(let{past:n,future:r,savepoint:i}of e.values())for(let e of[...n,...r,...i===void 0?[]:[i.net,...i.below]])for(let n of e)t+=(n.before?.length??0)+(n.after?.length??0);return t}function RR({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...VR(n,1,[])}:{past:e,future:t.slice(1),...VR(n,0,[])}}function zR(e){return e.slice(-50)}const BR=e=>e===Rv.member;function VR(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:HR(e.net,n),below:e.below}}}function HR(e,t){let n=new Map(e.map(e=>[FR(e),e]));for(let e of t){let t=n.get(FR(e));n.set(FR(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const UR=e=>e.map(e=>({...e,before:e.after,after:e.before}));function WR(e,t){let n=[...e.past,t],r=zR(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...VR(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...GR(e.future,a),...i.below]},n.length-r.length,t)}}function GR(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function KR(e,t){return{past:e.past.slice(0,-1),future:zR([...e.future,t]),...VR(e.savepoint,0,UR(t))}}function qR(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...GR(r,t.at-i.length),...t.below]}function JR(e,t){if(BR(t.after)&&!BR(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!BR(t.after)&&BR(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function YR(e,t){return e.map(e=>e.filter(e=>!t.has(FR(e)))).filter(e=>e.length>0)}function XR(e){return e.map(ZR).join(`, `)}function ZR(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function QR(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 $R(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(QR))}function ez(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(QR)&&$R(t.below)}function tz(e){if(typeof e!=`object`||!e)return!1;let t=e;return $R(t.past)&&$R(t.future)&&(t.savepoint===void 0||ez(t.savepoint))}function nz(e,t){let n=e=>e.kind===`file`||MR(e.key)?!0:(t.add(e.key),!1),r=e=>e.map(e=>e.filter(n)).filter(e=>e.length>0),{savepoint:i}=e,a=r(e.past),o=r(e.future);return i===void 0?{past:a,future:o}:{past:a,future:o,savepoint:{at:r(e.past.slice(0,i.at)).length,net:i.net.filter(n),below:r(i.below)}}}function rz(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(tz)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,nz(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{r.mkdirSync(l.dirname(e),{recursive:!0}),Ne(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 iz=e=>!MR(e)&&!YS(e)&&e!==`update.dismissed`;var az=class{past=new Map;depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:wL(e,iz,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new $(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,gy.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)}};function oz(e){let t=fF(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures}`]);return t.kind===`ok`?{kind:`ok`,value:t.stdout.trim().split(`,`).filter(e=>e!==``)}:{kind:`failed`,reason:t.reason}}function sz(e){return{probeTmux:oz,loadConfig:e}}function cz(e,t){let n=e.loadConfig(t),r={layers:n.layers,warnings:n.warning===null?[]:n.warning.split(`
202
- `)};return n.error===null?{...r,kind:`loaded`,unused:n.unused}:{...r,kind:`failed`,error:n.error}}function lz(e){let t=cC(e).env;if(t===void 0)return{path:e,env:{}};if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`cannot read ${e}: \`env\` is not an object`);return{path:e,env:t}}function uz(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function dz(e){return{kind:`arrived`,handler:e,bar:dO}}function fz(e,t,n){return{tmux:uz(e,t.tmux),config:cz(e,n),claudeSettings:lz(aC(iC(t.claudeConfigDir)))}}function pz(e,t){let n=t.claudeSettings.path;switch(e.kind){case`claude-settings-env`:{let i=Hs(sC(n),[`env`,e.name],JSON.stringify(e.value),Ds);return r.mkdirSync(l.dirname(n),{recursive:!0}),Ne(n,i),{...t,claudeSettings:lz(n)}}default:return e.kind}}const mz={connectMs:200,budgetMs:500};async function hz(e){let n=e.includes(`--json`),r=await gz();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${uO(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
203
- `);return}t.stdout.write(bz(r.value))}function gz(){return iO({kind:`stats`},mz,e=>`stats`in e?e.stats:void 0)}function _z(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function vz(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function yz(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 bz(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 ${yz(e.uptimeSec)}`),t.push(` rss ${_z(e.rssBytes)}`),t.push(` heapUsed ${_z(e.heapUsedBytes)}`),t.push(` heapTotal ${_z(e.heapTotalBytes)}`),t.push(` external ${_z(e.externalBytes)}`),t.push(` arrayBuffers ${_z(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 ${vz(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 ${vz(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(`
199
+ `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function RI(e,t){let n=t.flatMap(e=>e.filter(e=>e.place===`above`)),r=t.map(e=>e.filter(e=>e.place===`flow`));return[...n,...zI(e,r)]}function zI(e,t){switch(e){case`vertical`:return t.flatMap(e=>e);case`horizontal`:return t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`,place:`flow`},...t.flatMap(e=>e.slice(1))]}}function BI(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:RI(e.direction,e.children.map((t,i)=>n(t,[...r,VI(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function VI(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:cc[e.direction]}}const HI={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:qa(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,mc(t.path,n)))}},render(e,t){return RI(e.direction,e.children.map((n,r)=>t.renderChild(n,t.visible,VI(e,r))))}},UI={drop:e=>e.place,above:()=>`above`},WI={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},GI={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:lc(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(jl(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,hc(t.path)),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render(e,t){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(!t.visible)return[];let a=mb(t.scope,e.settings);try{if(!CF(i.when,a))return[];let n=Vx(e.settings.theme,t.palette),o=e.opens!==void 0&&CF(e.opens.open,t.scope),{styles:s,fragments:c,lead:l,trail:u,drops:d,open:f}=t.evaluateSegment(e,a,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,lead:e.lead,trail:e.trail},o),p=f?s.trigger:s.closed,m={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:p,padding:t.padding},h=e.opens,g=h===void 0?[]:t.renderBody(h.body,o,s.disclosure).map(e=>({...e,place:UI[h.placement](e)})),_=LI(MF(c,p)).map((e,t)=>({cells:OF(e,{...m,lead:t===0?MF(l,p):[],trail:t===0?MF(u,p):[]}),band:`own`,place:`flow`})),v=d.map(e=>({cells:OF(MF([e],s.band),{...m,baseStyle:s.band}),band:`deeper`,place:`flow`})),y=(e,t,n)=>OF(MF([e],t),{...m,width:`auto`,baseStyle:t,padding:n}),b=g.findIndex(e=>e.band===`own`),{lead:x,stays:S}=h!==void 0&&b!==-1?WI[h.placement](_,()=>y(t.closeDisclosure(h.key),s.close,t.padding)):{lead:[],stays:_},C=x.flatMap(e=>y(new W(` `.repeat(EF(e).reduce((e,t)=>e+t.cellLength,0))),s.trigger,0)),w=(e,t)=>e.band===`own`?t===b?x:C:[],ee=g.map((e,t)=>({cells:[...w(e,t),...e.cells],band:`deeper`,place:e.place})),te=[...S,...v];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...te.flatMap(e=>e.cells),...g.flatMap(w)].flatMap(EF)),[...te,...ee]}catch(n){let r=n.message??String(n);t.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:OF([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,lead:KI(e.lead,e,a,t),trail:KI(e.trail,e,a,t)}),band:`own`,place:`flow`}]}}};function KI(e,t,n,r){if(e===void 0)return[];try{return r.evaluateSegment(t,n,r.palette,r.region,{bg:void 0,fg:void 0,body:e,lead:void 0,trail:void 0},!1).fragments}catch(e){return r.onSegmentError?.(t.id,e.message??String(e)),[]}}const qI={container:HI,segment:GI};function JI(e){return qI[e]}function YI(e){if(`ttl`in e)return{kind:`ttl`,durationMs:ix(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 XI(e,t){switch(vc(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 ZI(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);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:YI(n.cache),parse:XI(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:YI(n.cache),parse:XI(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?ix(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 QI(e,t){let n=Nf.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 $I=e=>ts(void 0,null,e.globals.variation);function eL(e,t,n){let r=n.cwd,i=Jx(e.globals.palette),a={store:t.variableStore,compiled:new Map,chromeCols:aj({endcaps:`powerline`,charset:Xo}),width:80,basePalette:i,palette:i,variation:za[$I(e)],padding:1,seamCols:oj({endcaps:`powerline`,charset:Xo}),layout:()=>[]},o=iI(t.drawnAt),s={action:a,activeSegment:o},c=Object.keys(e.styles),l=fv(e.presets),u=eT(e),d=db({...qF(a),...gI(a,o),...yI(a,o),...CI(a,o),...OI(a,o),...MI(s),...FI(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},n.clock,t.drawnAt),f=QI(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 Nx)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=FF(p,e.actions,g,u);let _=[];for(let[n,i]of Object.entries(e.variables))try{ZI(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{ZI(t,`${n}.${e}`,a,r)}catch(t){_.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let v=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=p)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};v[t]={when:n.when===void 0?void 0:e(n.when,`when`,h),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let y=(e,t,n)=>{try{return h(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},b=t.variableStore,x=t=>{let n=Cc(e.segments[t.name]),r=Object.create(null);for(let[e,i]of Object.entries(n)){let n=t.settings?.[e]??i.default,a=t.drafts?.[e];Object.defineProperty(r,e,{enumerable:!0,get:a===void 0?()=>n:()=>Oc(i,String(b.read(a.variable)))??n})}return Object.freeze(r)},S=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:y(e.when,t,`when`),parse:(e,n)=>y(e,t,n),compileChild:S,placementSettings:x};return JI(e.kind).compile(e,n)},C=new Map;for(let t of l){let{node:n,path:r}=hv(e,t);C.set(t,S(n,r))}let w=new Map(Ro.map(e=>[e,new Map])),ee=[[`globals`,e.globals],...Object.entries(e.presets).map(([e,t])=>[`presets.${e}.globals`,t.globals??{}])];for(let[e,t]of ee)for(let n of Ro){let r=t[n];if(!zo(r))continue;let i=`${e}.${n}`,a=w.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:tL(p,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:v,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:w,loadWarnings:_}}function tL(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function nL(e,t,n){let r=e.globalExpressions.get(t).get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the render but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r}function rL(e,t){return e.template.evaluate(t).map(e=>e.plain).join(``)}function iL(e,t){return e.kind===`decided`?e.name:t}function aL(e,t,n,r,i,a,o,s){let{perSegmentSink:c,onSegmentError:l,onRenderWarning:u}=o??{};r.drawAt(Qo(a.colorCompatibility));let{preset:d=uv}=s??{},f=gv(e,d),p=za[s?.variation??ts(void 0,null,f.variation)];t.menuRuntime.action.variation=p;let m=s?.style??Wo(`none`,e.styles),h=s?.theme??Kx(void 0,null,f.palette),g=(e,t)=>({...i,term:{cols:a.width},theme:{effective:e},style:{effective:t}});r.applyInput(g(iL(h,jo),iL(m,Ho))),t.menuRuntime.action.chromeCols=aj(a),t.menuRuntime.action.padding=a.padding,t.menuRuntime.action.width=a.width,t.menuRuntime.action.seamCols=oj(a);let _=fb(n),v=Vo(h,e=>{let n=nL(t,`palette`,e);return Gx(rL(n,_),n.where,e=>u?.(e))}),y=Vo(m,n=>Wo(rL(nL(t,`style`,n),_),e.styles));(v!==h||y!==m)&&r.applyInput(g(v.name,y.name));let b=v.value;t.menuRuntime.action.basePalette=b;let x=Ux(b,y.value);t.menuRuntime.action.palette=x,c?.clear();let S=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},C=(e,n,i,a,o,s)=>{try{let c=r.drawnAt(),{tint:l,disclosure:u}=Oo(i,a,c),d=aI(t.activeSegment,e.name,e.id,i,u,l),f=xS(d,c,o.bg,o.fg,n),p=()=>_o(i,u,c).state;s&&(d.bg=p());let m=o.body.evaluate(n),h=d.drops.length>0||s;h&&(d.bg=p());let g=o.lead?.evaluate(n)??[],_=o.trail?.evaluate(n)??[];return{styles:{closed:f,get trigger(){return YF(i,p(),c)},get band(){return YF(i,_o(i,u,c).plane,c)},get close(){return ZF(i,p(),c)},disclosure:u},fragments:m,lead:g,trail:_,drops:d.drops,open:h}}finally{t.activeSegment.current=null}},w=(e,t,r)=>{let i=t&&CF(e.when,_),o={scope:_,palette:x,visible:i,padding:a.padding,region:r,perSegmentSink:c,onSegmentError:l,evaluateSegment:C,lookupSegment:S,renderChild:(e,t,n)=>w(e,t,Eo(r,n)),renderBody:(e,t,n)=>w(e,i&&t,Do(n)),closeDisclosure:e=>JF(n,e)};return JI(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 "${uv}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let te=e=>{if(!CF(e.when,_))return!1;if(e.kind===`container`)return!0;if(dT(e.name)===void 0)return!1;try{return CF(t.segments[e.name].when,mb(_,e.settings))}catch{return!0}};return t.menuRuntime.action.layout=()=>BI(ee,te).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=dT(e);return r===void 0?[]:[{name:r,address:t,palette:Vx(n.theme,x)}]})),w(ee,!0,To(p)).map(e=>sj(jF(e.cells,a),a)).join(`
200
+ `)}function*oL(e){yield*Object.entries(e.variables??{});for(let[t,n]of Object.entries(e.segments??{}))for(let[e,r]of Object.entries(n.vars??{}))yield[`${t}.${e}`,r]}function*sL(e){for(let t of Object.values(e.segments))for(let e of[t.template,t.bg,t.fg,t.when])e!==void 0&&(yield e);for(let t of fv(e.presets)){for(let n of pc(hv(e,t).node))n.when!==void 0&&(yield n.when);let n=gv(e,t);for(let e of Ro){let t=n[e];zo(t)&&(yield t)}}for(let[,t]of oL(e))t.kind===`template`&&(yield t.template),bc(t)&&t.cache&&`key`in t.cache&&(yield t.cache.key);for(let t of Object.values(e.actions))`copy`in t&&(yield t.copy),`open`in t&&(yield t.open),`preset`in t&&t.preset===`delete`&&(yield t.name)}function cL(e,t){return e===t||t.startsWith(`${e}.`)||e.startsWith(`${t}.`)}function lL(e,t){let n=new Set,r=new Set,i=new Set;for(let e of sL(t)){for(let r of ny(e,t.helpers).keys())n.add(r);for(let{name:n}of oy(e,t.helpers))r.add(n);for(let n of sy(e,t.helpers))i.add(n)}for(let[,e]of oL(t))if(bc(e)&&e.cache&&`depends_on`in e.cache)for(let t of e.cache.depends_on)n.add(t);let a=new Set(r);for(let e of r){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)a.add(e)}let o=new Set,s=new Set;for(let e of a){let n=t.actions[e];if(n!==void 0&&(`set`in n&&o.add(n.set),`insertSegment`in n&&s.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)s.add(e)}for(let e of fv(t.presets))for(let n of pc(hv(t,e).node))n.kind===`segment`&&s.add(n.name);let c=(e,t)=>[...n].some(t=>cL(t,e))||t.kind===`state`&&o.has(t.key),l=e=>[...e].filter(e=>!sd(e)),u=(e,t,n)=>l(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),d=new Map(oL(e));return[...u(`variable`,d.keys(),e=>c(e,d.get(e))),...u(`action`,Object.keys(e.actions??{}),e=>a.has(e)),...u(`helper`,Object.keys(e.helpers??{}),e=>i.has(e)),...u(`segment`,Object.keys(e.segments??{}),e=>s.has(e))]}var uL=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,gL(e,t,n,`initial value`),this.cell=gy.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){gL(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}},dL=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,gy.computed)(()=>{let e=n();return gL(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},fL=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=gy.observable.box(hL(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=hL(e);mL(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function pL(e){return JSON.stringify(e)}function mL(e,t){return pL(e)===pL(t)}function hL(e){return e.kind===`ok`?{kind:`ok`,value:_y(e.value)}:e}function gL(e,t,n,r){let i=vy(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var _L=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new uL(e,t,n))}defineDocument(e,t){this.assertNotDefined(e),this.nodes.set(e,new fL(e,t))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new dL(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,gy.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,gy.runInAction)(()=>n.set(t))}runInAction(e){(0,gy.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 pL(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 vL(e,{loaded:t,dropped:n,unreached:r}){Z(`info`,`config load ${e.join(` < `)||`<default>`}: plugins loaded=${t.length} dropped=${n.length} unplaced=${r.length}`+t.map(e=>` +${e}`).join(``)+n.map(e=>` -${e.path} (${e.reason})`).join(``)+r.map(e=>` ~${e.path} (${e.reason})`).join(``))}function yL(e,t,n){return e+`\0`+t+`\0`+(n??``)}function bL(e,t){return new Set(fv(e.presets).filter(n=>hv(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function xL(e,t){let n=new Map,{roots:r,loaded:i,dropped:a,unreached:o}=e.state.plugins;for(let t of[...YE(e.projectDir,e.cwd,e.configFile),...r,...i,...[...a,...o].map(e=>e.path)]){let{dir:e,name:r}=fy(t),i=n.has(e)?n.get(e):new Set;i?.add(r),n.set(e,i)}for(let e of r){let{dir:t,name:r,leaf:i}=fy(l.join(e,`_`));i&&r===`_`&&n.set(t,null)}return{files:t,dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})}}function SL(e){return e.filter(Boolean).join(`
201
+ `)||null}function CL(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=LD(t.layers,oM,{entered:i,warned:e=>n.push(...e)},{projectDir:t.projectDir});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??oM,l=a.find(e=>e.path===t.home)?.raw??{},u=new _L,d=new Tx(u,o.globals.default_empty_value??``,r.gitService,r.sessionState),f;try{f=eL(o,d,{cwd:e}),n.push(...f.loadWarnings),LN(o),Wj(o)}catch(e){throw d.dispose(),e}return{config:o,store:u,registry:d,compiled:f,neededInputPaths:JM(o),lastRenderCellsBySegment:new Map,authoredRoots:bL(c,l),fileHeldSettings:CN(l),unused:[...new Map(a.flatMap(e=>lL(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering}}}function wL(e,t,n,r){let i=ZE(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[nD(e,t),eD(i)],s,c=null;try{s=CL(t,a,o,r,e=>{c=e})}catch(e){return e instanceof nc&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:SL(o),state:null,error:e instanceof nc||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:SL(o),state:s,error:null}}var TL=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=yL(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=wL(e,t,n,this.deps);a.state!==null&&vL(a.layers,a.state.plugins);let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??CL(t,{layers:[],home:``,projectDir:e},[],this.deps),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;n.state.registry.dispose(),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a),this.observers.onReload?.(o),o}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=wL(e.projectDir,e.cwd,e.configFile,this.deps);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(vL(t.layers,t.state.plugins),e.state.registry.dispose(),e.state=t.state),this.refreshWatcher(e,t),this.observers.onReload?.(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=xL(e,t.layers),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){Z(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const EL=16384;var DL=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<EL){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%EL}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:hO,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,renderCache:{size:e.renderCacheSize},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes}}};function OL(e,t,n){let r=(r,i,a)=>{let o=i.filter(t).map(t=>({key:t,before:e.get(r,t)}));a();for(let{key:t,before:i}of o)n(r,t,i,e.get(r,t))};return{get:(t,n)=>e.get(t,n),set:(t,n,i)=>r(t,[n],()=>e.set(t,n,i)),setBatch:(t,n)=>r(t,n.map(e=>e.key),()=>e.setBatch(t,n)),clear:(t,n)=>r(t,[n],()=>e.clear(t,n))}}const kL={load:()=>({}),save:()=>{},flush:()=>{}};function AL(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var jL=class{sessions;storage;atom=(0,gy.createAtom)(`SessionState`);constructor(e=kL,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=AL(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,gy.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,gy.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,gy.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,n]of this.sessions)e[t]=Object.fromEntries(n);return e}};function ML(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 NL=class{timer=null;pending=null;constructor(e,t=500,n=Ub){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 ML(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(l.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 PL={default_empty_value:`string`,default_separator:`string`,palette:`string`,style:`string`,preset:`string`,endcaps:`string`,variation:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,updateNotice:`boolean`,colorCompatibility:`string`,menuGlyph:`string`},FL=new Set([`1`,`true`]),IL=new Set([`0`,`false`,``]);function LL(e,t){let n=cR(e),r=n.scope===`segment-palette`?`string`:PL[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(FL.has(t))return`true`;if(IL.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function RL(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function zL(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(l.dirname(e),{recursive:!0}),Ne(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function BL(e){return/^\s*$/.test(e)?null:vs(e)}function VL(e,t){return e!==null&&bs(e,t)!==void 0}function HL(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(HL),...i}}return e}function UL(e){if(!pl(e))return HL(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,HL(t)])),...n}}const WL=iM,GL=WL.segments,KL=WL.presets,qL=WL.root;function JL(e,t,n,r){if(!VL(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function YL(e,t){let n=hS(t);return t.scope===`segment-palette`&&JL(e,[`segments`,t.segment],GL[t.segment],n.join(`.`)),n}function XL(e){return vs(Os(e))}function ZL(){return Object.entries(qL.rows).map(([e,t])=>{let n=HL(t);return{path:[`root`],fragment:XL({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function QL(e,t){let n=e===null?void 0:bs(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function $L(e,t){if(t===void 0)return null;let n=UL(t);return{path:e,fragment:XL(n),unit:{path:e,value:n}}}function eR(e,t){let n=[`presets`,t],r=[...n,`root`],i=KL[t];JL(e,n,i,r.join(`.`));let a=QL(e,r)??$L(r,i?.root);return a!==null&&Ys(a.fragment)?a:null}function tR(e,t){let n=Js(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 nR(e,t){return[...ZL(),QL(e,[`root`]),eR(e,t)].filter(e=>e!==null).reduce(tR,new Map)}function rR(e,t,n){for(let{node:r,...i}of nR(e,t).values())if(Zs(r,n))return i;throw new $(`${iR(e,t).join(`.`)} holds no placement "${n}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`)}function iR(e,t){return eR(e,t)?.path??[`root`]}function aR(e,t){return t.scope===`preset-root`?iR(e,t.preset):hS(t)}function oR(e,{unit:t}){return t===null?e:Hs(e,t.path,Os(t.value),Es)}function sR(e){let t=mS(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function cR(e){let t=sR(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function lR(e,t,n,r,i){i(t,n,bR(t,r)),zL(t.path,r,e.logger),e.record(t.path,n,r)}function uR(e,t,n){let r=pR(e,t,n);if(r.length>0)throw new $(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const dR=()=>{};function fR(e,t){try{return t()}catch(t){throw!(t instanceof $)||e.above.length===0?t:new $(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function pR(e,t,n){let r=mR(e,t);if(r===null)return[];let i=new Set(vR(_R(r),_R(n)));return vR(gR(e,r),gR(e,n)).filter(e=>!i.has(e))}function mR(e,t){try{return hR(e,t)}catch(e){if(e instanceof nc)return null;throw e}}function hR(e,t){return LD(t===null?e.above:[e.path,...e.above],oM,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir},n=>n===e.path&&t!==null?t:r.readFileSync(n,`utf8`))}function gR(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function _R(e){return e.layers.at(-1)?.config??e.base}function vR(e,t,n=``){return!yR(e)||!yR(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>vR(e[r],t[r],n===``?r:`${n}.${r}`))}function yR(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bR(e,t){try{return hR(e,t)}catch(e){throw e instanceof nc?new $(`refused: the config file would not load after this click — ${e.message}`):e}}function xR(e,t){let n=cR(t),r=BL(RL(e)??``),i=r===null?void 0:bs(r,hS(n));return i!==void 0&&`value`in i?i.value:void 0}function SR(e,t,n){CR(e,t,n,[])}function CR(e,t,n,r){let i=RL(t.path),a=n.reduce((e,[t,n])=>Hs(e,YL(BL(e),cR(t)),LL(t,n),Es),i??``);lR(e,t,i,fR(t,()=>wR(a,t.path,r,e=>e)),uR)}function wR(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=rR(BL(s),n,i),l=tc(oR(s,c),c.path,i,a,Os(o));if(l===null)throw new $(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function TR(e,t,n){let r=BL(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of nR(r,t)){if(!Zs(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?Ss(e,c):Os(s.value);if(a!==`#`)return Hs(e,[...i,`rows`,a],l,Es);if(eR(r,t)!==null)throw new $(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return Hs(e,i,l,Es)}return e}function ER(e,t){return Ws(e,t,t[0]===`presets`&&t.length>2&&!cM(t[1])?2:0)}function DR(e,t,n){let r=n.map(sR),i=RL(t.path);if(i===null)return;let a=r.reduce((e,t)=>ER(e,aR(BL(e),t)),i);a!==i&&lR(e,t,i,a,dR)}function OR(e){let t=e===null?void 0:bs(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function kR(e,t){let n=new Set([...sM,...OR(e),...t.above.flatMap(e=>Object.keys(it.default.parse(r.readFileSync(e,`utf8`)).presets??{}))].map(td));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(td(e)))}function AR(e,t,n,r,i,a){let o=RL(t.path),s=BL(o??``),c=kR(s,t),l=[`presets`,c],u=fR(t,()=>eR(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?Ss(o??``,u.fragment):Os(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Os(r)]]],f=i.map(([e,t])=>{let n=pS(c,e);return[YL(s,cR(n)),LL(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Hs(e,t,n,Es),Hs(o??``,l,`{}`,Es));return lR(e,t,o,fR(t,()=>wR(p,t.path,a.map(e=>({...e,preset:c})),TR)),uR),c}function jR(e,t,n){if(cM(n))throw new $(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=RL(t.path),a=BL(i??``);if(i===null||a===null||bs(a,r)===void 0)throw new $(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=bs(a,[`globals`,`preset`]);lR(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>ER(e,t),i),dR)}function MR(e,t,n,r){let i=sR(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=RL(t.path),o=r.op===`remove`?r.target:r.anchor,s=fR(t,()=>rR(BL(a??``),i.preset,o)),c=oR(a??``,s),{after:l,placed:u}=NR(c,s.path,r,()=>{let e=bR(t,c).config;return fv(e.presets).map(t=>hv(e,t).node)});if(l===null)throw new $(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return lR(e,t,a,l,uR),u}function NR(e,t,n,r){switch(n.op){case`remove`:return{after:$s(e,t,n.target),placed:null};case`insert`:{let i=jj(n.segment,n.anchor,r());return{after:ec(e,t,i,n.anchor,n.relation),placed:i}}}}const PR={load:()=>({}),save:()=>{}},FR=new Set(kx.map(e=>e.sessionKey)),IR=e=>FR.has(e)||e.startsWith(Iv),LR=8*1024*1024,RR={past:[],future:[]},zR=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var BR=class{state=new Map;constructor(e,t,n=PR){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}useStorage(e){this.storage=e,this.state=new Map(Object.entries(e.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??RR;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??RR}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(zR(n));r.set(zR(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:OL(this.sessionState,e=>IR(e)||e===`edit.mode`,(e,r,i,a)=>{if(r===`edit.mode`){let t=n.get(e);n.set(e,{before:t===void 0?i:t.before,after:a});return}t(e,{kind:`session`,key:r,before:i,after:a})}),file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=new Map(e),r=new Map(n);e.clear(),n.clear();for(let e of new Set([...t.keys(),...r.keys()])){let n=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=n.length===0?i:JR(i,n),o=r.get(e),s=o===void 0?a:QR(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new $(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,XR(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new $(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(zR)),a=n.net.filter(e=>!i.has(zR(e))),o=UR($R(ZR(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new $(`rewind: ${r.map(tz).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new $(`redo: nothing to redo`);let a=[...n,i],o=UR(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...GR(t.savepoint,a.length-o.length,i)}),i}apply(e,t,n,r,i){let a=n===`before`?`after`:`before`,o=t.filter(t=>this.read(e,t)!==t[a]);if(o.length>0){let t=new Set(o.map(zR)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:$R(n,t),future:$R(i,t),...a!==void 0&&{savepoint:{at:$R([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(zR(e))),below:$R(a.below,t)}}}),new $(`${r}: ${o.map(tz).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):RL(t.file)}write(e,t,n){t.kind===`file`?zL(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||VR(n)>LR;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,HR(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${LR} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function VR(e){let t=0;for(let{past:n,future:r,savepoint:i}of e.values())for(let e of[...n,...r,...i===void 0?[]:[i.net,...i.below]])for(let n of e)t+=(n.before?.length??0)+(n.after?.length??0);return t}function HR({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...GR(n,1,[])}:{past:e,future:t.slice(1),...GR(n,0,[])}}function UR(e){return e.slice(-50)}const WR=e=>e===Rv.member;function GR(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:KR(e.net,n),below:e.below}}}function KR(e,t){let n=new Map(e.map(e=>[zR(e),e]));for(let e of t){let t=n.get(zR(e));n.set(zR(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const qR=e=>e.map(e=>({...e,before:e.after,after:e.before}));function JR(e,t){let n=[...e.past,t],r=UR(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...GR(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...YR(e.future,a),...i.below]},n.length-r.length,t)}}function YR(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function XR(e,t){return{past:e.past.slice(0,-1),future:UR([...e.future,t]),...GR(e.savepoint,0,qR(t))}}function ZR(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...YR(r,t.at-i.length),...t.below]}function QR(e,t){if(WR(t.after)&&!WR(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!WR(t.after)&&WR(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function $R(e,t){return e.map(e=>e.filter(e=>!t.has(zR(e)))).filter(e=>e.length>0)}function ez(e){return e.map(tz).join(`, `)}function tz(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function nz(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 rz(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(nz))}function iz(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(nz)&&rz(t.below)}function az(e){if(typeof e!=`object`||!e)return!1;let t=e;return rz(t.past)&&rz(t.future)&&(t.savepoint===void 0||iz(t.savepoint))}function oz(e,t){let n=e=>e.kind===`file`||IR(e.key)?!0:(t.add(e.key),!1),r=e=>e.map(e=>e.filter(n)).filter(e=>e.length>0),{savepoint:i}=e,a=r(e.past),o=r(e.future);return i===void 0?{past:a,future:o}:{past:a,future:o,savepoint:{at:r(e.past.slice(0,i.at)).length,net:i.net.filter(n),below:r(i.below)}}}function sz(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(az)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,oz(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{r.mkdirSync(l.dirname(e),{recursive:!0}),Ne(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 cz=e=>!IR(e)&&!YS(e)&&e!==`update.dismissed`;var lz=class{past=new Map;depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:OL(e,cz,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new $(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,gy.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)}};function uz(e){let t=gF(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures}`]);return t.kind===`ok`?{kind:`ok`,value:t.stdout.trim().split(`,`).filter(e=>e!==``)}:{kind:`failed`,reason:t.reason}}function dz(e){return{probeTmux:uz,loadConfig:e}}function fz(e,t){let n=e.loadConfig(t),r={layers:n.layers,warnings:n.warning===null?[]:n.warning.split(`
202
+ `)};return n.error===null?{...r,kind:`loaded`,unused:n.unused}:{...r,kind:`failed`,error:n.error}}function pz(e){let t=cC(e).env;if(t===void 0)return{path:e,env:{}};if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`cannot read ${e}: \`env\` is not an object`);return{path:e,env:t}}function mz(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function hz(e){return{kind:`arrived`,handler:e,bar:hO}}function gz(e,t,n){return{tmux:mz(e,t.tmux),config:fz(e,n),claudeSettings:pz(aC(iC(t.claudeConfigDir)))}}function _z(e,t){let n=t.claudeSettings.path;switch(e.kind){case`claude-settings-env`:{let i=Hs(sC(n),[`env`,e.name],JSON.stringify(e.value),Ds);return r.mkdirSync(l.dirname(n),{recursive:!0}),Ne(n,i),{...t,claudeSettings:pz(n)}}default:return e.kind}}const vz={connectMs:200,budgetMs:500};async function yz(e){let n=e.includes(`--json`),r=await bz();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${mO(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
203
+ `);return}t.stdout.write(wz(r.value))}function bz(){return cO({kind:`stats`},vz,e=>`stats`in e?e.stats:void 0)}function xz(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function Sz(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function Cz(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 wz(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 ${Cz(e.uptimeSec)}`),t.push(` rss ${xz(e.rssBytes)}`),t.push(` heapUsed ${xz(e.heapUsedBytes)}`),t.push(` heapTotal ${xz(e.heapTotalBytes)}`),t.push(` external ${xz(e.externalBytes)}`),t.push(` arrayBuffers ${xz(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 ${Sz(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 ${Sz(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(`
204
204
  `)+`
205
- `}const xz=e=>({kind:`ok`,value:e}),Sz=e=>({kind:`failed`,reason:e});var Cz=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const wz=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function Tz(e){return wz.test(e)?e:null}function Ez(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return xz(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return xz({app:n,missing:Sz(`its script could not be read (${r.reason})`)});let i=eA(r.value);return xz({app:n,missing:i===null?Sz("its script is not one `cc-candybar install` wrote"):xz([i.node,i.script].filter(t=>!e.exists(t)))})}async function Dz(e,t){let n=e.now()+5e3;for(;e.now()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,handler:r.handler,bar:n.value.version}}return null}async function Oz(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${$O}://${Sk}/${n}`);return(r===null?await Dz(e,n):null)??{kind:`lost`,unopened:r,opener:Ez(e)}}function kz(e,t,n){let r=k({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?xz(r.stdout):Sz(r.stderr.trim()||r.error||r.reason)}const Az=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${$O}://probe"));u.isNil() ? "" : u.path.js`;async function jz(){let e=await gz();if(e.kind!==`ok`)return Sz(uO(e).split(`
206
- `).join(` — `));let{version:t,handlerProbes:n}=e.value;return Array.isArray(n)?xz({version:t,arrivals:n}):Sz(`the running daemon (${t}) predates this check`)}function Mz(){return{platform:process.platform,sockets:{own:Re(),handler:ze()},now:Date.now,nonce:ce,daemon:jz,open:e=>{let t=kz(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=kz(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,Az]);if(e.kind===`failed`)return e;let t=e.value.trim();return xz(t===``?null:t)},script:e=>kz(`doctor.osadecompile`,`/usr/bin/osadecompile`,[tA(e)]),exists:r.existsSync}}const Nz=/^─{20,}/,Pz=/^❯(\s|$)/,Fz=/›\s*stashed$/;function Iz(e){if(e.inMode)return{kind:`in-mode`};let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>Nz.test(e)?[t]:[]).at(-2);return n===void 0||!Pz.test(t[n+1]??``)?{kind:`no-prompt`}:Fz.test(t[n-1]??``)?{kind:`stashed`}:{kind:`ready`}}const Lz={"in-mode":`the Claude Code pane is in tmux copy mode — leave it (q) and click again`,stashed:`Claude Code is holding a stashed prompt (ctrl+s) — restore or send it, then click again`,"no-prompt":`Claude Code is not at its prompt (a dialog or picker is open) — close it and click again`};function Rz(e,t,n){if(t===void 0)return{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`};if(t===null)return{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only type into a tmux pane`};let r=Iz(e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:Lz[r.kind]};let i=e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}const zz=`cc-candybar-slash`;function Bz(e,t,n,r){let i=fF(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function Vz(e){let t=Bz(e,`claude-input.read`,[`display`,`-p`,`-t`,e.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,e.pane]);if(t.kind===`rate-limited`)throw Error(t.reason);let[n=``,...r]=t.stdout.split(`
207
- `);return{inMode:n!==`0`,screen:r}}function Hz(e,t){let n=Bz(e,`claude-input.type`,[`load-buffer`,`-b`,zz,`-`,`;`,`send-keys`,`-t`,e.pane,`C-s`,`;`,`paste-buffer`,`-p`,`-d`,`-b`,zz,`-t`,e.pane,`;`,`send-keys`,`-t`,e.pane,`Enter`],t);return n.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${n.reason})`}}function Uz(){return{read:Vz,type:Hz}}function Wz(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function Gz(e){return Kz(()=>decodeURIComponent(e))}function Kz(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function qz(e,t){let n=k({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 Jz=(e,t)=>qz(Gz(e),t),Yz=(e,t)=>{let n=k({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,Gz(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`})`)}},Xz=(e,t)=>qz(Gz(e),t),Zz=(e,t)=>qz(Gz(e),t),Qz=(e,t)=>{let n=Wz(Gz(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},$z=(e,t)=>{let[n=``,...r]=Kz(()=>Ek(e)),i=Wz(n),a=NN(dB(t,i));if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new $(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new $(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new $(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}rB(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},eB=/^-?\d+$/;function tB(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const nB=(e,t)=>{let[n=``,r=``,i=``]=Kz(()=>Ek(e)),a=Wz(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!eB.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=dB(t,a),c=NN(s),l=c.rangeParamsFor(r);if(!l)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&eB.test(u)?iB(l,parseInt(u,10)):aB(`step-state`,r,l,IN(s,e=>t.sessionState.get(a,e),r)),f=tB(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new $(`step-state: ${p.reason}`);rB(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function rB(e,t,n,r){let i=r.filter(e=>e.key.startsWith(Iv));if(i.length===0)return;let a=mN(dB(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new $(`${n}: refused — ${a.join(`; `)}`)}function iB(e,t){return Math.max(e.min,Math.min(e.max,t))}function aB(e,t,n,r){if(r===null)return n.min;if(!eB.test(r))throw new $(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return iB(n,parseInt(r,10))}const oB=`render-origin`;function sB(e){return JSON.stringify(e)}function cB(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 lB(e,t){let n=e.sessionState.get(t,oB);if(n===null)throw new $(`session ${t} has not rendered yet — no config to act on`);return cB(n)}function uB(e,t,n){let r=e.sessionState.get(t,oB);if(r===null)return;let i=cB(r),{path:a}=fB(i);n.some(e=>e.kind===`file`&&e.file===a)&&e.reloadConfig(i)}function dB(e,t){return e.configFor(lB(e,t))}function fB(e){return ZE(e.projectDir,e.cwd,e.configFile??void 0)}function pB(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const mB=(e,t)=>{let[n=``,r=``,i=``]=Kz(()=>Ek(e)),a=Wz(n),o=lB(t,a),s=t.configFor(o),c=Bj(s);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new $(`set-config: ${l.reason}`);let u=fB(o),d=fN(s,e=>t.sessionState.get(a,e),r);vR(pB(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},hB=(e,t)=>{let[n=``,r=``,i=``]=Kz(()=>Ek(e)),a=Wz(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!eB.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=lB(t,a),c=t.configFor(s),l=Bj(c),u=l.rangeParamsFor(r);if(!u)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=fB(s),f=fN(c,e=>t.sessionState.get(a,e),r),p=_R(d.path,f.key),m=typeof p==`number`?iB(u,p):aB(`step-config`,r,u,Hj(f.globals,r)),h=tB(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new $(`step-config: ${g.reason}`);vR(pB(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.dlog(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},gB=(e,t)=>{let[n=``]=Kz(()=>Ek(e)),r=Wz(n),i=lB(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=uN(a,o),c=pN(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=NN(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new $(`save: ${t.reason}`);return[e.target,t.value]});vB(`save`,l,c);let d=fB(i);yR(pB(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.dlog(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(_B)].join(` `)} → ${d.path} (session=${r})`)},_B=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Dc(e.value)}`;function vB(e,t,n){for(let r of n){let n=t.validate(r.key,Dc(r.value));if(!n.ok)throw new $(`${e}: ${n.reason}`)}}const yB=(e,t)=>{let[n=``]=Kz(()=>Ek(e)),r=Wz(n),i=lB(t,r),a=t.configFor(i),o=_N(a,e=>t.sessionState.get(r,e)),s=NN(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new $(`save-preset: ${t.reason}`);return[e.configKey,t.value]});vB(`save-preset`,s,o.placements);let l=fB(i),u=ER(pB(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...kx.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Ox.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(_B)].join(` `)} → ${l.path} (session=${r})`)},bB=(e,t)=>{let[n=``,r=``]=Kz(()=>Ek(e)),i=Wz(n);if(!r)throw new $(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=lB(t,i),o=fB(a);DR(pB(t,i),o,r),t.reloadConfig(a);let s=Ox.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},xB=(e,t)=>{let[n=``,...r]=Kz(()=>Ek(e)),i=Wz(n),a=lB(t,i),o=Bj(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new $(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=fB(a),l=r.map(vN),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);CR(pB(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.dlog(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function SB(e,t){let n=(e,t)=>[...pc(hv(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(fv(t.presets).flatMap(e=>n(t,e).map(t=>Lv(td(e),lc(t)))));return fv(e.presets).flatMap(t=>n(e,t).map(e=>({member:Lv(td(t),lc(e)),node:e})).filter(({member:e})=>!r.has(e)))}function CB(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[jv]:[]])}const wB=(e,t)=>{let[n=``,r=``,i=``]=Kz(()=>Ek(e)),a=Wz(n),o=lB(t,a),s=t.configFor(o),c=Bj(s);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new $(`apply-layout-op: ${l.reason}`);let u=Ej(l.value);if(u===null)throw new $(`apply-layout-op: "${l.value}" is not a layout op token`);let d=fB(o),f=OR(pB(t,a),d,r,u);t.reloadConfig(o);let p=CB(SB(s,t.configFor(o)),t.sessionState.get(a,jv)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.dlog(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},TB=(e,t)=>{let[n=``]=Kz(()=>Ek(e)),r=Wz(n);t.journal.commit();let i=t.history.undo(r);uB(t,r,i),t.dlog(`info`,`undo: restored ${XR(i)} (session=${r})`)},EB=(e,t)=>{let n=Wz(Gz(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,NN(dB(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},DB=(e,t)=>{let n=Wz(Gz(e));t.journal.commit();let r=t.history.rewind(n);uB(t,n,r),t.dlog(`info`,`rewind: put back ${XR(r)||`nothing`} as edit mode found it (session=${n})`)},OB=(e,t)=>{let[n=``]=Kz(()=>Ek(e)),r=Wz(n);t.journal.commit();let i=t.history.redo(r);uB(t,r,i),t.dlog(`info`,`redo: re-applied ${XR(i)} (session=${r})`)},kB=(e,t)=>{Wz(Gz(e)),t.applyUpdate()},AB=`client-hints`;function jB(e,t){let n=e.sessionState.get(t,AB);if(n===null)throw new $(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new $(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new $(`client hints record is not an object: ${n}`);return GD(r)}function MB(e,t,n){let r=RS(n);e.sessionState.setBatch(t,US(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} (session=${t})`)}function NB(e,t){return{...fz(e.doctor,jB(e,t),lB(e,t)),urlHandler:dz(e.clientVersion)}}const PB=(e,t)=>{let n=Wz(Gz(e));MB(t,n,NB(t,n))},FB=(e,t)=>{let n=Tz(Gz(e));if(n===null)throw new $(`doctor-probe: the value is not a probe nonce`);t.probes.arrive({nonce:n,handler:t.clientVersion}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${t.clientVersion??`unreported`}`)},IB=(e,t)=>{let[n=``,r=``]=Kz(()=>Ek(e)),i=Wz(n),a=zS(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=NB(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new $(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=pz(s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.name}=${s.fix.value} (session=${i})`),MB(t,i,c)},LB=(e,t)=>{let[n=``,...r]=Kz(()=>Ek(e)),i=Wz(n),a=lB(t,i),o=Object.values(t.configFor(a).actions).filter(e=>`ceiling`in e).find(e=>{let t=bT(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(o===void 0)throw new $(`ceiling: "${r.join(` `)}" is not a move this config declares`);let s=o.ceiling===`set`?{kind:`set`,to:o.to}:{kind:`clear`},c=vM({sessionId:i,projectDir:a.projectDir,cwd:a.cwd},jB(t,i));t.memento.move(c,s),t.dlog(`info`,`ceiling: ${r.join(` `)} (session=${i} claudeConfigDir=${c.claudeConfigDir})`)},RB=(e,t)=>{let[n=``,r=``]=Kz(()=>Ek(e)),i=Wz(n),a=Object.values(t.configFor(lB(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new $(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=Rz(t.claudeInput,jB(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new $(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)},zB=`config-override`,BB=new Map([[rk,Jz],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=Wz(Kz(()=>decodeURIComponent(e.slice(0,n)))),i=Kz(()=>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,zB),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,zB,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[ik,Yz],[tk,$z],[nk,nB],[ck,mB],[lk,hB],[pk,xB],[uk,gB],[dk,yB],[fk,bB],[mk,wB],[hk,TB],[gk,OB],[_k,EB],[vk,DB],[ok,Xz],[sk,Zz],[ak,Qz],[yk,kB],[bk,PB],[xk,IB],[Sk,FB],[Ck,LB],[wk,RB]]),VB=new Set([tk,nk,ck,lk,pk,uk,dk,fk,mk,hk,gk,_k,vk,ak,yk,bk,xk,Ck,wk]),HB=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Ak(Ok(e))){if(!i&&VB.has(a)){let e=Ek(o);e.length>0&&e[0]&&(i=e[0])}let e=BB.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(`
208
- `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}};function UB(e){return(t,n)=>{let r=n.history.begin(),i=n.navigation.begin(r.sessionState),a=[];try{e(t,{...n,sessionState:r.sessionState,journal:r,navigating:i.sessionState})}catch(e){a.push(e)}i.commit();try{r.commit()}catch(e){a.push(e)}if(a.length===1)throw a[0];if(a.length>1)throw Error(a.map(e=>String(e.message??e)).join(`; `))}}const WB=new Map([...BB,[ek,HB]].map(([e,t])=>[e,UB(t)]));Object.freeze([...WB.keys()]);const GB=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`]),KB=[[`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`]],qB=[[`workspace.added_dirs`,`string-list`]];function JB(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of KB){let i=ZB(n,e);if(i==null)t.missingRequired.push(e);else{let n=YB(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of qB){let i=ZB(n,e),a=i===void 0?r:XB(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))GB.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function YB(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function XB(e){return Array.isArray(e)&&e.every(e=>YB(e)===`string`)?`string-list`:YB(e)}function ZB(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 QB(e,t){switch(e){case`vars`:return{what:e,vars:$B(t)};case`segments`:return{what:e,segments:iV(t)};case`config`:return{what:e,config:cV(t)}}}function $B(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=nV(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,...eV(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:tV(r.lastUpdatedMs())})}return o}function eV(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 tV(e){return e===null?null:Math.max(0,Date.now()-e)}function nV(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,rV(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}`,rV(i));return t}function rV(e){return e.kind}function iV(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=oV(n),o=aV(n),s=[];for(let e of a){let t=n.segments[e];t&&s.push({name:e,description:t.description??null,template:t.template,referencedVars:sV(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function aV(e){let t=new Map;for(let n of fv(e.presets))for(let r of pc(hv(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=lc(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function oV(e){let t=[],n=new Set;for(let r of pc(gl(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 sV(e,t,n){let r=new Set;for(let i of ny(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 cV(e){return e===null?null:e.config}const lV=[`vars`,`segments`,`config`];function uV(e){return typeof e==`string`&&lV.includes(e)}function dV(e){return Math.max(1,e-2)}var fV=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return l.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 pV=new CL,mV=new Cz;Oe(pV.launchStats);const hV=new Gb({counters:pV,logger:Z}),gV=vF({watchers:hV,logger:Z}),{gitProvider:_V,usageStore:vV,mementoProvider:yV}=gV,bV=new DL,xV=new IR(bV,Z),SV=new az,CV=new fV(Xe()),wV=new xL({gitService:_V,sessionState:bV,watchers:hV},{observers:{onReload:e=>Z(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),TV=60*1e3;function EV(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(E(e)),t.argv[1]&&n.push(t.argv[1]);let i=new Map;for(let e of n)try{i.set(e,r.statSync(e).mtimeMs)}catch{}let a=null,o=()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){Z(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),HV(0);return}}catch(e){Z(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,TV),a.unref())},checkNow:o}}const DV=EV(),OV=tP({entryUrl:import.meta.url,intervalMs:TV,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>DV.checkNow(),log:Z});let kV=null,AV=null,jV=0;function MV(){t.on(`uncaughtException`,e=>{Z(`error`,`uncaughtException: ${e.stack||e.message}`),HV(1)}),t.on(`unhandledRejection`,e=>{Z(`error`,`unhandledRejection: ${String(e)}`),HV(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Z(`info`,`received ${e}, shutting down`),HV(0)});try{jV=EO(t.env)}catch(e){Z(`error`,`refusing to boot: ${e.message}`),HV(1);return}kV=EA(t.pid);let e=IA(RA(kV));if(!e.decision.allow){Z(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),HV(1);return}AV=e.registryPath,r.mkdirSync(Le(),{recursive:!0}),Ve(Re()),bV.useStorage(new kL(We(),500,Z)),xV.useStorage(rz(Ge(),Z)),kA({anchor:OA(t.env),isAlive:AA,onOrphaned:e=>{Z(`info`,`parent watchdog: ${e}; shutting down`),HV(0)}}),NV(x.createServer({allowHalfOpen:!1},e=>{UV(e)}),Re(),!1)}function NV(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Z(`error`,`server error: ${i.message}`),HV(1);return}if(r){Z(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}PV(e,n)}),e.listen(n,()=>FV(n))}function PV(e,n){let i=gA(_A(He(n)),(e,t)=>TA(e,t,{readStartTime:wA,pidAlive:AA}));if(i.kind===`attach-and-exit`){Z(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}Z(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){Z(`error`,`cannot unlink stale socket ${n}: ${e.message}`),HV(1);return}}NV(e,n,!0)}function FV(e){let n=bA(e);if(n.kind!==`present`){Z(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),HV(0);return}zV(e);try{r.chmodSync(e,384)}catch(e){Z(`warn`,`chmod socket failed: ${e.message}`)}Z(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(re.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(jV/1048576)}MB`),UO();let i=CV.reset();i!==null&&Z(`warn`,`diagnostic dump wipe failed: ${i}`),DV.arm(),OV.arm(),RV(),IV(e,n.identity)}function IV(e,n){CA({bound:n,myPid:t.pid,readIdentity:()=>bA(e),readLease:()=>_A(He(e)),shutdown:e=>HV(e),log:Z}).arm()}let LV=null;function RV(){LV=AO(PO(pV.startedAt.getTime(),e=>HV(e),{rssLimitBytes:jV})),LV.arm()}function zV(e){let n=vA(He(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:kV});n!==null&&Z(`warn`,`lease write failed: ${n}`)}let BV=0,VV=!1;function HV(e){if(!VV){VV=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{_V.close()}catch(e){Z(`warn`,`gitService close failed: ${e.message}`)}try{vV.close()}catch(e){Z(`warn`,`usageStore close failed: ${e.message}`)}try{hV.closeAll()}catch(e){Z(`warn`,`watcherRegistry close failed: ${e.message}`)}try{bV.flush()}catch(e){Z(`warn`,`sessionState flush failed: ${e.message}`)}yA(Ue(),t.pid),AV!==null&&LA(AV,t.pid,PA,e=>r.unlinkSync(e)),t.exit(e)}}function UV(e){BV++,pV.inFlight=BV;let t=!1,n=(n,r)=>{if(t){r!==null&&Z(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>HV(r);try{e.end(tO(n),i)}catch(e){Z(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{pV.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=nO(e=>{GV(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{Z(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{Z(`warn`,`frame parse failed: ${e.message}`),n({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null)});e.on(`data`,i),e.on(`error`,e=>{Z(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),BV=Math.max(0,BV-1),pV.inFlight=BV})}const WV=e=>({resp:e,exitAfterFlush:null});async function GV(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return WV({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?Z(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):Z(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null};if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0};if(e.kind===`stats`)return WV({ok:!0,stats:pV.snapshot({gitCache:_V.getStats(),usageCache:vV.getStats(),renderCacheSize:wV.size,watchersActive:hV.size(),nextRestartReason:LV?.describeNextRestart()??null,handlerProbes:mV.list()})});if(e.kind===`render`){pV.requestsTotal++;let t=Date.now();try{let{report:n}=JB(e.hookData);for(let e of n.unknownTopLevelFields)Z(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let r=[];for(let e of n.missingRequired)r.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:i}of n.typeMismatches)r.push(`field '${e}' expected ${t}, got ${i}`);if(e.cwd===``&&r.push(`request 'cwd' is empty`),r.length>0)return pV.requestsErrored++,Z(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),WV({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=KV(e.args),s=e.hookData.session_id,c=GD(e),l=JSON.stringify(c);bV.get(s,`client-hints`)!==l&&bV.set(s,AB,l);let u=bV.get(s,`config-override`)??a??c.configEnv,d=wV.getOrCreate(i,e.cwd,u),f=sB({projectDir:i,cwd:e.cwd,configFile:u??null});bV.get(s,`render-origin`)!==f&&bV.set(s,oB,f);let p=c.termCols,m=dV(p??120),h=ij(c.termRows),{authoredRoots:g}=d.state,_=t=>bV.get(e.hookData.session_id,t),v=jM(d.state.config,_,e=>g.has(e)),y=await JM(e.hookData,{...ZV,navigation:e=>SV.depth(e,bV,NN(d.state.config))},e.cwd,d.state.neededInputPaths(v.preset),v,c,{...bN(d.state.config,d.state.fileHeldSettings,_),configPath:d.configLayers.includes(d.configHome)?d.configHome:null}),b=[],x=MM(v,m),S=tL(d.state.config,d.state.compiled,d.state.store,d.state.registry,y,x,{perSegmentSink:d.state.lastRenderCellsBySegment,onRenderWarning:e=>b.push(e)},NM(v)),C=bV.get(e.hookData.session_id,`click.error`);C&&bV.clear(e.hookData.session_id,`click.error`);let w=[o,d.lastError,C].filter(Boolean).join(`
209
- `),ee=OV.notice({sessionId:s,dismissed:bV.get(s,zN),enabled:v.updateNotice}),te=d.lastError===null?null:d.failedFile,ne=lj(w,ee,[d.lastWarning??``,...b].filter(Boolean).join(`
210
- `)),re=CV.sync(s,ne===null?null:dj(ne));re!==null&&Z(`warn`,`diagnostic dump failed: ${re}`);let ie=fj(S,ne,{fullText:re===null?{kind:`file`,path:CV.pathFor(s)}:{kind:`unavailable`,reason:re},failedConfigFile:te},{width:m,rowCap:h,colorCompatibility:v.colorCompatibility}),T=Date.now()-t,E=_V.getStats(),ae=vV.getStats();return Z(`info`,`render sid=${e.hookData.session_id??`?`} took=${T}ms termCols=${p??`?`} termRows=${c.termRows??`?`} width=${m} git=${E.size}/${E.hits}h/${E.misses}m usage=${ae.size}/${ae.hits}h/${ae.misses}m err=${w?`Y`:`N`} upd=${ee.length} warn=${d.lastWarning?`Y`:`N`}`),WV({ok:!0,output:ie+`
211
- `})}catch(e){throw pV.requestsErrored++,e}}if(e.kind===`click`)return WV(QV(e.verb,e.value,$D(e.clientVersion)));if(e.kind===`debug`){if(!uV(e.what))return WV({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${lV.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=wV.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?XV(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):YV};return WV({ok:!0,debug:QB(e.what,n)})}return WV({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function KV(e){let{values:t,tokens:n}=y({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:JD(t.config),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}const qV={sessionState:bV,dlog:Z,applyUpdate:()=>OV.act(),doctor:sz(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];wV.reload(...t);let n=wV.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused}}),probes:mV,memento:yV,claudeInput:Uz(),history:xV,navigation:SV,configFor:e=>wV.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>wV.reload(e.projectDir,e.cwd,e.configFile??void 0)};qV.reloadConfig;const JV={endcaps:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:Xo,width:1/0},YV=new Map;function XV(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,rj(a,{...JV,charset:t,colorCompatibility:n}));return r}const ZV={...gV,clock:()=>new Date,history:e=>xV.depth(e)};function QV(e,t,n){let r=WB.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return r(t,{...qV,clientVersion:n}),{ok:!0,output:``}}catch(e){let t=e instanceof $?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}const $V={connectMs:200,budgetMs:500};async function eH(e,n){let r=n.includes(`--json`),i=await tH(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${uO(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
212
- `);return}t.stdout.write(nH(i.value))}function tH(e){return iO({kind:`debug`,what:e},$V,e=>`debug`in e?e.debug:void 0)}function nH(e){switch(e.what){case`vars`:return rH(e.vars);case`segments`:return iH(e.segments);case`config`:return aH(e.config);default:return e}}function rH(e){if(e.length===0)return`no variables (DSL not active)
213
- `;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?``:` ${sH(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${oH(a.value)}${e}${o}`)}return t.join(`
205
+ `}const Tz=e=>({kind:`ok`,value:e}),Ez=e=>({kind:`failed`,reason:e});var Dz=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const Oz=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function kz(e){return Oz.test(e)?e:null}function Az(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return Tz(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return Tz({app:n,missing:Ez(`its script could not be read (${r.reason})`)});let i=iA(r.value);return Tz({app:n,missing:i===null?Ez("its script is not one `cc-candybar install` wrote"):Tz([i.node,i.script].filter(t=>!e.exists(t)))})}async function jz(e,t){let n=e.now()+5e3;for(;e.now()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,handler:r.handler,bar:n.value.version}}return null}async function Mz(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${rk}://${Ek}/${n}`);return(r===null?await jz(e,n):null)??{kind:`lost`,unopened:r,opener:Az(e)}}function Nz(e,t,n){let r=k({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?Tz(r.stdout):Ez(r.stderr.trim()||r.error||r.reason)}const Pz=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${rk}://probe"));u.isNil() ? "" : u.path.js`;async function Fz(){let e=await bz();if(e.kind!==`ok`)return Ez(mO(e).split(`
206
+ `).join(` — `));let{version:t,handlerProbes:n}=e.value;return Array.isArray(n)?Tz({version:t,arrivals:n}):Ez(`the running daemon (${t}) predates this check`)}function Iz(){return{platform:process.platform,sockets:{own:Re(),handler:ze()},now:Date.now,nonce:ce,daemon:Fz,open:e=>{let t=Nz(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=Nz(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,Pz]);if(e.kind===`failed`)return e;let t=e.value.trim();return Tz(t===``?null:t)},script:e=>Nz(`doctor.osadecompile`,`/usr/bin/osadecompile`,[aA(e)]),exists:r.existsSync}}const Lz=/^─{20,}/,Rz=/^❯(\s|$)/,zz=/›\s*stashed$/;function Bz(e){if(e.inMode)return{kind:`in-mode`};let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>Lz.test(e)?[t]:[]).at(-2);return n===void 0||!Rz.test(t[n+1]??``)?{kind:`no-prompt`}:zz.test(t[n-1]??``)?{kind:`stashed`}:{kind:`ready`}}const Vz={"in-mode":`the Claude Code pane is in tmux copy mode — leave it (q) and click again`,stashed:`Claude Code is holding a stashed prompt (ctrl+s) — restore or send it, then click again`,"no-prompt":`Claude Code is not at its prompt (a dialog or picker is open) — close it and click again`};function Hz(e,t,n){if(t===void 0)return{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`};if(t===null)return{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only type into a tmux pane`};let r=Bz(e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:Vz[r.kind]};let i=e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}const Uz=`cc-candybar-slash`;function Wz(e,t,n,r){let i=gF(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function Gz(e){let t=Wz(e,`claude-input.read`,[`display`,`-p`,`-t`,e.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,e.pane]);if(t.kind===`rate-limited`)throw Error(t.reason);let[n=``,...r]=t.stdout.split(`
207
+ `);return{inMode:n!==`0`,screen:r}}function Kz(e,t){let n=Wz(e,`claude-input.type`,[`load-buffer`,`-b`,Uz,`-`,`;`,`send-keys`,`-t`,e.pane,`C-s`,`;`,`paste-buffer`,`-p`,`-d`,`-b`,Uz,`-t`,e.pane,`;`,`send-keys`,`-t`,e.pane,`Enter`],t);return n.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${n.reason})`}}function qz(){return{read:Gz,type:Kz}}function Jz(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function Yz(e){return Xz(()=>decodeURIComponent(e))}function Xz(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function Zz(e,t){let n=k({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 Qz=(e,t)=>Zz(Yz(e),t),$z=(e,t)=>{let n=k({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,Yz(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`})`)}},eB=(e,t)=>Zz(Yz(e),t),tB=(e,t)=>Zz(Yz(e),t),nB=(e,t)=>{let n=Jz(Yz(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},rB=(e,t)=>{let[n=``,...r]=Xz(()=>Ak(e)),i=Jz(n),a=LN(hB(t,i));if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new $(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new $(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new $(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}sB(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},iB=/^-?\d+$/;function aB(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const oB=(e,t)=>{let[n=``,r=``,i=``]=Xz(()=>Ak(e)),a=Jz(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!iB.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=hB(t,a),c=LN(s),l=c.rangeParamsFor(r);if(!l)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&iB.test(u)?cB(l,parseInt(u,10)):lB(`step-state`,r,l,BN(s,e=>t.sessionState.get(a,e),r)),f=aB(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new $(`step-state: ${p.reason}`);sB(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function sB(e,t,n,r){let i=r.filter(e=>e.key.startsWith(Iv));if(i.length===0)return;let a=vN(hB(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new $(`${n}: refused — ${a.join(`; `)}`)}function cB(e,t){return Math.max(e.min,Math.min(e.max,t))}function lB(e,t,n,r){if(r===null)return n.min;if(!iB.test(r))throw new $(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return cB(n,parseInt(r,10))}const uB=`render-origin`;function dB(e){return JSON.stringify(e)}function fB(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 pB(e,t){let n=e.sessionState.get(t,uB);if(n===null)throw new $(`session ${t} has not rendered yet — no config to act on`);return fB(n)}function mB(e,t,n){let r=e.sessionState.get(t,uB);if(r===null)return;let i=fB(r),{path:a}=gB(i);n.some(e=>e.kind===`file`&&e.file===a)&&e.reloadConfig(i)}function hB(e,t){return e.configFor(pB(e,t))}function gB(e){return $E(e.projectDir,e.cwd,e.configFile??void 0)}function _B(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const vB=(e,t)=>{let[n=``,r=``,i=``]=Xz(()=>Ak(e)),a=Jz(n),o=pB(t,a),s=t.configFor(o),c=Wj(s);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new $(`set-config: ${l.reason}`);let u=gB(o),d=gN(s,e=>t.sessionState.get(a,e),r);SR(_B(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},yB=(e,t)=>{let[n=``,r=``,i=``]=Xz(()=>Ak(e)),a=Jz(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!iB.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=pB(t,a),c=t.configFor(s),l=Wj(c),u=l.rangeParamsFor(r);if(!u)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=gB(s),f=gN(c,e=>t.sessionState.get(a,e),r),p=xR(d.path,f.key),m=typeof p==`number`?cB(u,p):lB(`step-config`,r,u,Kj(f.globals,r)),h=aB(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new $(`step-config: ${g.reason}`);SR(_B(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.dlog(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},bB=(e,t)=>{let[n=``]=Xz(()=>Ak(e)),r=Jz(n),i=pB(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=mN(a,o),c=_N(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=LN(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new $(`save: ${t.reason}`);return[e.target,t.value]});SB(`save`,l,c);let d=gB(i);CR(_B(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.dlog(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(xB)].join(` `)} → ${d.path} (session=${r})`)},xB=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Dc(e.value)}`;function SB(e,t,n){for(let r of n){let n=t.validate(r.key,Dc(r.value));if(!n.ok)throw new $(`${e}: ${n.reason}`)}}const CB=(e,t)=>{let[n=``]=Xz(()=>Ak(e)),r=Jz(n),i=pB(t,r),a=t.configFor(i),o=xN(a,e=>t.sessionState.get(r,e)),s=LN(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new $(`save-preset: ${t.reason}`);return[e.configKey,t.value]});SB(`save-preset`,s,o.placements);let l=gB(i),u=AR(_B(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...kx.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Ox.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(xB)].join(` `)} → ${l.path} (session=${r})`)},wB=(e,t)=>{let[n=``,r=``]=Xz(()=>Ak(e)),i=Jz(n);if(!r)throw new $(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=pB(t,i),o=gB(a);jR(_B(t,i),o,r),t.reloadConfig(a);let s=Ox.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},TB=(e,t)=>{let[n=``,...r]=Xz(()=>Ak(e)),i=Jz(n),a=pB(t,i),o=Wj(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new $(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=gB(a),l=r.map(SN),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);DR(_B(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.dlog(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function EB(e,t){let n=(e,t)=>[...pc(hv(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(fv(t.presets).flatMap(e=>n(t,e).map(t=>Lv(td(e),lc(t)))));return fv(e.presets).flatMap(t=>n(e,t).map(e=>({member:Lv(td(t),lc(e)),node:e})).filter(({member:e})=>!r.has(e)))}function DB(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[jv]:[]])}const OB=(e,t)=>{let[n=``,r=``,i=``]=Xz(()=>Ak(e)),a=Jz(n),o=pB(t,a),s=t.configFor(o),c=Wj(s);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new $(`apply-layout-op: ${l.reason}`);let u=Aj(l.value);if(u===null)throw new $(`apply-layout-op: "${l.value}" is not a layout op token`);let d=gB(o),f=MR(_B(t,a),d,r,u);t.reloadConfig(o);let p=DB(EB(s,t.configFor(o)),t.sessionState.get(a,jv)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.dlog(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},kB=(e,t)=>{let[n=``]=Xz(()=>Ak(e)),r=Jz(n);t.journal.commit();let i=t.history.undo(r);mB(t,r,i),t.dlog(`info`,`undo: restored ${ez(i)} (session=${r})`)},AB=(e,t)=>{let n=Jz(Yz(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,LN(hB(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},jB=(e,t)=>{let n=Jz(Yz(e));t.journal.commit();let r=t.history.rewind(n);mB(t,n,r),t.dlog(`info`,`rewind: put back ${ez(r)||`nothing`} as edit mode found it (session=${n})`)},MB=(e,t)=>{let[n=``]=Xz(()=>Ak(e)),r=Jz(n);t.journal.commit();let i=t.history.redo(r);mB(t,r,i),t.dlog(`info`,`redo: re-applied ${ez(i)} (session=${r})`)},NB=(e,t)=>{Jz(Yz(e)),t.applyUpdate()},PB=`client-hints`;function FB(e,t){let n=e.sessionState.get(t,PB);if(n===null)throw new $(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new $(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new $(`client hints record is not an object: ${n}`);return YD(r)}function IB(e,t,n){let r=RS(n);e.sessionState.setBatch(t,US(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} (session=${t})`)}function LB(e,t){return{...gz(e.doctor,FB(e,t),pB(e,t)),urlHandler:hz(e.clientVersion)}}const RB=(e,t)=>{let n=Jz(Yz(e));IB(t,n,LB(t,n))},zB=(e,t)=>{let n=kz(Yz(e));if(n===null)throw new $(`doctor-probe: the value is not a probe nonce`);t.probes.arrive({nonce:n,handler:t.clientVersion}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${t.clientVersion??`unreported`}`)},BB=(e,t)=>{let[n=``,r=``]=Xz(()=>Ak(e)),i=Jz(n),a=zS(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=LB(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new $(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=_z(s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.name}=${s.fix.value} (session=${i})`),IB(t,i,c)},VB=(e,t)=>{let[n=``,...r]=Xz(()=>Ak(e)),i=Jz(n),a=pB(t,i),o=Object.values(t.configFor(a).actions).filter(e=>`ceiling`in e).find(e=>{let t=bT(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(o===void 0)throw new $(`ceiling: "${r.join(` `)}" is not a move this config declares`);let s=o.ceiling===`set`?{kind:`set`,to:o.to}:{kind:`clear`},c=SM({sessionId:i,projectDir:a.projectDir,cwd:a.cwd},FB(t,i));t.memento.move(c,s),t.dlog(`info`,`ceiling: ${r.join(` `)} (session=${i} claudeConfigDir=${c.claudeConfigDir})`)},HB=(e,t)=>{let[n=``,r=``]=Xz(()=>Ak(e)),i=Jz(n),a=Object.values(t.configFor(pB(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new $(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=Hz(t.claudeInput,FB(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new $(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)},UB=`config-override`,WB=new Map([[sk,Qz],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=Jz(Xz(()=>decodeURIComponent(e.slice(0,n)))),i=Xz(()=>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,UB),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,UB,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[ck,$z],[ak,rB],[ok,oB],[fk,vB],[pk,yB],[_k,TB],[mk,bB],[hk,CB],[gk,wB],[vk,OB],[yk,kB],[bk,MB],[xk,AB],[Sk,jB],[uk,eB],[dk,tB],[lk,nB],[Ck,NB],[wk,RB],[Tk,BB],[Ek,zB],[Dk,VB],[Ok,HB]]),GB=new Set([ak,ok,fk,pk,_k,mk,hk,gk,vk,yk,bk,xk,Sk,lk,Ck,wk,Tk,Dk,Ok]),KB=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Pk(Mk(e))){if(!i&&GB.has(a)){let e=Ak(o);e.length>0&&e[0]&&(i=e[0])}let e=WB.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(`
208
+ `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}};function qB(e){return(t,n)=>{let r=n.history.begin(),i=n.navigation.begin(r.sessionState),a=[];try{e(t,{...n,sessionState:r.sessionState,journal:r,navigating:i.sessionState})}catch(e){a.push(e)}i.commit();try{r.commit()}catch(e){a.push(e)}if(a.length===1)throw a[0];if(a.length>1)throw Error(a.map(e=>String(e.message??e)).join(`; `))}}const JB=new Map([...WB,[ik,KB]].map(([e,t])=>[e,qB(t)]));Object.freeze([...JB.keys()]);const YB=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`]),XB=[[`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`]],ZB=[[`workspace.added_dirs`,`string-list`]];function QB(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of XB){let i=tV(n,e);if(i==null)t.missingRequired.push(e);else{let n=$B(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of ZB){let i=tV(n,e),a=i===void 0?r:eV(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))YB.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function $B(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function eV(e){return Array.isArray(e)&&e.every(e=>$B(e)===`string`)?`string-list`:$B(e)}function tV(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 nV(e,t){switch(e){case`vars`:return{what:e,vars:rV(t)};case`segments`:return{what:e,segments:cV(t)};case`config`:return{what:e,config:fV(t)}}}function rV(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=oV(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,...iV(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:aV(r.lastUpdatedMs())})}return o}function iV(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 aV(e){return e===null?null:Math.max(0,Date.now()-e)}function oV(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,sV(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}`,sV(i));return t}function sV(e){return e.kind}function cV(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=uV(n),o=lV(n),s=[];for(let e of a){let t=n.segments[e];t&&s.push({name:e,description:t.description??null,template:t.template,referencedVars:dV(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function lV(e){let t=new Map;for(let n of fv(e.presets))for(let r of pc(hv(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=lc(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function uV(e){let t=[],n=new Set;for(let r of pc(gl(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 dV(e,t,n){let r=new Set;for(let i of ny(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 fV(e){return e===null?null:e.config}const pV=[`vars`,`segments`,`config`];function mV(e){return typeof e==`string`&&pV.includes(e)}function hV(e){return Math.max(1,e-2)}var gV=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return l.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 _V=new DL,vV=new Dz;Oe(_V.launchStats);const yV=new Gb({counters:_V,logger:Z}),bV=SF({watchers:yV,logger:Z}),{gitProvider:xV,usageStore:SV,mementoProvider:CV}=bV,wV=new jL,TV=new BR(wV,Z),EV=new lz,DV=new gV(Xe()),OV=new TL({gitService:xV,sessionState:wV,watchers:yV},{observers:{onReload:e=>Z(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),kV=60*1e3;function AV(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(E(e)),t.argv[1]&&n.push(t.argv[1]);let i=new Map;for(let e of n)try{i.set(e,r.statSync(e).mtimeMs)}catch{}let a=null,o=()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){Z(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),KV(0);return}}catch(e){Z(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,kV),a.unref())},checkNow:o}}const jV=AV(),MV=aP({entryUrl:import.meta.url,intervalMs:kV,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>jV.checkNow(),log:Z});let NV=null,PV=null,FV=0;function IV(){t.on(`uncaughtException`,e=>{Z(`error`,`uncaughtException: ${e.stack||e.message}`),KV(1)}),t.on(`unhandledRejection`,e=>{Z(`error`,`unhandledRejection: ${String(e)}`),KV(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Z(`info`,`received ${e}, shutting down`),KV(0)});try{FV=AO(t.env)}catch(e){Z(`error`,`refusing to boot: ${e.message}`),KV(1);return}NV=AA(t.pid);let e=BA(HA(NV));if(!e.decision.allow){Z(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),KV(1);return}PV=e.registryPath,r.mkdirSync(Le(),{recursive:!0}),Ve(Re()),wV.useStorage(new NL(We(),500,Z)),TV.useStorage(sz(Ge(),Z)),NA({anchor:MA(t.env),isAlive:PA,onOrphaned:e=>{Z(`info`,`parent watchdog: ${e}; shutting down`),KV(0)}}),LV(x.createServer({allowHalfOpen:!1},e=>{qV(e)}),Re(),!1)}function LV(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Z(`error`,`server error: ${i.message}`),KV(1);return}if(r){Z(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}RV(e,n)}),e.listen(n,()=>zV(n))}function RV(e,n){let i=bA(xA(He(n)),(e,t)=>kA(e,t,{readStartTime:OA,pidAlive:PA}));if(i.kind===`attach-and-exit`){Z(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}Z(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){Z(`error`,`cannot unlink stale socket ${n}: ${e.message}`),KV(1);return}}LV(e,n,!0)}function zV(e){let n=wA(e);if(n.kind!==`present`){Z(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),KV(0);return}UV(e);try{r.chmodSync(e,384)}catch(e){Z(`warn`,`chmod socket failed: ${e.message}`)}Z(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(re.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(FV/1048576)}MB`),qO();let i=DV.reset();i!==null&&Z(`warn`,`diagnostic dump wipe failed: ${i}`),jV.arm(),MV.arm(),HV(),BV(e,n.identity)}function BV(e,n){DA({bound:n,myPid:t.pid,readIdentity:()=>wA(e),readLease:()=>xA(He(e)),shutdown:e=>KV(e),log:Z}).arm()}let VV=null;function HV(){VV=PO(RO(_V.startedAt.getTime(),e=>KV(e),{rssLimitBytes:FV})),VV.arm()}function UV(e){let n=SA(He(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:NV});n!==null&&Z(`warn`,`lease write failed: ${n}`)}let WV=0,GV=!1;function KV(e){if(!GV){GV=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{xV.close()}catch(e){Z(`warn`,`gitService close failed: ${e.message}`)}try{SV.close()}catch(e){Z(`warn`,`usageStore close failed: ${e.message}`)}try{yV.closeAll()}catch(e){Z(`warn`,`watcherRegistry close failed: ${e.message}`)}try{wV.flush()}catch(e){Z(`warn`,`sessionState flush failed: ${e.message}`)}CA(Ue(),t.pid),PV!==null&&VA(PV,t.pid,RA,e=>r.unlinkSync(e)),t.exit(e)}}function qV(e){WV++,_V.inFlight=WV;let t=!1,n=(n,r)=>{if(t){r!==null&&Z(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>KV(r);try{e.end(aO(n),i)}catch(e){Z(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{_V.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=oO(e=>{YV(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{Z(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{Z(`warn`,`frame parse failed: ${e.message}`),n({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null)});e.on(`data`,i),e.on(`error`,e=>{Z(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),WV=Math.max(0,WV-1),_V.inFlight=WV})}const JV=e=>({resp:e,exitAfterFlush:null});async function YV(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return JV({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?Z(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):Z(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null};if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0};if(e.kind===`stats`)return JV({ok:!0,stats:_V.snapshot({gitCache:xV.getStats(),usageCache:SV.getStats(),renderCacheSize:OV.size,watchersActive:yV.size(),nextRestartReason:VV?.describeNextRestart()??null,handlerProbes:vV.list()})});if(e.kind===`render`){_V.requestsTotal++;let t=Date.now();try{let{report:n}=QB(e.hookData);for(let e of n.unknownTopLevelFields)Z(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let r=[];for(let e of n.missingRequired)r.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:i}of n.typeMismatches)r.push(`field '${e}' expected ${t}, got ${i}`);if(e.cwd===``&&r.push(`request 'cwd' is empty`),r.length>0)return _V.requestsErrored++,Z(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),JV({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=XV(e.args),s=e.hookData.session_id,c=YD(e),l=JSON.stringify(c);wV.get(s,`client-hints`)!==l&&wV.set(s,PB,l);let u=wV.get(s,`config-override`)??a??c.configEnv,d=OV.getOrCreate(i,e.cwd,u),f=dB({projectDir:i,cwd:e.cwd,configFile:u??null});wV.get(s,`render-origin`)!==f&&wV.set(s,uB,f);let p=c.termCols,m=hV(p??120),h=cj(c.termRows),{authoredRoots:g}=d.state,_=t=>wV.get(e.hookData.session_id,t),v=FM(d.state.config,_,e=>g.has(e)),y=await QM(e.hookData,{...tH,navigation:e=>EV.depth(e,wV,LN(d.state.config))},e.cwd,d.state.neededInputPaths(v.preset),v,c,{...wN(d.state.config,d.state.fileHeldSettings,_),configPath:d.configLayers.includes(d.configHome)?d.configHome:null}),b=[],x=IM(v,m),S=aL(d.state.config,d.state.compiled,d.state.store,d.state.registry,y,x,{perSegmentSink:d.state.lastRenderCellsBySegment,onRenderWarning:e=>b.push(e)},LM(v)),C=wV.get(e.hookData.session_id,`click.error`);C&&wV.clear(e.hookData.session_id,`click.error`);let w=[o,d.lastError,C].filter(Boolean).join(`
209
+ `),ee=MV.notice({sessionId:s,dismissed:wV.get(s,UN),enabled:v.updateNotice}),te=d.lastError===null?null:d.failedFile,ne=pj(w,ee,[d.lastWarning??``,...b].filter(Boolean).join(`
210
+ `)),re=DV.sync(s,ne===null?null:hj(ne));re!==null&&Z(`warn`,`diagnostic dump failed: ${re}`);let ie=gj(S,ne,{fullText:re===null?{kind:`file`,path:DV.pathFor(s)}:{kind:`unavailable`,reason:re},failedConfigFile:te},{width:m,rowCap:h,colorCompatibility:v.colorCompatibility}),T=Date.now()-t,E=xV.getStats(),ae=SV.getStats();return Z(`info`,`render sid=${e.hookData.session_id??`?`} took=${T}ms termCols=${p??`?`} termRows=${c.termRows??`?`} width=${m} git=${E.size}/${E.hits}h/${E.misses}m usage=${ae.size}/${ae.hits}h/${ae.misses}m err=${w?`Y`:`N`} upd=${ee.length} warn=${d.lastWarning?`Y`:`N`}`),JV({ok:!0,output:ie+`
211
+ `})}catch(e){throw _V.requestsErrored++,e}}if(e.kind===`click`)return JV(nH(e.verb,e.value,rO(e.clientVersion)));if(e.kind===`debug`){if(!mV(e.what))return JV({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${pV.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=OV.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?eH(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):$V};return JV({ok:!0,debug:nV(e.what,n)})}return JV({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function XV(e){let{values:t,tokens:n}=y({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:QD(t.config),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}const ZV={sessionState:wV,dlog:Z,applyUpdate:()=>MV.act(),doctor:dz(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];OV.reload(...t);let n=OV.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused}}),probes:vV,memento:CV,claudeInput:qz(),history:TV,navigation:EV,configFor:e=>OV.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>OV.reload(e.projectDir,e.cwd,e.configFile??void 0)};ZV.reloadConfig;const QV={endcaps:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:Xo,width:1/0},$V=new Map;function eH(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,sj(a,{...QV,charset:t,colorCompatibility:n}));return r}const tH={...bV,clock:()=>new Date,history:e=>TV.depth(e)};function nH(e,t,n){let r=JB.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return r(t,{...ZV,clientVersion:n}),{ok:!0,output:``}}catch(e){let t=e instanceof $?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}const rH={connectMs:200,budgetMs:500};async function iH(e,n){let r=n.includes(`--json`),i=await aH(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${mO(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
212
+ `);return}t.stdout.write(oH(i.value))}function aH(e){return cO({kind:`debug`,what:e},rH,e=>`debug`in e?e.debug:void 0)}function oH(e){switch(e.what){case`vars`:return sH(e.vars);case`segments`:return cH(e.segments);case`config`:return lH(e.config);default:return e}}function sH(e){if(e.length===0)return`no variables (DSL not active)
213
+ `;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?``:` ${dH(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${uH(a.value)}${e}${o}`)}return t.join(`
214
214
  `)+`
215
- `}function iH(e){if(e.length===0)return`no segments (DSL not active)
215
+ `}function cH(e){if(e.length===0)return`no segments (DSL not active)
216
216
  `;let t=[`segments (${e.length})`,``];for(let n of e){t.push(` ${n.name}`),n.description!==null&&t.push(` shows ${n.description}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`);for(let{id:e,lastRender:r}of n.placements)r!==null&&t.push(` last ${e}: ${r}`)}return t.join(`
217
217
  `)+`
218
- `}function aH(e){return e===null?`config: DSL not active
218
+ `}function lH(e){return e===null?`config: DSL not active
219
219
  `:JSON.stringify(e,null,2)+`
220
- `}function oH(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function sH(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function cH(){let e=uH();return e===null?null:r.readFileSync(e,`utf-8`)}function lH(){let e;try{e=cH()}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 uH(){let e=l.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let i=l.dirname(l.resolve(n));for(;;){let t=l.join(i,e);if(r.existsSync(t))return t;let n=l.dirname(i);if(n===i)return null;i=n}}function dH(e){let t=e.CC_CANDYBAR_CONFIG??``;return t===``?void 0:t}const fH=5e3;function pH(e,t){let n=`/home/tester`,r=Math.floor(Date.now()/1e3),i=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,a={current_dir:`${n}/code/cc-candybar/src`,project_dir:`${n}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:i,version:`1.15.0`,home:n,cwd:`${n}/code/cc-candybar/src`,transcript_path:`${n}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:a,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:r+2*3600},weekly:{percentage:21,resetsAt:r+5*86400},cache:{expiresAt:r+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:mC(4e5,1e6),...PM(e),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:Px(()=>!0),resumeCommand:AM(a,i,void 0),configPath:t??`${n}/.config/cc-candybar/config.json5`}}function mH(e,t){let n=YE(e,e),r=QE(n);return r!==null&&t.push(r),n.kind===`chain`?n.layers:[]}async function hH(e,n=t.cwd()){let i=[],a=e===void 0?null:l.resolve(KE(e)),o=a===null?mH(n,i):[a];if(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 s=eD(n,n);s!==null&&i.push(s);try{return{kind:`clean`,layers:o,warnings:i,rendered:await vH(o,n,i)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&o.includes(t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof nc&&i.push(...e.warnings),{kind:`fatal`,layers:o,message:e instanceof nc||e instanceof Error?e.message:String(e),warnings:i})}}async function gH(e,t,n){let r=PD(e,nM,{entered:()=>{},warned:e=>n.push(...e)},{projectDir:t}),{config:i}=r,a=new pL,o=new Tx(a,i.globals.default_empty_value??``,void 0,new DL);try{let s=XI(i,o,{cwd:t});n.push(...s.loadWarnings);let c=await o.settled(fH);return c.length>0&&n.push(`source${c.length===1?``:`s`} still running after ${fH} ms, rendered with fallback values: ${c.join(`, `)}`),{layers:e,droppedPlugins:[...r.installed.dropped,...r.layers.flatMap(e=>e.plugins.dropped)],config:i,compiled:s,store:a,registry:o}}catch(e){throw o.dispose(),e}}function _H({layers:e,config:t,compiled:n,store:r,registry:i},a,o){let s=new Map;return{rendered:tL(t,n,r,i,pH(a,e.at(-1)??null),MM(a,o),{onSegmentError:(e,t)=>s.set(`segment "${e}"`,t),onRenderWarning:e=>s.set(`theme rule`,e)},NM(a)),failures:s}}async function vH(e,t,n){let r=await gH(e,t,n),{config:i}=r;try{let e=eP();try{NN(i),Bj(i)}finally{e()}let t=pv(null,i.globals.preset,i.presets),n=(e,t)=>{let n=jM(i,t=>t===`preset`?e:null,()=>t),a;try{a=_H(r,n,200)}catch(e){a={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]])}}return{preset:e,customized:t,...a}},a=n(t,!1),o=[a,n(t,!0),...fv(i.presets).filter(e=>e!==t).flatMap(e=>[n(e,!1),n(e,!0)])],s=new Map;for(let{preset:e,customized:t,failures:n}of o)for(let[r,i]of n){let n=`${r}: ${i}`,a=s.get(n)??new Map;a.set(e,(a.get(e)??new Set).add(t)),s.set(n,a)}let c=[...s].map(([e,n])=>n.get(t)?.has(!1)?e:`${e} (under ${[...n].map(([e,n])=>[...e===t?[]:[`preset "${e}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`),l=a.rendered,u=r.droppedPlugins.length,d=[...u>0?[`${u} plugin${u===1?``:`s`} did not load (named in the warnings)`]:[],...c.length>0||l===void 0?[`config renders with ${c.length} render error${c.length===1?``:`s`} (the daemon would show them on the bar):\n`+c.map(e=>` ${e}`).join(`
220
+ `}function uH(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function dH(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function fH(){let e=mH();return e===null?null:r.readFileSync(e,`utf-8`)}function pH(){let e;try{e=fH()}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 mH(){let e=l.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let i=l.dirname(l.resolve(n));for(;;){let t=l.join(i,e);if(r.existsSync(t))return t;let n=l.dirname(i);if(n===i)return null;i=n}}function hH(e){let t=e.CC_CANDYBAR_CONFIG??``;return t===``?void 0:t}const gH=5e3;function _H(e,t){let n=`/home/tester`,r=Math.floor(Date.now()/1e3),i=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,a={current_dir:`${n}/code/cc-candybar/src`,project_dir:`${n}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:i,version:`1.15.0`,home:n,cwd:`${n}/code/cc-candybar/src`,transcript_path:`${n}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:a,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:r+2*3600},weekly:{percentage:21,resetsAt:r+5*86400},cache:{expiresAt:r+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:mC(4e5,1e6),...RM(e),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:Px(()=>!0),resumeCommand:PM(a,i,void 0),configPath:t??`${n}/.config/cc-candybar/config.json5`}}function vH(e,t){let n=ZE(e,e),r=eD(n);return r!==null&&t.push(r),n.kind===`chain`?n.layers:[]}async function yH(e,n=t.cwd()){let i=[],a=e===void 0?null:l.resolve(JE(e)),o=a===null?vH(n,i):[a];if(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 s=nD(n,n);s!==null&&i.push(s);try{return{kind:`clean`,layers:o,warnings:i,rendered:await SH(o,n,i)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&o.includes(t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof nc&&i.push(...e.warnings),{kind:`fatal`,layers:o,message:e instanceof nc||e instanceof Error?e.message:String(e),warnings:i})}}async function bH(e,t,n){let r=LD(e,oM,{entered:()=>{},warned:e=>n.push(...e)},{projectDir:t}),{config:i}=r,a=new _L,o=new Tx(a,i.globals.default_empty_value??``,void 0,new jL);try{let s=eL(i,o,{cwd:t});n.push(...s.loadWarnings);let c=await o.settled(gH);return c.length>0&&n.push(`source${c.length===1?``:`s`} still running after ${gH} ms, rendered with fallback values: ${c.join(`, `)}`),{layers:e,droppedPlugins:[...r.installed.dropped,...r.layers.flatMap(e=>e.plugins.dropped)],config:i,compiled:s,store:a,registry:o}}catch(e){throw o.dispose(),e}}function xH({layers:e,config:t,compiled:n,store:r,registry:i},a,o){let s=new Map;return{rendered:aL(t,n,r,i,_H(a,e.at(-1)??null),IM(a,o),{onSegmentError:(e,t)=>s.set(`segment "${e}"`,t),onRenderWarning:e=>s.set(`theme rule`,e)},LM(a)),failures:s}}async function SH(e,t,n){let r=await bH(e,t,n),{config:i}=r;try{let e=iP();try{LN(i),Wj(i)}finally{e()}let t=pv(null,i.globals.preset,i.presets),n=(e,t)=>{let n=FM(i,t=>t===`preset`?e:null,()=>t),a;try{a=xH(r,n,200)}catch(e){a={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]])}}return{preset:e,customized:t,...a}},a=n(t,!1),o=[a,n(t,!0),...fv(i.presets).filter(e=>e!==t).flatMap(e=>[n(e,!1),n(e,!0)])],s=new Map;for(let{preset:e,customized:t,failures:n}of o)for(let[r,i]of n){let n=`${r}: ${i}`,a=s.get(n)??new Map;a.set(e,(a.get(e)??new Set).add(t)),s.set(n,a)}let c=[...s].map(([e,n])=>n.get(t)?.has(!1)?e:`${e} (under ${[...n].map(([e,n])=>[...e===t?[]:[`preset "${e}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`),l=a.rendered,u=r.droppedPlugins.length,d=[...u>0?[`${u} plugin${u===1?``:`s`} did not load (named in the warnings)`]:[],...c.length>0||l===void 0?[`config renders with ${c.length} render error${c.length===1?``:`s`} (the daemon would show them on the bar):\n`+c.map(e=>` ${e}`).join(`
221
221
  `)]:[]];if(d.length>0||l===void 0)throw Error(d.join(`
222
- `));return l}finally{r.registry.dispose()}}function yH(e){return e.map(e=>`warning: ${e}\n`).join(``)}function bH(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.layers.join(` < `)||`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:yH(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:yH(e.warnings)+`✗ ${e.layers.join(` < `)||`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const xH=`--render`,SH=`Usage: cc-candybar check [${xH}] [config-file]\n`;function CH(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==xH);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${SH}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${SH}`}:{kind:`run`,target:n[0],render:t.includes(xH)}}async function wH(e){let n=CH(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:bH(await hH(n.target??dH(t.env)),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const TH=`${UA}${HA}`;function EH(e){return`${TH}⚠ cc-candybar: ${DH(e)}\n`}function DH(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: ${VA(e.message,60)}`;case`render_failed`:return`render failed: ${VA(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${VA(e.message,60)}`}}function OH(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
223
- `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:EH(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function kH(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 AH=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function jH(e,t,n){return{termCols:kH(e.COLUMNS,n.columns),termRows:kH(e.LINES,n.rows),ssh:AH.some(t=>(e[t]??``)!==``),tmux:kS(e),configEnv:dH(e),claudeConfigDir:rC(e,t),mementoEnv:$e(e,t)}}const MH=` (fix: click the settings menu (${El} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`;function NH({check:e,verdict:t}){return t.ok?`✓ ${e.label}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:MH}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)}function PH(e){let t=bL(e.projectDir,e.cwd,e.configFile??void 0,{sessionState:new DL});return t.state?.registry.dispose(),{layers:t.layers,error:t.error,warning:t.warning,unused:t.state?.unused??[]}}async function FH(e,t,n,r,i=void 0){let a;try{a={...fz(e,{tmux:kS(n),claudeConfigDir:rC(n,r)},{projectDir:r,cwd:r,configFile:JD(i??dH(n))??null}),urlHandler:await Oz(t)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let o=RS(a);return{stdout:o.map(NH).join(``),stderr:``,code:+!o.every(e=>e.verdict.ok)}}async function IH(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
222
+ `));return l}finally{r.registry.dispose()}}function CH(e){return e.map(e=>`warning: ${e}\n`).join(``)}function wH(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.layers.join(` < `)||`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:CH(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:CH(e.warnings)+`✗ ${e.layers.join(` < `)||`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const TH=`--render`,EH=`Usage: cc-candybar check [${TH}] [config-file]\n`;function DH(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==TH);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${EH}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${EH}`}:{kind:`run`,target:n[0],render:t.includes(TH)}}async function OH(e){let n=DH(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:wH(await yH(n.target??hH(t.env)),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const kH=`${qA}${KA}`;function AH(e){return`${kH}⚠ cc-candybar: ${jH(e)}\n`}function jH(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: ${GA(e.message,60)}`;case`render_failed`:return`render failed: ${GA(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${GA(e.message,60)}`}}function MH(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
223
+ `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:AH(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function NH(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 PH=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function FH(e,t,n){return{termCols:NH(e.COLUMNS,n.columns),termRows:NH(e.LINES,n.rows),ssh:PH.some(t=>(e[t]??``)!==``),tmux:kS(e),configEnv:hH(e),claudeConfigDir:rC(e,t),mementoEnv:$e(e,t)}}const IH=` (fix: click the settings menu (${El} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`;function LH({check:e,verdict:t}){return t.ok?`✓ ${e.label}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:IH}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)}function RH(e){let t=wL(e.projectDir,e.cwd,e.configFile??void 0,{sessionState:new jL});return t.state?.registry.dispose(),{layers:t.layers,error:t.error,warning:t.warning,unused:t.state?.unused??[]}}async function zH(e,t,n,r,i=void 0){let a;try{a={...gz(e,{tmux:kS(n),claudeConfigDir:rC(n,r)},{projectDir:r,cwd:r,configFile:QD(i??hH(n))??null}),urlHandler:await Mz(t)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let o=RS(a);return{stdout:o.map(LH).join(``),stderr:``,code:+!o.every(e=>e.verdict.ok)}}async function BH(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
224
224
  Usage: cc-candybar doctor [config-file]
225
- `),t.exit(2));let n=t.cwd(),r=await FH(sz(PH),Mz(),t.env,n,e[0]===void 0?void 0:l.resolve(n,KE(e[0])));t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const LH=e=>e.some(e=>t.argv.includes(e));function RH(){console.log(ES)}async function zH(){try{LH(wS.help)&&(RH(),t.exit(0)),LH(wS.version)&&(console.log(`cc-candybar ${dO}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await mA(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(lA(),t.exit(0)),e===`url-handle`){await dA(t.argv[3]);return}if(e===`daemon`){MV();return}if(e===`daemon-stats`&&(await hz(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){await wH(t.argv.slice(3));return}if(e===`schema`){lH();return}if(e===`doctor`){await IH(t.argv.slice(3));return}uV(e)&&(await eH(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
225
+ `),t.exit(2));let n=t.cwd(),r=await zH(dz(RH),Iz(),t.env,n,e[0]===void 0?void 0:l.resolve(n,JE(e[0])));t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const VH=e=>e.some(e=>t.argv.includes(e));function HH(){console.log(ES)}async function UH(){try{VH(wS.help)&&(HH(),t.exit(0)),VH(wS.version)&&(console.log(`cc-candybar ${hO}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await vA(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(pA(),t.exit(0)),e===`url-handle`){await hA(t.argv[3]);return}if(e===`daemon`){IV();return}if(e===`daemon-stats`&&(await yz(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){await OH(t.argv.slice(3));return}if(e===`schema`){pH();return}if(e===`doctor`){await BH(t.argv.slice(3));return}mV(e)&&(await iH(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
226
226
 
227
227
  cc-candybar is designed to be used as a Claude Code statusLine command.
228
228
  It reads hook data from stdin and outputs formatted statusline.
@@ -238,4 +238,4 @@ Add to ~/.claude/settings.json:
238
238
  Run with --help for more options.
239
239
 
240
240
  To test output manually:
241
- echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),O(`Working directory: ${t.cwd()}`),O(`Process args:`,t.argv);let r=await n(t.stdin);O(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),RH(),t.exit(1));let i=OH(await hO(r,t.argv,t.cwd(),jH(t.env,t.cwd(),t.stderr)));i.debug!==null&&O(i.debug),i.kick&&FO(),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)}}zH();export{};
241
+ echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),O(`Working directory: ${t.cwd()}`),O(`Process args:`,t.argv);let r=await n(t.stdin);O(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),HH(),t.exit(1));let i=MH(await yO(r,t.argv,t.cwd(),FH(t.env,t.cwd(),t.stderr)));i.debug!==null&&O(i.debug),i.kick&&zO(),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)}}UH();export{};